am 7cf05b15: am 2f0a1d66: am 7f6932df: am 35ab6119: am 3e03bf8a: am fd2dcf90: am f4770dcf: am 0de7c611: Validate asec names.
* commit '7cf05b15b76b91aa07182e86a730d7552b23130c':
Validate asec names.
diff --git a/Android.mk b/Android.mk
index 098c3d0..cecab1e 100644
--- a/Android.mk
+++ b/Android.mk
@@ -15,23 +15,34 @@
Devmapper.cpp \
ResponseCode.cpp \
Xwarp.cpp \
+ VoldUtil.c \
fstrim.c \
cryptfs.c
common_c_includes := \
$(KERNEL_HEADERS) \
system/extras/ext4_utils \
- external/openssl/include
+ external/openssl/include \
+ external/stlport/stlport \
+ bionic \
+ external/scrypt/lib/crypto
common_shared_libraries := \
libsysutils \
+ libstlport \
libcutils \
liblog \
libdiskconfig \
libhardware_legacy \
liblogwrap \
+ libext4_utils \
libcrypto
+common_static_libraries := \
+ libfs_mgr \
+ libscrypt_static \
+ libmincrypt
+
include $(CLEAR_VARS)
LOCAL_MODULE := libvold
@@ -42,7 +53,7 @@
LOCAL_SHARED_LIBRARIES := $(common_shared_libraries)
-LOCAL_STATIC_LIBRARIES := libfs_mgr
+LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
LOCAL_MODULE_TAGS := eng tests
@@ -62,7 +73,7 @@
LOCAL_SHARED_LIBRARIES := $(common_shared_libraries)
-LOCAL_STATIC_LIBRARIES := libfs_mgr
+LOCAL_STATIC_LIBRARIES := $(common_static_libraries)
include $(BUILD_EXECUTABLE)
diff --git a/CommandListener.cpp b/CommandListener.cpp
index f8baff5..049d42c 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -162,11 +162,16 @@
}
rc = vm->unmountVolume(argv[2], force, revert);
} else if (!strcmp(argv[1], "format")) {
- if (argc != 3) {
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: volume format <path>", false);
+ if (argc < 3 || argc > 4 ||
+ (argc == 4 && strcmp(argv[3], "wipe"))) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: volume format <path> [wipe]", false);
return 0;
}
- rc = vm->formatVolume(argv[2]);
+ bool wipe = false;
+ if (argc >= 4 && !strcmp(argv[3], "wipe")) {
+ wipe = true;
+ }
+ rc = vm->formatVolume(argv[2], wipe);
} else if (!strcmp(argv[1], "share")) {
if (argc != 4) {
cli->sendMsg(ResponseCode::CommandSyntaxError,
@@ -197,6 +202,12 @@
(enabled ? "Share enabled" : "Share disabled"), false);
}
return 0;
+ } else if (!strcmp(argv[1], "mkdirs")) {
+ if (argc != 3) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: volume mkdirs <path>", false);
+ return 0;
+ }
+ rc = vm->mkdirs(argv[2]);
} else {
cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown volume cmd", false);
}
@@ -598,6 +609,25 @@
}
SLOGD("cryptfs verifypw {}");
rc = cryptfs_verify_passwd(argv[2]);
+ } else if (!strcmp(argv[1], "getfield")) {
+ char valbuf[PROPERTY_VALUE_MAX];
+
+ if (argc != 3) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs getfield <fieldname>", false);
+ return 0;
+ }
+ dumpArgs(argc, argv, -1);
+ rc = cryptfs_getfield(argv[2], valbuf, sizeof(valbuf));
+ if (rc == 0) {
+ cli->sendMsg(ResponseCode::CryptfsGetfieldResult, valbuf, false);
+ }
+ } else if (!strcmp(argv[1], "setfield")) {
+ if (argc != 4) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs setfield <fieldname> <value>", false);
+ return 0;
+ }
+ dumpArgs(argc, argv, -1);
+ rc = cryptfs_setfield(argv[2], argv[3]);
} else {
dumpArgs(argc, argv, -1);
cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown cryptfs cmd", false);
diff --git a/DirectVolume.cpp b/DirectVolume.cpp
index 2a24376..960eef6 100644
--- a/DirectVolume.cpp
+++ b/DirectVolume.cpp
@@ -33,11 +33,8 @@
// #define PARTITION_DEBUG
-DirectVolume::DirectVolume(VolumeManager *vm, const char *label,
- const char *mount_point, int partIdx) :
- Volume(vm, label, mount_point) {
- mPartIdx = partIdx;
-
+DirectVolume::DirectVolume(VolumeManager *vm, const fstab_rec* rec, int flags) :
+ Volume(vm, rec, flags) {
mPaths = new PathCollection();
for (int i = 0; i < MAX_PARTITIONS; i++)
mPartMinors[i] = -1;
@@ -46,6 +43,18 @@
mDiskMinor = -1;
mDiskNumParts = 0;
+ if (strcmp(rec->mount_point, "auto") != 0) {
+ ALOGE("Vold managed volumes must have auto mount point; ignoring %s",
+ rec->mount_point);
+ }
+
+ char mount[PATH_MAX];
+
+ snprintf(mount, PATH_MAX, "%s/%s", Volume::MEDIA_DIR, rec->label);
+ mMountpoint = strdup(mount);
+ snprintf(mount, PATH_MAX, "%s/%s", Volume::FUSE_DIR, rec->label);
+ mFuseMountpoint = strdup(mount);
+
setState(Volume::State_NoMedia);
}
@@ -62,10 +71,6 @@
return 0;
}
-void DirectVolume::setFlags(int flags) {
- mFlags = flags;
-}
-
dev_t DirectVolume::getDiskDevice() {
return MKDEV(mDiskMajor, mDiskMinor);
}
@@ -119,7 +124,7 @@
snprintf(msg, sizeof(msg),
"Volume %s %s disk inserted (%d:%d)", getLabel(),
- getMountpoint(), mDiskMajor, mDiskMinor);
+ getFuseMountpoint(), mDiskMajor, mDiskMinor);
mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeDiskInserted,
msg, false);
}
@@ -286,7 +291,7 @@
SLOGD("Volume %s %s disk %d:%d removed\n", getLabel(), getMountpoint(), major, minor);
snprintf(msg, sizeof(msg), "Volume %s %s disk removed (%d:%d)",
- getLabel(), getMountpoint(), major, minor);
+ getLabel(), getFuseMountpoint(), major, minor);
mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeDiskRemoved,
msg, false);
setState(Volume::State_NoMedia);
@@ -316,15 +321,16 @@
* Yikes, our mounted partition is going away!
*/
- snprintf(msg, sizeof(msg), "Volume %s %s bad removal (%d:%d)",
- getLabel(), getMountpoint(), major, minor);
- mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
- msg, false);
-
- if (mVm->cleanupAsec(this, true)) {
+ bool providesAsec = (getFlags() & VOL_PROVIDES_ASEC) != 0;
+ if (providesAsec && mVm->cleanupAsec(this, true)) {
SLOGE("Failed to cleanup ASEC - unmount will probably fail!");
}
+ snprintf(msg, sizeof(msg), "Volume %s %s bad removal (%d:%d)",
+ getLabel(), getFuseMountpoint(), major, minor);
+ mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
+ msg, false);
+
if (Volume::unmountVol(true, false)) {
SLOGE("Failed to unmount volume on bad removal (%s)",
strerror(errno));
@@ -452,7 +458,7 @@
{
strcpy(v->label, mLabel);
strcpy(v->mnt_point, mMountpoint);
- v->flags=mFlags;
+ v->flags = getFlags();
/* Other fields of struct volume_info are filled in by the caller or cryptfs.c */
return 0;
diff --git a/DirectVolume.h b/DirectVolume.h
index c0139d4..7be133f 100644
--- a/DirectVolume.h
+++ b/DirectVolume.h
@@ -29,6 +29,9 @@
public:
static const int MAX_PARTITIONS = 32;
protected:
+ const char* mMountpoint;
+ const char* mFuseMountpoint;
+
PathCollection *mPaths;
int mDiskMajor;
int mDiskMinor;
@@ -39,28 +42,28 @@
int mDiskNumParts;
unsigned int mPendingPartMap;
int mIsDecrypted;
- int mFlags;
public:
- DirectVolume(VolumeManager *vm, const char *label, const char *mount_point, int partIdx);
+ DirectVolume(VolumeManager *vm, const fstab_rec* rec, int flags);
virtual ~DirectVolume();
int addPath(const char *path);
+ const char *getMountpoint() { return mMountpoint; }
+ const char *getFuseMountpoint() { return mFuseMountpoint; }
+
int handleBlockEvent(NetlinkEvent *evt);
dev_t getDiskDevice();
dev_t getShareDevice();
void handleVolumeShared();
void handleVolumeUnshared();
int getVolInfo(struct volume_info *v);
- void setFlags(int flags);
protected:
int getDeviceNodes(dev_t *devs, int max);
int updateDeviceInfo(char *new_path, int new_major, int new_minor);
virtual void revertDeviceInfo(void);
int isDecrypted() { return mIsDecrypted; }
- int getFlags() { return mFlags; }
private:
void handleDiskAdded(const char *devpath, NetlinkEvent *evt);
diff --git a/Fat.cpp b/Fat.cpp
index 807f440..c967a90 100644
--- a/Fat.cpp
+++ b/Fat.cpp
@@ -30,6 +30,8 @@
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/wait.h>
+#include <linux/fs.h>
+#include <sys/ioctl.h>
#include <linux/kdev_t.h>
@@ -167,12 +169,16 @@
return rc;
}
-int Fat::format(const char *fsPath, unsigned int numSectors) {
+int Fat::format(const char *fsPath, unsigned int numSectors, bool wipe) {
int fd;
const char *args[10];
int rc;
int status;
+ if (wipe) {
+ Fat::wipe(fsPath, numSectors);
+ }
+
args[0] = MKDOSFS_PATH;
args[1] = "-F";
args[2] = "32";
@@ -220,3 +226,30 @@
}
return 0;
}
+
+void Fat::wipe(const char *fsPath, unsigned int numSectors) {
+ int fd;
+ unsigned long long range[2];
+
+ fd = open(fsPath, O_RDWR);
+ if (fd >= 0) {
+ if (numSectors == 0) {
+ numSectors = get_blkdev_size(fd);
+ }
+ if (numSectors == 0) {
+ SLOGE("Fat wipe failed to determine size of %s", fsPath);
+ close(fd);
+ return;
+ }
+ range[0] = 0;
+ range[1] = (unsigned long long)numSectors * 512;
+ if (ioctl(fd, BLKDISCARD, &range) < 0) {
+ SLOGE("Fat wipe failed to discard blocks on %s", fsPath);
+ } else {
+ SLOGI("Fat wipe %d sectors on %s succeeded", numSectors, fsPath);
+ }
+ close(fd);
+ } else {
+ SLOGE("Fat wipe failed to open device %s", fsPath);
+ }
+}
diff --git a/Fat.h b/Fat.h
index e02d88c..19614d1 100644
--- a/Fat.h
+++ b/Fat.h
@@ -26,7 +26,10 @@
bool ro, bool remount, bool executable,
int ownerUid, int ownerGid, int permMask,
bool createLost);
- static int format(const char *fsPath, unsigned int numSectors);
+ static int format(const char *fsPath, unsigned int numSectors, bool wipe);
+
+private:
+ static void wipe(const char *fsPath, unsigned int numSectors);
};
#endif
diff --git a/ResponseCode.h b/ResponseCode.h
index 402e35b..5e4c6fa 100644
--- a/ResponseCode.h
+++ b/ResponseCode.h
@@ -26,6 +26,7 @@
static const int VolumeListResult = 110;
static const int AsecListResult = 111;
static const int StorageUsersListResult = 112;
+ static const int CryptfsGetfieldResult = 113;
// 200 series - Requested action has been successfully completed
static const int CommandOkay = 200;
@@ -56,6 +57,8 @@
static const int VolumeMountFailedBlank = 610;
static const int VolumeMountFailedDamaged = 611;
static const int VolumeMountFailedNoMedia = 612;
+ static const int VolumeUuidChange = 613;
+ static const int VolumeUserLabelChange = 614;
static const int ShareAvailabilityChange = 620;
diff --git a/VoldUtil.c b/VoldUtil.c
new file mode 100644
index 0000000..b5f9946
--- /dev/null
+++ b/VoldUtil.c
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <sys/ioctl.h>
+#include <linux/fs.h>
+
+unsigned int get_blkdev_size(int fd)
+{
+ unsigned int nr_sec;
+
+ if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
+ nr_sec = 0;
+ }
+
+ return nr_sec;
+}
diff --git a/VoldUtil.h b/VoldUtil.h
index 30a3add..469489a 100644
--- a/VoldUtil.h
+++ b/VoldUtil.h
@@ -17,6 +17,12 @@
#ifndef _VOLDUTIL_H
#define _VOLDUTIL_H
+#include <sys/cdefs.h>
+
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a)))
+__BEGIN_DECLS
+ unsigned int get_blkdev_size(int fd);
+__END_DECLS
+
#endif
diff --git a/Volume.cpp b/Volume.cpp
index 4a00ccc..6dd1cc0 100644
--- a/Volume.cpp
+++ b/Volume.cpp
@@ -37,8 +37,11 @@
#define LOG_TAG "Vold"
+#include <cutils/fs.h>
#include <cutils/log.h>
+#include <string>
+
#include "Volume.h"
#include "VolumeManager.h"
#include "ResponseCode.h"
@@ -51,21 +54,14 @@
/*
- * Secure directory - stuff that only root can see
+ * Media directory - stuff that only media_rw user can see
*/
-const char *Volume::SECDIR = "/mnt/secure";
+const char *Volume::MEDIA_DIR = "/mnt/media_rw";
/*
- * Secure staging directory - where media is mounted for preparation
+ * Fuse directory - location where fuse wrapped filesystems go
*/
-const char *Volume::SEC_STGDIR = "/mnt/secure/staging";
-
-/*
- * Path to the directory on the media which contains publicly accessable
- * asec imagefiles. This path will be obscured before the mount is
- * exposed to non priviledged users.
- */
-const char *Volume::SEC_STG_SECIMGDIR = "/mnt/secure/staging/.android_secure";
+const char *Volume::FUSE_DIR = "/storage";
/*
* Path to external storage where *only* root can access ASEC image files
@@ -76,6 +72,7 @@
* Path to internal storage where *only* root can access ASEC image files
*/
const char *Volume::SEC_ASECDIR_INT = "/data/app-asec";
+
/*
* Path to where secure containers are mounted
*/
@@ -86,6 +83,8 @@
*/
const char *Volume::LOOPDIR = "/mnt/obb";
+const char *Volume::BLKID_PATH = "/system/bin/blkid";
+
static const char *stateToStr(int state) {
if (state == Volume::State_Init)
return "Initializing";
@@ -111,39 +110,23 @@
return "Unknown-Error";
}
-Volume::Volume(VolumeManager *vm, const char *label, const char *mount_point) {
+Volume::Volume(VolumeManager *vm, const fstab_rec* rec, int flags) {
mVm = vm;
mDebug = false;
- mLabel = strdup(label);
- mMountpoint = strdup(mount_point);
+ mLabel = strdup(rec->label);
+ mUuid = NULL;
+ mUserLabel = NULL;
mState = Volume::State_Init;
+ mFlags = flags;
mCurrentlyMountedKdev = -1;
- mPartIdx = -1;
+ mPartIdx = rec->partnum;
mRetryMount = false;
}
Volume::~Volume() {
free(mLabel);
- free(mMountpoint);
-}
-
-void Volume::protectFromAutorunStupidity() {
- char filename[255];
-
- snprintf(filename, sizeof(filename), "%s/autorun.inf", SEC_STGDIR);
- if (!access(filename, F_OK)) {
- SLOGW("Volume contains an autorun.inf! - removing");
- /*
- * Ensure the filename is all lower-case so
- * the process killer can find the inode.
- * Probably being paranoid here but meh.
- */
- rename(filename, filename);
- Process::killProcessesWithOpenFiles(filename, 2);
- if (unlink(filename)) {
- SLOGE("Failed to remove %s (%s)", filename, strerror(errno));
- }
- }
+ free(mUuid);
+ free(mUserLabel);
}
void Volume::setDebug(bool enable) {
@@ -169,6 +152,46 @@
return -1;
}
+void Volume::setUuid(const char* uuid) {
+ char msg[256];
+
+ if (mUuid) {
+ free(mUuid);
+ }
+
+ if (uuid) {
+ mUuid = strdup(uuid);
+ snprintf(msg, sizeof(msg), "%s %s \"%s\"", getLabel(),
+ getFuseMountpoint(), mUuid);
+ } else {
+ mUuid = NULL;
+ snprintf(msg, sizeof(msg), "%s %s", getLabel(), getFuseMountpoint());
+ }
+
+ mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeUuidChange, msg,
+ false);
+}
+
+void Volume::setUserLabel(const char* userLabel) {
+ char msg[256];
+
+ if (mUserLabel) {
+ free(mUserLabel);
+ }
+
+ if (userLabel) {
+ mUserLabel = strdup(userLabel);
+ snprintf(msg, sizeof(msg), "%s %s \"%s\"", getLabel(),
+ getFuseMountpoint(), mUserLabel);
+ } else {
+ mUserLabel = NULL;
+ snprintf(msg, sizeof(msg), "%s %s", getLabel(), getFuseMountpoint());
+ }
+
+ mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeUserLabelChange,
+ msg, false);
+}
+
void Volume::setState(int state) {
char msg[255];
int oldState = mState;
@@ -188,7 +211,7 @@
oldState, stateToStr(oldState), mState, stateToStr(mState));
snprintf(msg, sizeof(msg),
"Volume %s %s state changed from %d (%s) to %d (%s)", getLabel(),
- getMountpoint(), oldState, stateToStr(oldState), mState,
+ getFuseMountpoint(), oldState, stateToStr(oldState), mState,
stateToStr(mState));
mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeStateChange,
@@ -206,7 +229,7 @@
return 0;
}
-int Volume::formatVol() {
+int Volume::formatVol(bool wipe) {
if (getState() == Volume::State_NoMedia) {
errno = ENODEV;
@@ -227,7 +250,9 @@
bool formatEntireDevice = (mPartIdx == -1);
char devicePath[255];
dev_t diskNode = getDiskDevice();
- dev_t partNode = MKDEV(MAJOR(diskNode), (formatEntireDevice ? 1 : mPartIdx));
+ dev_t partNode =
+ MKDEV(MAJOR(diskNode),
+ MINOR(diskNode) + (formatEntireDevice ? 1 : mPartIdx));
setState(Volume::State_Formatting);
@@ -250,7 +275,7 @@
SLOGI("Formatting volume %s (%s)", getLabel(), devicePath);
}
- if (Fat::format(devicePath, 0)) {
+ if (Fat::format(devicePath, 0, wipe)) {
SLOGE("Failed to format (%s)", strerror(errno));
goto err;
}
@@ -281,7 +306,6 @@
fclose(fp);
return true;
}
-
}
fclose(fp);
@@ -292,12 +316,15 @@
dev_t deviceNodes[4];
int n, i, rc = 0;
char errmsg[255];
- const char* externalStorage = getenv("EXTERNAL_STORAGE");
- bool primaryStorage = externalStorage && !strcmp(getMountpoint(), externalStorage);
+
+ int flags = getFlags();
+ bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
+
+ // TODO: handle "bind" style mounts, for emulated storage
+
char decrypt_state[PROPERTY_VALUE_MAX];
char crypto_state[PROPERTY_VALUE_MAX];
char encrypt_progress[PROPERTY_VALUE_MAX];
- int flags;
property_get("vold.decrypt", decrypt_state, "");
property_get("vold.encrypt_progress", encrypt_progress, "");
@@ -306,10 +333,10 @@
* or are in the process of encrypting.
*/
if ((getState() == Volume::State_NoMedia) ||
- ((!strcmp(decrypt_state, "1") || encrypt_progress[0]) && primaryStorage)) {
+ ((!strcmp(decrypt_state, "1") || encrypt_progress[0]) && providesAsec)) {
snprintf(errmsg, sizeof(errmsg),
"Volume %s %s mount failed - no media",
- getLabel(), getMountpoint());
+ getLabel(), getFuseMountpoint());
mVm->getBroadcaster()->sendBroadcast(
ResponseCode::VolumeMountFailedNoMedia,
errmsg, false);
@@ -337,13 +364,12 @@
}
/* If we're running encrypted, and the volume is marked as encryptable and nonremovable,
- * and vold is asking to mount the primaryStorage device, then we need to decrypt
+ * and also marked as providing Asec storage, then we need to decrypt
* that partition, and update the volume object to point to it's new decrypted
* block device
*/
property_get("ro.crypto.state", crypto_state, "");
- flags = getFlags();
- if (primaryStorage &&
+ if (providesAsec &&
((flags & (VOL_NONREMOVABLE | VOL_ENCRYPTABLE))==(VOL_NONREMOVABLE | VOL_ENCRYPTABLE)) &&
!strcmp(crypto_state, "encrypted") && !isDecrypted()) {
char new_sys_path[MAXPATHLEN];
@@ -409,49 +435,28 @@
return -1;
}
- /*
- * Mount the device on our internal staging mountpoint so we can
- * muck with it before exposing it to non priviledged users.
- */
errno = 0;
int gid;
- if (primaryStorage) {
- // Special case the primary SD card.
- // For this we grant write access to the SDCARD_RW group.
- gid = AID_SDCARD_RW;
- } else {
- // For secondary external storage we keep things locked up.
- gid = AID_MEDIA_RW;
- }
- if (Fat::doMount(devicePath, "/mnt/secure/staging", false, false, false,
- AID_SYSTEM, gid, 0702, true)) {
+ if (Fat::doMount(devicePath, getMountpoint(), false, false, false,
+ AID_MEDIA_RW, AID_MEDIA_RW, 0007, true)) {
SLOGE("%s failed to mount via VFAT (%s)\n", devicePath, strerror(errno));
continue;
}
- SLOGI("Device %s, target %s mounted @ /mnt/secure/staging", devicePath, getMountpoint());
+ extractMetadata(devicePath);
- protectFromAutorunStupidity();
-
- // only create android_secure on primary storage
- if (primaryStorage && createBindMounts()) {
- SLOGE("Failed to create bindmounts (%s)", strerror(errno));
- umount("/mnt/secure/staging");
+ if (providesAsec && mountAsecExternal() != 0) {
+ SLOGE("Failed to mount secure area (%s)", strerror(errno));
+ umount(getMountpoint());
setState(Volume::State_Idle);
return -1;
}
- /*
- * Now that the bindmount trickery is done, atomically move the
- * whole subtree to expose it to non priviledged users.
- */
- if (doMoveMount("/mnt/secure/staging", getMountpoint(), false)) {
- SLOGE("Failed to move mount (%s)", strerror(errno));
- umount("/mnt/secure/staging");
- setState(Volume::State_Idle);
- return -1;
- }
+ char service[64];
+ snprintf(service, 64, "fuse_%s", getLabel());
+ property_set("ctl.start", service);
+
setState(Volume::State_Mounted);
mCurrentlyMountedKdev = deviceNodes[i];
return 0;
@@ -463,103 +468,34 @@
return -1;
}
-int Volume::createBindMounts() {
- unsigned long flags;
+int Volume::mountAsecExternal() {
+ char legacy_path[PATH_MAX];
+ char secure_path[PATH_MAX];
- /*
- * Rename old /android_secure -> /.android_secure
- */
- if (!access("/mnt/secure/staging/android_secure", R_OK | X_OK) &&
- access(SEC_STG_SECIMGDIR, R_OK | X_OK)) {
- if (rename("/mnt/secure/staging/android_secure", SEC_STG_SECIMGDIR)) {
+ snprintf(legacy_path, PATH_MAX, "%s/android_secure", getMountpoint());
+ snprintf(secure_path, PATH_MAX, "%s/.android_secure", getMountpoint());
+
+ // Recover legacy secure path
+ if (!access(legacy_path, R_OK | X_OK) && access(secure_path, R_OK | X_OK)) {
+ if (rename(legacy_path, secure_path)) {
SLOGE("Failed to rename legacy asec dir (%s)", strerror(errno));
}
}
- /*
- * Ensure that /android_secure exists and is a directory
- */
- if (access(SEC_STG_SECIMGDIR, R_OK | X_OK)) {
- if (errno == ENOENT) {
- if (mkdir(SEC_STG_SECIMGDIR, 0777)) {
- SLOGE("Failed to create %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
- return -1;
- }
- } else {
- SLOGE("Failed to access %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
- return -1;
- }
- } else {
- struct stat sbuf;
-
- if (stat(SEC_STG_SECIMGDIR, &sbuf)) {
- SLOGE("Failed to stat %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
- return -1;
- }
- if (!S_ISDIR(sbuf.st_mode)) {
- SLOGE("%s is not a directory", SEC_STG_SECIMGDIR);
- errno = ENOTDIR;
- return -1;
- }
- }
-
- /*
- * Bind mount /mnt/secure/staging/android_secure -> /mnt/secure/asec so we'll
- * have a root only accessable mountpoint for it.
- */
- if (mount(SEC_STG_SECIMGDIR, SEC_ASECDIR_EXT, "", MS_BIND, NULL)) {
- SLOGE("Failed to bind mount points %s -> %s (%s)",
- SEC_STG_SECIMGDIR, SEC_ASECDIR_EXT, strerror(errno));
+ if (fs_prepare_dir(secure_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
+ SLOGW("fs_prepare_dir failed: %s", strerror(errno));
return -1;
}
- /*
- * Mount a read-only, zero-sized tmpfs on <mountpoint>/android_secure to
- * obscure the underlying directory from everybody - sneaky eh? ;)
- */
- if (mount("tmpfs", SEC_STG_SECIMGDIR, "tmpfs", MS_RDONLY, "size=0,mode=000,uid=0,gid=0")) {
- SLOGE("Failed to obscure %s (%s)", SEC_STG_SECIMGDIR, strerror(errno));
- umount("/mnt/asec_secure");
+ if (mount(secure_path, SEC_ASECDIR_EXT, "", MS_BIND, NULL)) {
+ SLOGE("Failed to bind mount points %s -> %s (%s)", secure_path,
+ SEC_ASECDIR_EXT, strerror(errno));
return -1;
}
return 0;
}
-int Volume::doMoveMount(const char *src, const char *dst, bool force) {
- unsigned int flags = MS_MOVE;
- int retries = 5;
-
- while(retries--) {
- if (!mount(src, dst, "", flags, NULL)) {
- if (mDebug) {
- SLOGD("Moved mount %s -> %s sucessfully", src, dst);
- }
- return 0;
- } else if (errno != EBUSY) {
- SLOGE("Failed to move mount %s -> %s (%s)", src, dst, strerror(errno));
- return -1;
- }
- int action = 0;
-
- if (force) {
- if (retries == 1) {
- action = 2; // SIGKILL
- } else if (retries == 2) {
- action = 1; // SIGHUP
- }
- }
- SLOGW("Failed to move %s -> %s (%s, retries %d, action %d)",
- src, dst, strerror(errno), retries, action);
- Process::killProcessesWithOpenFiles(src, action);
- usleep(1000*250);
- }
-
- errno = EBUSY;
- SLOGE("Giving up on move %s -> %s (%s)", src, dst, strerror(errno));
- return -1;
-}
-
int Volume::doUnmount(const char *path, bool force) {
int retries = 10;
@@ -597,6 +533,9 @@
int Volume::unmountVol(bool force, bool revert) {
int i, rc;
+ int flags = getFlags();
+ bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
+
if (getState() != Volume::State_Mounted) {
SLOGE("Volume %s unmount request when not mounted", getLabel());
errno = EINVAL;
@@ -606,35 +545,32 @@
setState(Volume::State_Unmounting);
usleep(1000 * 1000); // Give the framework some time to react
- /*
- * Remove the bindmount we were using to keep a reference to
- * the previously obscured directory.
- */
- if (doUnmount(Volume::SEC_ASECDIR_EXT, force)) {
- SLOGE("Failed to remove bindmount on %s (%s)", SEC_ASECDIR_EXT, strerror(errno));
- goto fail_remount_tmpfs;
+ char service[64];
+ snprintf(service, 64, "fuse_%s", getLabel());
+ property_set("ctl.stop", service);
+ /* Give it a chance to stop. I wish we had a synchronous way to determine this... */
+ sleep(1);
+
+ // TODO: determine failure mode if FUSE times out
+
+ if (providesAsec && doUnmount(Volume::SEC_ASECDIR_EXT, force) != 0) {
+ SLOGE("Failed to unmount secure area on %s (%s)", getMountpoint(), strerror(errno));
+ goto out_mounted;
}
- /*
- * Unmount the tmpfs which was obscuring the asec image directory
- * from non root users
- */
- char secure_dir[PATH_MAX];
- snprintf(secure_dir, PATH_MAX, "%s/.android_secure", getMountpoint());
- if (doUnmount(secure_dir, force)) {
- SLOGE("Failed to unmount tmpfs on %s (%s)", secure_dir, strerror(errno));
- goto fail_republish;
+ /* Now that the fuse daemon is dead, unmount it */
+ if (doUnmount(getFuseMountpoint(), force) != 0) {
+ SLOGE("Failed to unmount %s (%s)", getFuseMountpoint(), strerror(errno));
+ goto fail_remount_secure;
}
- /*
- * Finally, unmount the actual block device from the staging dir
- */
- if (doUnmount(getMountpoint(), force)) {
- SLOGE("Failed to unmount %s (%s)", SEC_STGDIR, strerror(errno));
- goto fail_recreate_bindmount;
+ /* Unmount the real sd card */
+ if (doUnmount(getMountpoint(), force) != 0) {
+ SLOGE("Failed to unmount %s (%s)", getMountpoint(), strerror(errno));
+ goto fail_remount_secure;
}
- SLOGI("%s unmounted sucessfully", getMountpoint());
+ SLOGI("%s unmounted successfully", getMountpoint());
/* If this is an encrypted volume, and we've been asked to undo
* the crypto mapping, then revert the dm-crypt mapping, and revert
@@ -646,29 +582,19 @@
SLOGI("Encrypted volume %s reverted successfully", getMountpoint());
}
+ setUuid(NULL);
+ setUserLabel(NULL);
setState(Volume::State_Idle);
mCurrentlyMountedKdev = -1;
return 0;
- /*
- * Failure handling - try to restore everything back the way it was
- */
-fail_recreate_bindmount:
- if (mount(SEC_STG_SECIMGDIR, SEC_ASECDIR_EXT, "", MS_BIND, NULL)) {
- SLOGE("Failed to restore bindmount after failure! - Storage will appear offline!");
- goto out_nomedia;
- }
-fail_remount_tmpfs:
- if (mount("tmpfs", SEC_STG_SECIMGDIR, "tmpfs", MS_RDONLY, "size=0,mode=0,uid=0,gid=0")) {
- SLOGE("Failed to restore tmpfs after failure! - Storage will appear offline!");
- goto out_nomedia;
- }
-fail_republish:
- if (doMoveMount(SEC_STGDIR, getMountpoint(), force)) {
- SLOGE("Failed to republish mount after failure! - Storage will appear offline!");
+fail_remount_secure:
+ if (providesAsec && mountAsecExternal() != 0) {
+ SLOGE("Failed to remount secure area (%s)", strerror(errno));
goto out_nomedia;
}
+out_mounted:
setState(Volume::State_Mounted);
return -1;
@@ -676,6 +602,7 @@
setState(Volume::State_NoMedia);
return -1;
}
+
int Volume::initializeMbr(const char *deviceNode) {
struct disk_info dinfo;
@@ -715,3 +642,56 @@
return rc;
}
+
+/*
+ * Use blkid to extract UUID and label from device, since it handles many
+ * obscure edge cases around partition types and formats. Always broadcasts
+ * updated metadata values.
+ */
+int Volume::extractMetadata(const char* devicePath) {
+ int res = 0;
+
+ std::string cmd;
+ cmd = BLKID_PATH;
+ cmd += " -c /dev/null ";
+ cmd += devicePath;
+
+ FILE* fp = popen(cmd.c_str(), "r");
+ if (!fp) {
+ ALOGE("Failed to run %s: %s", cmd.c_str(), strerror(errno));
+ res = -1;
+ goto done;
+ }
+
+ char line[1024];
+ char value[128];
+ if (fgets(line, sizeof(line), fp) != NULL) {
+ ALOGD("blkid identified as %s", line);
+
+ char* start = strstr(line, "UUID=");
+ if (start != NULL && sscanf(start + 5, "\"%127[^\"]\"", value) == 1) {
+ setUuid(value);
+ } else {
+ setUuid(NULL);
+ }
+
+ start = strstr(line, "LABEL=");
+ if (start != NULL && sscanf(start + 6, "\"%127[^\"]\"", value) == 1) {
+ setUserLabel(value);
+ } else {
+ setUserLabel(NULL);
+ }
+ } else {
+ ALOGW("blkid failed to identify %s", devicePath);
+ res = -1;
+ }
+
+ pclose(fp);
+
+done:
+ if (res == -1) {
+ setUuid(NULL);
+ setUserLabel(NULL);
+ }
+ return res;
+}
diff --git a/Volume.h b/Volume.h
index c717d4d..1444ed3 100644
--- a/Volume.h
+++ b/Volume.h
@@ -18,6 +18,7 @@
#define _VOLUME_H
#include <utils/List.h>
+#include <fs_mgr.h>
class NetlinkEvent;
class VolumeManager;
@@ -25,6 +26,7 @@
class Volume {
private:
int mState;
+ int mFlags;
public:
static const int State_Init = -1;
@@ -38,18 +40,18 @@
static const int State_Shared = 7;
static const int State_SharedMnt = 8;
- static const char *SECDIR;
- static const char *SEC_STGDIR;
- static const char *SEC_STG_SECIMGDIR;
+ static const char *MEDIA_DIR;
+ static const char *FUSE_DIR;
static const char *SEC_ASECDIR_EXT;
static const char *SEC_ASECDIR_INT;
static const char *ASECDIR;
-
static const char *LOOPDIR;
+ static const char *BLKID_PATH;
protected:
- char *mLabel;
- char *mMountpoint;
+ char* mLabel;
+ char* mUuid;
+ char* mUserLabel;
VolumeManager *mVm;
bool mDebug;
int mPartIdx;
@@ -62,16 +64,22 @@
dev_t mCurrentlyMountedKdev;
public:
- Volume(VolumeManager *vm, const char *label, const char *mount_point);
+ Volume(VolumeManager *vm, const fstab_rec* rec, int flags);
virtual ~Volume();
int mountVol();
int unmountVol(bool force, bool revert);
- int formatVol();
+ int formatVol(bool wipe);
- const char *getLabel() { return mLabel; }
- const char *getMountpoint() { return mMountpoint; }
+ const char* getLabel() { return mLabel; }
+ const char* getUuid() { return mUuid; }
+ const char* getUserLabel() { return mUserLabel; }
int getState() { return mState; }
+ int getFlags() { return mFlags; };
+
+ /* Mountpoint of the raw volume */
+ virtual const char *getMountpoint() = 0;
+ virtual const char *getFuseMountpoint() = 0;
virtual int handleBlockEvent(NetlinkEvent *evt);
virtual dev_t getDiskDevice();
@@ -83,23 +91,23 @@
virtual int getVolInfo(struct volume_info *v) = 0;
protected:
+ void setUuid(const char* uuid);
+ void setUserLabel(const char* userLabel);
void setState(int state);
virtual int getDeviceNodes(dev_t *devs, int max) = 0;
virtual int updateDeviceInfo(char *new_path, int new_major, int new_minor) = 0;
virtual void revertDeviceInfo(void) = 0;
virtual int isDecrypted(void) = 0;
- virtual int getFlags(void) = 0;
int createDeviceNode(const char *path, int major, int minor);
private:
int initializeMbr(const char *deviceNode);
bool isMountpointMounted(const char *path);
- int createBindMounts();
+ int mountAsecExternal();
int doUnmount(const char *path, bool force);
- int doMoveMount(const char *src, const char *dst, bool force);
- void protectFromAutorunStupidity();
+ int extractMetadata(const char* devicePath);
};
typedef android::List<Volume *> VolumeCollection;
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 70f2b13..f2d4e55 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -32,6 +32,7 @@
#include <openssl/md5.h>
+#include <cutils/fs.h>
#include <cutils/log.h>
#include <sysutils/NetlinkEvent.h>
@@ -158,7 +159,7 @@
for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
char *buffer;
asprintf(&buffer, "%s %s %d",
- (*i)->getLabel(), (*i)->getMountpoint(),
+ (*i)->getLabel(), (*i)->getFuseMountpoint(),
(*i)->getState());
cli->sendMsg(ResponseCode::VolumeListResult, buffer, false);
free(buffer);
@@ -167,7 +168,7 @@
return 0;
}
-int VolumeManager::formatVolume(const char *label) {
+int VolumeManager::formatVolume(const char *label, bool wipe) {
Volume *v = lookupVolume(label);
if (!v) {
@@ -180,7 +181,7 @@
return -1;
}
- return v->formatVol();
+ return v->formatVol(wipe);
}
int VolumeManager::getObbMountPath(const char *sourceFile, char *mountPath, int mountPathLen) {
@@ -432,7 +433,7 @@
if (usingExt4) {
formatStatus = Ext4::format(dmDevice, mountPoint);
} else {
- formatStatus = Fat::format(dmDevice, numImgSectors);
+ formatStatus = Fat::format(dmDevice, numImgSectors, 0);
}
if (formatStatus < 0) {
@@ -1151,7 +1152,7 @@
VolumeCollection::iterator i;
for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
- const char* mountPoint = (*i)->getMountpoint();
+ const char* mountPoint = (*i)->getFuseMountpoint();
if (!strncmp(fileName, mountPoint, strlen(mountPoint))) {
return *i;
}
@@ -1609,7 +1610,7 @@
for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
if (label[0] == '/') {
- if (!strcmp(label, (*i)->getMountpoint()))
+ if (!strcmp(label, (*i)->getFuseMountpoint()))
return (*i);
} else {
if (!strcmp(label, (*i)->getLabel()))
@@ -1646,28 +1647,49 @@
}
int VolumeManager::cleanupAsec(Volume *v, bool force) {
- int rc = unmountAllAsecsInDir(Volume::SEC_ASECDIR_EXT);
+ int rc = 0;
- AsecIdCollection toUnmount;
- // Find the remaining OBB files that are on external storage.
+ char asecFileName[255];
+
+ AsecIdCollection removeAsec;
+ AsecIdCollection removeObb;
+
for (AsecIdCollection::iterator it = mActiveContainers->begin(); it != mActiveContainers->end();
++it) {
ContainerData* cd = *it;
if (cd->type == ASEC) {
- // nothing
+ if (findAsec(cd->id, asecFileName, sizeof(asecFileName))) {
+ SLOGE("Couldn't find ASEC %s; cleaning up", cd->id);
+ removeAsec.push_back(cd);
+ } else {
+ SLOGD("Found ASEC at path %s", asecFileName);
+ if (!strncmp(asecFileName, Volume::SEC_ASECDIR_EXT,
+ strlen(Volume::SEC_ASECDIR_EXT))) {
+ removeAsec.push_back(cd);
+ }
+ }
} else if (cd->type == OBB) {
if (v == getVolumeForFile(cd->id)) {
- toUnmount.push_back(cd);
+ removeObb.push_back(cd);
}
} else {
SLOGE("Unknown container type %d!", cd->type);
}
}
- for (AsecIdCollection::iterator it = toUnmount.begin(); it != toUnmount.end(); ++it) {
+ for (AsecIdCollection::iterator it = removeAsec.begin(); it != removeAsec.end(); ++it) {
ContainerData *cd = *it;
- SLOGI("Unmounting ASEC %s (dependant on %s)", cd->id, v->getMountpoint());
+ SLOGI("Unmounting ASEC %s (dependent on %s)", cd->id, v->getLabel());
+ if (unmountAsec(cd->id, force)) {
+ SLOGE("Failed to unmount ASEC %s (%s)", cd->id, strerror(errno));
+ rc = -1;
+ }
+ }
+
+ for (AsecIdCollection::iterator it = removeObb.begin(); it != removeObb.end(); ++it) {
+ ContainerData *cd = *it;
+ SLOGI("Unmounting OBB %s (dependent on %s)", cd->id, v->getLabel());
if (unmountObb(cd->id, force)) {
SLOGE("Failed to unmount OBB %s (%s)", cd->id, strerror(errno));
rc = -1;
@@ -1675,6 +1697,26 @@
}
return rc;
-
}
+int VolumeManager::mkdirs(char* path) {
+ // Require that path lives under a volume we manage
+ const char* emulated_source = getenv("EMULATED_STORAGE_SOURCE");
+ const char* root = NULL;
+ if (emulated_source && !strncmp(path, emulated_source, strlen(emulated_source))) {
+ root = emulated_source;
+ } else {
+ Volume* vol = getVolumeForFile(path);
+ if (vol) {
+ root = vol->getMountpoint();
+ }
+ }
+
+ if (!root) {
+ SLOGE("Failed to find volume for %s", path);
+ return -EINVAL;
+ }
+
+ /* fs_mkdirs() does symlink checking and relative path enforcement */
+ return fs_mkdirs(path, 0700);
+}
diff --git a/VolumeManager.h b/VolumeManager.h
index 77fff87..cc8958d 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -83,7 +83,7 @@
int shareVolume(const char *label, const char *method);
int unshareVolume(const char *label, const char *method);
int shareEnabled(const char *path, const char *method, bool *enabled);
- int formatVolume(const char *label);
+ int formatVolume(const char *label, bool wipe);
void disableVolumeManager(void) { mVolManagerDisabled = 1; }
/* ASEC */
@@ -140,6 +140,15 @@
int getDirectVolumeList(struct volume_info *vol_list);
int unmountAllAsecsInDir(const char *directory);
+ /*
+ * Ensure that all directories along given path exist, creating parent
+ * directories as needed. Validates that given path is absolute and that
+ * it contains no relative "." or ".." paths or symlinks. Last path segment
+ * is treated as filename and ignored, unless the path ends with "/". Also
+ * ensures that path belongs to a volume managed by vold.
+ */
+ int mkdirs(char* path);
+
private:
VolumeManager();
void readInitialState();
diff --git a/cryptfs.c b/cryptfs.c
index 3af7a5e..6247014 100644
--- a/cryptfs.c
+++ b/cryptfs.c
@@ -21,6 +21,7 @@
*/
#include <sys/types.h>
+#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
@@ -35,17 +36,19 @@
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <errno.h>
-#include <cutils/android_reboot.h>
#include <ext4.h>
#include <linux/kdev_t.h>
#include <fs_mgr.h>
#include "cryptfs.h"
#define LOG_TAG "Cryptfs"
-#include "cutils/android_reboot.h"
#include "cutils/log.h"
#include "cutils/properties.h"
+#include "cutils/android_reboot.h"
#include "hardware_legacy/power.h"
+#include <logwrap/logwrap.h>
#include "VolumeManager.h"
+#include "VoldUtil.h"
+#include "crypto_scrypt.h"
#define DM_CRYPT_BUF_SIZE 4096
#define DATA_MNT_POINT "/data"
@@ -64,12 +67,25 @@
char *me = "cryptfs";
static unsigned char saved_master_key[KEY_LEN_BYTES];
-static char *saved_data_blkdev;
static char *saved_mount_point;
static int master_key_saved = 0;
+static struct crypt_persist_data *persist_data = NULL;
extern struct fstab *fstab;
+static void cryptfs_reboot(int recovery)
+{
+ if (recovery) {
+ property_set(ANDROID_RB_PROPERTY, "reboot,recovery");
+ } else {
+ property_set(ANDROID_RB_PROPERTY, "reboot");
+ }
+ sleep(20);
+
+ /* Shouldn't get here, reboot should happen before sleep times out */
+ return;
+}
+
static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
{
memset(io, 0, dataSize);
@@ -84,6 +100,56 @@
}
}
+/**
+ * Gets the default device scrypt parameters for key derivation time tuning.
+ * The parameters should lead to about one second derivation time for the
+ * given device.
+ */
+static void get_device_scrypt_params(struct crypt_mnt_ftr *ftr) {
+ const int default_params[] = SCRYPT_DEFAULTS;
+ int params[] = SCRYPT_DEFAULTS;
+ char paramstr[PROPERTY_VALUE_MAX];
+ char *token;
+ char *saveptr;
+ int i;
+
+ property_get(SCRYPT_PROP, paramstr, "");
+ if (paramstr[0] != '\0') {
+ /*
+ * The token we're looking for should be three integers separated by
+ * colons (e.g., "12:8:1"). Scan the property to make sure it matches.
+ */
+ for (i = 0, token = strtok_r(paramstr, ":", &saveptr);
+ token != NULL && i < 3;
+ i++, token = strtok_r(NULL, ":", &saveptr)) {
+ char *endptr;
+ params[i] = strtol(token, &endptr, 10);
+
+ /*
+ * Check that there was a valid number and it's 8-bit. If not,
+ * break out and the end check will take the default values.
+ */
+ if ((*token == '\0') || (*endptr != '\0') || params[i] < 0 || params[i] > 255) {
+ break;
+ }
+ }
+
+ /*
+ * If there were not enough tokens or a token was malformed (not an
+ * integer), it will end up here and the default parameters can be
+ * taken.
+ */
+ if ((i != 3) || (token != NULL)) {
+ SLOGW("bad scrypt parameters '%s' should be like '12:8:1'; using defaults", paramstr);
+ memcpy(params, default_params, sizeof(params));
+ }
+ }
+
+ ftr->N_factor = params[0];
+ ftr->r_factor = params[1];
+ ftr->p_factor = params[2];
+}
+
static unsigned int get_fs_size(char *dev)
{
int fd, block_size;
@@ -115,64 +181,90 @@
return (unsigned int) (len / 512);
}
-static unsigned int get_blkdev_size(int fd)
+static int get_crypt_ftr_info(char **metadata_fname, off64_t *off)
{
+ static int cached_data = 0;
+ static off64_t cached_off = 0;
+ static char cached_metadata_fname[PROPERTY_VALUE_MAX] = "";
+ int fd;
+ char key_loc[PROPERTY_VALUE_MAX];
+ char real_blkdev[PROPERTY_VALUE_MAX];
unsigned int nr_sec;
+ int rc = -1;
- if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
- nr_sec = 0;
+ if (!cached_data) {
+ fs_mgr_get_crypt_info(fstab, key_loc, real_blkdev, sizeof(key_loc));
+
+ if (!strcmp(key_loc, KEY_IN_FOOTER)) {
+ if ( (fd = open(real_blkdev, O_RDWR)) < 0) {
+ SLOGE("Cannot open real block device %s\n", real_blkdev);
+ return -1;
+ }
+
+ if ((nr_sec = get_blkdev_size(fd))) {
+ /* If it's an encrypted Android partition, the last 16 Kbytes contain the
+ * encryption info footer and key, and plenty of bytes to spare for future
+ * growth.
+ */
+ strlcpy(cached_metadata_fname, real_blkdev, sizeof(cached_metadata_fname));
+ cached_off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
+ cached_data = 1;
+ } else {
+ SLOGE("Cannot get size of block device %s\n", real_blkdev);
+ }
+ close(fd);
+ } else {
+ strlcpy(cached_metadata_fname, key_loc, sizeof(cached_metadata_fname));
+ cached_off = 0;
+ cached_data = 1;
+ }
}
- return nr_sec;
+ if (cached_data) {
+ if (metadata_fname) {
+ *metadata_fname = cached_metadata_fname;
+ }
+ if (off) {
+ *off = cached_off;
+ }
+ rc = 0;
+ }
+
+ return rc;
}
/* key or salt can be NULL, in which case just skip writing that value. Useful to
* update the failed mount count but not change the key.
*/
-static int put_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
- unsigned char *key, unsigned char *salt)
+static int put_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
{
int fd;
unsigned int nr_sec, cnt;
- off64_t off;
+ /* starting_off is set to the SEEK_SET offset
+ * where the crypto structure starts
+ */
+ off64_t starting_off;
int rc = -1;
- char *fname;
- char key_loc[PROPERTY_VALUE_MAX];
+ char *fname = NULL;
struct stat statbuf;
- fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
-
- if (!strcmp(key_loc, KEY_IN_FOOTER)) {
- fname = real_blk_name;
- if ( (fd = open(fname, O_RDWR)) < 0) {
- SLOGE("Cannot open real block device %s\n", fname);
- return -1;
- }
-
- if ( (nr_sec = get_blkdev_size(fd)) == 0) {
- SLOGE("Cannot get size of block device %s\n", fname);
- goto errout;
- }
-
- /* If it's an encrypted Android partition, the last 16 Kbytes contain the
- * encryption info footer and key, and plenty of bytes to spare for future
- * growth.
- */
- off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
-
- if (lseek64(fd, off, SEEK_SET) == -1) {
- SLOGE("Cannot seek to real block device footer\n");
- goto errout;
- }
- } else if (key_loc[0] == '/') {
- fname = key_loc;
- if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
- SLOGE("Cannot open footer file %s\n", fname);
- return -1;
- }
- } else {
+ if (get_crypt_ftr_info(&fname, &starting_off)) {
+ SLOGE("Unable to get crypt_ftr_info\n");
+ return -1;
+ }
+ if (fname[0] != '/') {
SLOGE("Unexpected value for crypto key location\n");
- return -1;;
+ return -1;
+ }
+ if ( (fd = open(fname, O_RDWR | O_CREAT, 0600)) < 0) {
+ SLOGE("Cannot open footer file %s for put\n", fname);
+ return -1;
+ }
+
+ /* Seek to the start of the crypt footer */
+ if (lseek64(fd, starting_off, SEEK_SET) == -1) {
+ SLOGE("Cannot seek to real block device footer\n");
+ goto errout;
}
if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
@@ -180,39 +272,9 @@
goto errout;
}
- if (key) {
- if (crypt_ftr->keysize != KEY_LEN_BYTES) {
- SLOGE("Keysize of %d bits not supported for real block device %s\n",
- crypt_ftr->keysize*8, fname);
- goto errout;
- }
-
- if ( (cnt = write(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
- SLOGE("Cannot write key for real block device %s\n", fname);
- goto errout;
- }
- }
-
- if (salt) {
- /* Compute the offset from the last write to the salt */
- off = KEY_TO_SALT_PADDING;
- if (! key)
- off += crypt_ftr->keysize;
-
- if (lseek64(fd, off, SEEK_CUR) == -1) {
- SLOGE("Cannot seek to real block device salt \n");
- goto errout;
- }
-
- if ( (cnt = write(fd, salt, SALT_LEN)) != SALT_LEN) {
- SLOGE("Cannot write salt for real block device %s\n", fname);
- goto errout;
- }
- }
-
fstat(fd, &statbuf);
/* If the keys are kept on a raw block device, do not try to truncate it. */
- if (S_ISREG(statbuf.st_mode) && (key_loc[0] == '/')) {
+ if (S_ISREG(statbuf.st_mode)) {
if (ftruncate(fd, 0x4000)) {
SLOGE("Cannot set footer file size\n", fname);
goto errout;
@@ -228,57 +290,118 @@
}
-static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
- unsigned char *key, unsigned char *salt)
+static inline int unix_read(int fd, void* buff, int len)
+{
+ return TEMP_FAILURE_RETRY(read(fd, buff, len));
+}
+
+static inline int unix_write(int fd, const void* buff, int len)
+{
+ return TEMP_FAILURE_RETRY(write(fd, buff, len));
+}
+
+static void init_empty_persist_data(struct crypt_persist_data *pdata, int len)
+{
+ memset(pdata, 0, len);
+ pdata->persist_magic = PERSIST_DATA_MAGIC;
+ pdata->persist_valid_entries = 0;
+}
+
+/* A routine to update the passed in crypt_ftr to the lastest version.
+ * fd is open read/write on the device that holds the crypto footer and persistent
+ * data, crypt_ftr is a pointer to the struct to be updated, and offset is the
+ * absolute offset to the start of the crypt_mnt_ftr on the passed in fd.
+ */
+static void upgrade_crypt_ftr(int fd, struct crypt_mnt_ftr *crypt_ftr, off64_t offset)
+{
+ int orig_major = crypt_ftr->major_version;
+ int orig_minor = crypt_ftr->minor_version;
+
+ if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version == 0)) {
+ struct crypt_persist_data *pdata;
+ off64_t pdata_offset = offset + CRYPT_FOOTER_TO_PERSIST_OFFSET;
+
+ SLOGW("upgrading crypto footer to 1.1");
+
+ pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
+ if (pdata == NULL) {
+ SLOGE("Cannot allocate persisent data\n");
+ return;
+ }
+ memset(pdata, 0, CRYPT_PERSIST_DATA_SIZE);
+
+ /* Need to initialize the persistent data area */
+ if (lseek64(fd, pdata_offset, SEEK_SET) == -1) {
+ SLOGE("Cannot seek to persisent data offset\n");
+ return;
+ }
+ /* Write all zeros to the first copy, making it invalid */
+ unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
+
+ /* Write a valid but empty structure to the second copy */
+ init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
+ unix_write(fd, pdata, CRYPT_PERSIST_DATA_SIZE);
+
+ /* Update the footer */
+ crypt_ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
+ crypt_ftr->persist_data_offset[0] = pdata_offset;
+ crypt_ftr->persist_data_offset[1] = pdata_offset + CRYPT_PERSIST_DATA_SIZE;
+ crypt_ftr->minor_version = 1;
+ }
+
+ if ((crypt_ftr->major_version == 1) && (crypt_ftr->minor_version)) {
+ SLOGW("upgrading crypto footer to 1.2");
+ /* But keep the old kdf_type.
+ * It will get updated later to KDF_SCRYPT after the password has been verified.
+ */
+ crypt_ftr->kdf_type = KDF_PBKDF2;
+ get_device_scrypt_params(crypt_ftr);
+ crypt_ftr->minor_version = 2;
+ }
+
+ if ((orig_major != crypt_ftr->major_version) || (orig_minor != crypt_ftr->minor_version)) {
+ if (lseek64(fd, offset, SEEK_SET) == -1) {
+ SLOGE("Cannot seek to crypt footer\n");
+ return;
+ }
+ unix_write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr));
+ }
+}
+
+
+static int get_crypt_ftr_and_key(struct crypt_mnt_ftr *crypt_ftr)
{
int fd;
unsigned int nr_sec, cnt;
- off64_t off;
+ off64_t starting_off;
int rc = -1;
- char key_loc[PROPERTY_VALUE_MAX];
- char *fname;
+ char *fname = NULL;
struct stat statbuf;
- fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
-
- if (!strcmp(key_loc, KEY_IN_FOOTER)) {
- fname = real_blk_name;
- if ( (fd = open(fname, O_RDONLY)) < 0) {
- SLOGE("Cannot open real block device %s\n", fname);
- return -1;
- }
-
- if ( (nr_sec = get_blkdev_size(fd)) == 0) {
- SLOGE("Cannot get size of block device %s\n", fname);
- goto errout;
- }
-
- /* If it's an encrypted Android partition, the last 16 Kbytes contain the
- * encryption info footer and key, and plenty of bytes to spare for future
- * growth.
- */
- off = ((off64_t)nr_sec * 512) - CRYPT_FOOTER_OFFSET;
-
- if (lseek64(fd, off, SEEK_SET) == -1) {
- SLOGE("Cannot seek to real block device footer\n");
- goto errout;
- }
- } else if (key_loc[0] == '/') {
- fname = key_loc;
- if ( (fd = open(fname, O_RDONLY)) < 0) {
- SLOGE("Cannot open footer file %s\n", fname);
- return -1;
- }
-
- /* Make sure it's 16 Kbytes in length */
- fstat(fd, &statbuf);
- if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
- SLOGE("footer file %s is not the expected size!\n", fname);
- goto errout;
- }
- } else {
+ if (get_crypt_ftr_info(&fname, &starting_off)) {
+ SLOGE("Unable to get crypt_ftr_info\n");
+ return -1;
+ }
+ if (fname[0] != '/') {
SLOGE("Unexpected value for crypto key location\n");
- return -1;;
+ return -1;
+ }
+ if ( (fd = open(fname, O_RDWR)) < 0) {
+ SLOGE("Cannot open footer file %s for get\n", fname);
+ return -1;
+ }
+
+ /* Make sure it's 16 Kbytes in length */
+ fstat(fd, &statbuf);
+ if (S_ISREG(statbuf.st_mode) && (statbuf.st_size != 0x4000)) {
+ SLOGE("footer file %s is not the expected size!\n", fname);
+ goto errout;
+ }
+
+ /* Seek to the start of the crypt footer */
+ if (lseek64(fd, starting_off, SEEK_SET) == -1) {
+ SLOGE("Cannot seek to real block device footer\n");
+ goto errout;
}
if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
@@ -291,46 +414,22 @@
goto errout;
}
- if (crypt_ftr->major_version != 1) {
- SLOGE("Cannot understand major version %d real block device footer\n",
- crypt_ftr->major_version);
+ if (crypt_ftr->major_version != CURRENT_MAJOR_VERSION) {
+ SLOGE("Cannot understand major version %d real block device footer; expected %d\n",
+ crypt_ftr->major_version, CURRENT_MAJOR_VERSION);
goto errout;
}
- if (crypt_ftr->minor_version != 0) {
- SLOGW("Warning: crypto footer minor version %d, expected 0, continuing...\n",
- crypt_ftr->minor_version);
+ if (crypt_ftr->minor_version > CURRENT_MINOR_VERSION) {
+ SLOGW("Warning: crypto footer minor version %d, expected <= %d, continuing...\n",
+ crypt_ftr->minor_version, CURRENT_MINOR_VERSION);
}
- if (crypt_ftr->ftr_size > sizeof(struct crypt_mnt_ftr)) {
- /* the footer size is bigger than we expected.
- * Skip to it's stated end so we can read the key.
- */
- if (lseek(fd, crypt_ftr->ftr_size - sizeof(struct crypt_mnt_ftr), SEEK_CUR) == -1) {
- SLOGE("Cannot seek to start of key\n");
- goto errout;
- }
- }
-
- if (crypt_ftr->keysize != KEY_LEN_BYTES) {
- SLOGE("Keysize of %d bits not supported for real block device %s\n",
- crypt_ftr->keysize * 8, fname);
- goto errout;
- }
-
- if ( (cnt = read(fd, key, crypt_ftr->keysize)) != crypt_ftr->keysize) {
- SLOGE("Cannot read key for real block device %s\n", fname);
- goto errout;
- }
-
- if (lseek64(fd, KEY_TO_SALT_PADDING, SEEK_CUR) == -1) {
- SLOGE("Cannot seek to real block device salt\n");
- goto errout;
- }
-
- if ( (cnt = read(fd, salt, SALT_LEN)) != SALT_LEN) {
- SLOGE("Cannot read salt for real block device %s\n", fname);
- goto errout;
+ /* If this is a verion 1.0 crypt_ftr, make it a 1.1 crypt footer, and update the
+ * copy on disk before returning.
+ */
+ if (crypt_ftr->minor_version < CURRENT_MINOR_VERSION) {
+ upgrade_crypt_ftr(fd, crypt_ftr, starting_off);
}
/* Success! */
@@ -341,6 +440,227 @@
return rc;
}
+static int validate_persistent_data_storage(struct crypt_mnt_ftr *crypt_ftr)
+{
+ if (crypt_ftr->persist_data_offset[0] + crypt_ftr->persist_data_size >
+ crypt_ftr->persist_data_offset[1]) {
+ SLOGE("Crypt_ftr persist data regions overlap");
+ return -1;
+ }
+
+ if (crypt_ftr->persist_data_offset[0] >= crypt_ftr->persist_data_offset[1]) {
+ SLOGE("Crypt_ftr persist data region 0 starts after region 1");
+ return -1;
+ }
+
+ if (((crypt_ftr->persist_data_offset[1] + crypt_ftr->persist_data_size) -
+ (crypt_ftr->persist_data_offset[0] - CRYPT_FOOTER_TO_PERSIST_OFFSET)) >
+ CRYPT_FOOTER_OFFSET) {
+ SLOGE("Persistent data extends past crypto footer");
+ return -1;
+ }
+
+ return 0;
+}
+
+static int load_persistent_data(void)
+{
+ struct crypt_mnt_ftr crypt_ftr;
+ struct crypt_persist_data *pdata = NULL;
+ char encrypted_state[PROPERTY_VALUE_MAX];
+ char *fname;
+ int found = 0;
+ int fd;
+ int ret;
+ int i;
+
+ if (persist_data) {
+ /* Nothing to do, we've already loaded or initialized it */
+ return 0;
+ }
+
+
+ /* If not encrypted, just allocate an empty table and initialize it */
+ property_get("ro.crypto.state", encrypted_state, "");
+ if (strcmp(encrypted_state, "encrypted") ) {
+ pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
+ if (pdata) {
+ init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
+ persist_data = pdata;
+ return 0;
+ }
+ return -1;
+ }
+
+ if(get_crypt_ftr_and_key(&crypt_ftr)) {
+ return -1;
+ }
+
+ if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
+ SLOGE("Crypt_ftr version doesn't support persistent data");
+ return -1;
+ }
+
+ if (get_crypt_ftr_info(&fname, NULL)) {
+ return -1;
+ }
+
+ ret = validate_persistent_data_storage(&crypt_ftr);
+ if (ret) {
+ return -1;
+ }
+
+ fd = open(fname, O_RDONLY);
+ if (fd < 0) {
+ SLOGE("Cannot open %s metadata file", fname);
+ return -1;
+ }
+
+ if (persist_data == NULL) {
+ pdata = malloc(crypt_ftr.persist_data_size);
+ if (pdata == NULL) {
+ SLOGE("Cannot allocate memory for persistent data");
+ goto err;
+ }
+ }
+
+ for (i = 0; i < 2; i++) {
+ if (lseek64(fd, crypt_ftr.persist_data_offset[i], SEEK_SET) < 0) {
+ SLOGE("Cannot seek to read persistent data on %s", fname);
+ goto err2;
+ }
+ if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0){
+ SLOGE("Error reading persistent data on iteration %d", i);
+ goto err2;
+ }
+ if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
+ found = 1;
+ break;
+ }
+ }
+
+ if (!found) {
+ SLOGI("Could not find valid persistent data, creating");
+ init_empty_persist_data(pdata, crypt_ftr.persist_data_size);
+ }
+
+ /* Success */
+ persist_data = pdata;
+ close(fd);
+ return 0;
+
+err2:
+ free(pdata);
+
+err:
+ close(fd);
+ return -1;
+}
+
+static int save_persistent_data(void)
+{
+ struct crypt_mnt_ftr crypt_ftr;
+ struct crypt_persist_data *pdata;
+ char *fname;
+ off64_t write_offset;
+ off64_t erase_offset;
+ int found = 0;
+ int fd;
+ int ret;
+
+ if (persist_data == NULL) {
+ SLOGE("No persistent data to save");
+ return -1;
+ }
+
+ if(get_crypt_ftr_and_key(&crypt_ftr)) {
+ return -1;
+ }
+
+ if ((crypt_ftr.major_version != 1) || (crypt_ftr.minor_version != 1)) {
+ SLOGE("Crypt_ftr version doesn't support persistent data");
+ return -1;
+ }
+
+ ret = validate_persistent_data_storage(&crypt_ftr);
+ if (ret) {
+ return -1;
+ }
+
+ if (get_crypt_ftr_info(&fname, NULL)) {
+ return -1;
+ }
+
+ fd = open(fname, O_RDWR);
+ if (fd < 0) {
+ SLOGE("Cannot open %s metadata file", fname);
+ return -1;
+ }
+
+ pdata = malloc(crypt_ftr.persist_data_size);
+ if (pdata == NULL) {
+ SLOGE("Cannot allocate persistant data");
+ goto err;
+ }
+
+ if (lseek64(fd, crypt_ftr.persist_data_offset[0], SEEK_SET) < 0) {
+ SLOGE("Cannot seek to read persistent data on %s", fname);
+ goto err2;
+ }
+
+ if (unix_read(fd, pdata, crypt_ftr.persist_data_size) < 0) {
+ SLOGE("Error reading persistent data before save");
+ goto err2;
+ }
+
+ if (pdata->persist_magic == PERSIST_DATA_MAGIC) {
+ /* The first copy is the curent valid copy, so write to
+ * the second copy and erase this one */
+ write_offset = crypt_ftr.persist_data_offset[1];
+ erase_offset = crypt_ftr.persist_data_offset[0];
+ } else {
+ /* The second copy must be the valid copy, so write to
+ * the first copy, and erase the second */
+ write_offset = crypt_ftr.persist_data_offset[0];
+ erase_offset = crypt_ftr.persist_data_offset[1];
+ }
+
+ /* Write the new copy first, if successful, then erase the old copy */
+ if (lseek(fd, write_offset, SEEK_SET) < 0) {
+ SLOGE("Cannot seek to write persistent data");
+ goto err2;
+ }
+ if (unix_write(fd, persist_data, crypt_ftr.persist_data_size) ==
+ (int) crypt_ftr.persist_data_size) {
+ if (lseek(fd, erase_offset, SEEK_SET) < 0) {
+ SLOGE("Cannot seek to erase previous persistent data");
+ goto err2;
+ }
+ fsync(fd);
+ memset(pdata, 0, crypt_ftr.persist_data_size);
+ if (unix_write(fd, pdata, crypt_ftr.persist_data_size) !=
+ (int) crypt_ftr.persist_data_size) {
+ SLOGE("Cannot write to erase previous persistent data");
+ goto err2;
+ }
+ fsync(fd);
+ } else {
+ SLOGE("Cannot write to save persistent data");
+ goto err2;
+ }
+
+ /* Success */
+ free(pdata);
+ close(fd);
+ return 0;
+
+err2:
+ free(pdata);
+err:
+ close(fd);
+ return -1;
+}
+
/* Convert a binary key of specified length into an ascii hex string equivalent,
* without the leading 0x and with null termination
*/
@@ -548,24 +868,37 @@
}
-static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
-{
+static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
/* Turn the password into a key and IV that can decrypt the master key */
PKCS5_PBKDF2_HMAC_SHA1(passwd, strlen(passwd), salt, SALT_LEN,
HASH_COUNT, KEY_LEN_BYTES+IV_LEN_BYTES, ikey);
}
+static void scrypt(char *passwd, unsigned char *salt, unsigned char *ikey, void *params) {
+ struct crypt_mnt_ftr *ftr = (struct crypt_mnt_ftr *) params;
+
+ int N = 1 << ftr->N_factor;
+ int r = 1 << ftr->r_factor;
+ int p = 1 << ftr->p_factor;
+
+ /* Turn the password into a key and IV that can decrypt the master key */
+ crypto_scrypt((unsigned char *) passwd, strlen(passwd), salt, SALT_LEN, N, r, p, ikey,
+ KEY_LEN_BYTES + IV_LEN_BYTES);
+}
+
static int encrypt_master_key(char *passwd, unsigned char *salt,
unsigned char *decrypted_master_key,
- unsigned char *encrypted_master_key)
+ unsigned char *encrypted_master_key,
+ struct crypt_mnt_ftr *crypt_ftr)
{
unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
EVP_CIPHER_CTX e_ctx;
int encrypted_len, final_len;
/* Turn the password into a key and IV that can decrypt the master key */
- pbkdf2(passwd, salt, ikey);
-
+ get_device_scrypt_params(crypt_ftr);
+ scrypt(passwd, salt, ikey, crypt_ftr);
+
/* Initialize the decryption engine */
if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
SLOGE("EVP_EncryptInit failed\n");
@@ -592,16 +925,17 @@
}
}
-static int decrypt_master_key(char *passwd, unsigned char *salt,
+static int decrypt_master_key_aux(char *passwd, unsigned char *salt,
unsigned char *encrypted_master_key,
- unsigned char *decrypted_master_key)
+ unsigned char *decrypted_master_key,
+ kdf_func kdf, void *kdf_params)
{
unsigned char ikey[32+32] = { 0 }; /* Big enough to hold a 256 bit key and 256 bit IV */
EVP_CIPHER_CTX d_ctx;
int decrypted_len, final_len;
/* Turn the password into a key and IV that can decrypt the master key */
- pbkdf2(passwd, salt, ikey);
+ kdf(passwd, salt, ikey, kdf_params);
/* Initialize the decryption engine */
if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
@@ -624,8 +958,36 @@
}
}
-static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
+static void get_kdf_func(struct crypt_mnt_ftr *ftr, kdf_func *kdf, void** kdf_params)
{
+ if (ftr->kdf_type == KDF_SCRYPT) {
+ *kdf = scrypt;
+ *kdf_params = ftr;
+ } else {
+ *kdf = pbkdf2;
+ *kdf_params = NULL;
+ }
+}
+
+static int decrypt_master_key(char *passwd, unsigned char *decrypted_master_key,
+ struct crypt_mnt_ftr *crypt_ftr)
+{
+ kdf_func kdf;
+ void *kdf_params;
+ int ret;
+
+ get_kdf_func(crypt_ftr, &kdf, &kdf_params);
+ ret = decrypt_master_key_aux(passwd, crypt_ftr->salt, crypt_ftr->master_key, decrypted_master_key, kdf,
+ kdf_params);
+ if (ret != 0) {
+ SLOGW("failure decrypting master key");
+ }
+
+ return ret;
+}
+
+static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt,
+ struct crypt_mnt_ftr *crypt_ftr) {
int fd;
unsigned char key_buf[KEY_LEN_BYTES];
EVP_CIPHER_CTX e_ctx;
@@ -638,7 +1000,7 @@
close(fd);
/* Now encrypt it with the password */
- return encrypt_master_key(passwd, salt, key_buf, master_key);
+ return encrypt_master_key(passwd, salt, key_buf, master_key, crypt_ftr);
}
static int wait_and_unmount(char *mountpoint)
@@ -791,9 +1153,6 @@
static int do_crypto_complete(char *mount_point)
{
struct crypt_mnt_ftr crypt_ftr;
- unsigned char encrypted_master_key[32];
- unsigned char salt[SALT_LEN];
- char real_blkdev[MAXPATHLEN];
char encrypted_state[PROPERTY_VALUE_MAX];
char key_loc[PROPERTY_VALUE_MAX];
@@ -803,9 +1162,7 @@
return 1;
}
- fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
-
- if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
fs_mgr_get_crypt_info(fstab, key_loc, 0, sizeof(key_loc));
/*
@@ -838,14 +1195,15 @@
{
struct crypt_mnt_ftr crypt_ftr;
/* Allocate enough space for a 256 bit key, but we may use less */
- unsigned char encrypted_master_key[32], decrypted_master_key[32];
- unsigned char salt[SALT_LEN];
+ unsigned char decrypted_master_key[32];
char crypto_blkdev[MAXPATHLEN];
char real_blkdev[MAXPATHLEN];
char tmp_mount_point[64];
unsigned int orig_failed_decrypt_count;
char encrypted_state[PROPERTY_VALUE_MAX];
int rc;
+ kdf_func kdf;
+ void *kdf_params;
property_get("ro.crypto.state", encrypted_state, "");
if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
@@ -855,7 +1213,7 @@
fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
- if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
SLOGE("Error getting crypt footer and key\n");
return -1;
}
@@ -864,7 +1222,10 @@
orig_failed_decrypt_count = crypt_ftr.failed_decrypt_count;
if (! (crypt_ftr.flags & CRYPT_MNT_KEY_UNENCRYPTED) ) {
- decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
+ if (decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr)) {
+ SLOGE("Failed to decrypt master key\n");
+ return -1;
+ }
}
if (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
@@ -873,7 +1234,7 @@
return -1;
}
- /* If init detects an encrypted filesystme, it writes a file for each such
+ /* If init detects an encrypted filesystem, it writes a file for each such
* encrypted fs into the tmpfs /data filesystem, and then the framework finds those
* files and passes that data to me */
/* Create a tmp mount point to try mounting the decryptd fs
@@ -895,7 +1256,7 @@
}
if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
- put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
+ put_crypt_ftr_and_key(&crypt_ftr);
}
if (crypt_ftr.failed_decrypt_count) {
@@ -912,10 +1273,22 @@
* the key when we want to change the password on it.
*/
memcpy(saved_master_key, decrypted_master_key, KEY_LEN_BYTES);
- saved_data_blkdev = strdup(real_blkdev);
saved_mount_point = strdup(mount_point);
master_key_saved = 1;
+ SLOGD("%s(): Master key saved\n", __FUNCTION__);
rc = 0;
+ /*
+ * Upgrade if we're not using the latest KDF.
+ */
+ if (crypt_ftr.kdf_type != KDF_SCRYPT) {
+ crypt_ftr.kdf_type = KDF_SCRYPT;
+ rc = encrypt_master_key(passwd, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key,
+ &crypt_ftr);
+ if (!rc) {
+ rc = put_crypt_ftr_and_key(&crypt_ftr);
+ }
+ SLOGD("Key Derivation Function upgrade: rc=%d\n", rc);
+ }
}
return rc;
@@ -941,14 +1314,12 @@
{
char real_blkdev[MAXPATHLEN], crypto_blkdev[MAXPATHLEN];
struct crypt_mnt_ftr sd_crypt_ftr;
- unsigned char key[32], salt[32];
struct stat statbuf;
int nr_sec, fd;
sprintf(real_blkdev, "/dev/block/vold/%d:%d", major, minor);
- /* Just want the footer, but gotta get it all */
- get_crypt_ftr_and_key(saved_data_blkdev, &sd_crypt_ftr, key, salt);
+ get_crypt_ftr_and_key(&sd_crypt_ftr);
/* Update the fs_size field to be the size of the volume */
fd = open(real_blkdev, O_RDONLY);
@@ -991,9 +1362,7 @@
{
struct crypt_mnt_ftr crypt_ftr;
/* Allocate enough space for a 256 bit key, but we may use less */
- unsigned char encrypted_master_key[32], decrypted_master_key[32];
- unsigned char salt[SALT_LEN];
- char real_blkdev[MAXPATHLEN];
+ unsigned char decrypted_master_key[32];
char encrypted_state[PROPERTY_VALUE_MAX];
int rc;
@@ -1013,9 +1382,7 @@
return -1;
}
- fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
-
- if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
SLOGE("Error getting crypt footer and key\n");
return -1;
}
@@ -1024,7 +1391,7 @@
/* If the device has no password, then just say the password is valid */
rc = 0;
} else {
- decrypt_master_key(passwd, salt, encrypted_master_key, decrypted_master_key);
+ decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
if (!memcmp(decrypted_master_key, saved_master_key, crypt_ftr.keysize)) {
/* They match, the password is correct */
rc = 0;
@@ -1045,60 +1412,88 @@
*/
static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
{
+ off64_t off;
+
+ memset(ftr, 0, sizeof(struct crypt_mnt_ftr));
ftr->magic = CRYPT_MNT_MAGIC;
- ftr->major_version = 1;
- ftr->minor_version = 0;
+ ftr->major_version = CURRENT_MAJOR_VERSION;
+ ftr->minor_version = CURRENT_MINOR_VERSION;
ftr->ftr_size = sizeof(struct crypt_mnt_ftr);
- ftr->flags = 0;
ftr->keysize = KEY_LEN_BYTES;
- ftr->spare1 = 0;
- ftr->fs_size = 0;
- ftr->failed_decrypt_count = 0;
- ftr->crypto_type_name[0] = '\0';
+
+ ftr->kdf_type = KDF_SCRYPT;
+ get_device_scrypt_params(ftr);
+
+ ftr->persist_data_size = CRYPT_PERSIST_DATA_SIZE;
+ if (get_crypt_ftr_info(NULL, &off) == 0) {
+ ftr->persist_data_offset[0] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET;
+ ftr->persist_data_offset[1] = off + CRYPT_FOOTER_TO_PERSIST_OFFSET +
+ ftr->persist_data_size;
+ }
}
static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
{
- char cmdline[256];
+ const char *args[10];
+ char size_str[32]; /* Must be large enough to hold a %lld and null byte */
+ int num_args;
+ int status;
+ int tmp;
int rc = -1;
if (type == EXT4_FS) {
- snprintf(cmdline, sizeof(cmdline), "/system/bin/make_ext4fs -a /data -l %lld %s",
- size * 512, crypto_blkdev);
- SLOGI("Making empty filesystem with command %s\n", cmdline);
+ args[0] = "/system/bin/make_ext4fs";
+ args[1] = "-a";
+ args[2] = "/data";
+ args[3] = "-l";
+ snprintf(size_str, sizeof(size_str), "%lld", size * 512);
+ args[4] = size_str;
+ args[5] = crypto_blkdev;
+ num_args = 6;
+ SLOGI("Making empty filesystem with command %s %s %s %s %s %s\n",
+ args[0], args[1], args[2], args[3], args[4], args[5]);
} else if (type== FAT_FS) {
- snprintf(cmdline, sizeof(cmdline), "/system/bin/newfs_msdos -F 32 -O android -c 8 -s %lld %s",
- size, crypto_blkdev);
- SLOGI("Making empty filesystem with command %s\n", cmdline);
+ args[0] = "/system/bin/newfs_msdos";
+ args[1] = "-F";
+ args[2] = "32";
+ args[3] = "-O";
+ args[4] = "android";
+ args[5] = "-c";
+ args[6] = "8";
+ args[7] = "-s";
+ snprintf(size_str, sizeof(size_str), "%lld", size);
+ args[8] = size_str;
+ args[9] = crypto_blkdev;
+ num_args = 10;
+ SLOGI("Making empty filesystem with command %s %s %s %s %s %s %s %s %s %s\n",
+ args[0], args[1], args[2], args[3], args[4], args[5],
+ args[6], args[7], args[8], args[9]);
} else {
SLOGE("cryptfs_enable_wipe(): unknown filesystem type %d\n", type);
return -1;
}
- if (system(cmdline)) {
- SLOGE("Error creating empty filesystem on %s\n", crypto_blkdev);
+ tmp = android_fork_execvp(num_args, (char **)args, &status, false, true);
+
+ if (tmp != 0) {
+ SLOGE("Error creating empty filesystem on %s due to logwrap error\n", crypto_blkdev);
} else {
- SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
- rc = 0;
+ if (WIFEXITED(status)) {
+ if (WEXITSTATUS(status)) {
+ SLOGE("Error creating filesystem on %s, exit status %d ",
+ crypto_blkdev, WEXITSTATUS(status));
+ } else {
+ SLOGD("Successfully created filesystem on %s\n", crypto_blkdev);
+ rc = 0;
+ }
+ } else {
+ SLOGE("Error creating filesystem on %s, did not exit normally\n", crypto_blkdev);
+ }
}
return rc;
}
-static inline int unix_read(int fd, void* buff, int len)
-{
- int ret;
- do { ret = read(fd, buff, len); } while (ret < 0 && errno == EINTR);
- return ret;
-}
-
-static inline int unix_write(int fd, const void* buff, int len)
-{
- int ret;
- do { ret = write(fd, buff, len); } while (ret < 0 && errno == EINTR);
- return ret;
-}
-
#define CRYPT_INPLACE_BUFSIZE 4096
#define CRYPT_SECTORS_PER_BUFSIZE (CRYPT_INPLACE_BUFSIZE / 512)
static int cryptfs_enable_inplace(char *crypto_blkdev, char *real_blkdev, off64_t size,
@@ -1194,10 +1589,10 @@
int how = 0;
char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
unsigned long nr_sec;
- unsigned char master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
- unsigned char salt[SALT_LEN];
+ unsigned char decrypted_master_key[KEY_LEN_BYTES];
int rc=-1, fd, i, ret;
struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
+ struct crypt_persist_data *pdata;
char tmpfs_options[PROPERTY_VALUE_MAX];
char encrypted_state[PROPERTY_VALUE_MAX];
char lockid[32] = { 0 };
@@ -1358,6 +1753,7 @@
/* Start the actual work of making an encrypted filesystem */
/* Initialize a crypt_mnt_ftr for the partition */
cryptfs_init_crypt_mnt_ftr(&crypt_ftr);
+
if (!strcmp(key_loc, KEY_IN_FOOTER)) {
crypt_ftr.fs_size = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
} else {
@@ -1367,15 +1763,29 @@
strcpy((char *)crypt_ftr.crypto_type_name, "aes-cbc-essiv:sha256");
/* Make an encrypted master key */
- if (create_encrypted_random_key(passwd, master_key, salt)) {
+ if (create_encrypted_random_key(passwd, crypt_ftr.master_key, crypt_ftr.salt, &crypt_ftr)) {
SLOGE("Cannot create encrypted master key\n");
goto error_unencrypted;
}
/* Write the key to the end of the partition */
- put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, master_key, salt);
+ put_crypt_ftr_and_key(&crypt_ftr);
- decrypt_master_key(passwd, salt, master_key, decrypted_master_key);
+ /* If any persistent data has been remembered, save it.
+ * If none, create a valid empty table and save that.
+ */
+ if (!persist_data) {
+ pdata = malloc(CRYPT_PERSIST_DATA_SIZE);
+ if (pdata) {
+ init_empty_persist_data(pdata, CRYPT_PERSIST_DATA_SIZE);
+ persist_data = pdata;
+ }
+ }
+ if (persist_data) {
+ save_persistent_data();
+ }
+
+ decrypt_master_key(passwd, decrypted_master_key, &crypt_ftr);
create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
"userdata");
@@ -1445,10 +1855,10 @@
/* Clear the encryption in progres flag in the footer */
crypt_ftr.flags &= ~CRYPT_ENCRYPTION_IN_PROGRESS;
- put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
+ put_crypt_ftr_and_key(&crypt_ftr);
sleep(2); /* Give the UI a chance to show 100% progress */
- android_reboot(ANDROID_RB_RESTART, 0, 0);
+ cryptfs_reboot(0);
} else {
char value[PROPERTY_VALUE_MAX];
@@ -1464,7 +1874,7 @@
} else {
SLOGE("could not open /cache/recovery/command\n");
}
- android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
+ cryptfs_reboot(1);
} else {
/* set property to trigger dialog */
property_set("vold.encrypt_progress", "error_partially_encrypted");
@@ -1495,7 +1905,7 @@
* vold to restart the system.
*/
SLOGE("Error enabling encryption after framework is shutdown, no data changed, restarting system");
- android_reboot(ANDROID_RB_RESTART, 0, 0);
+ cryptfs_reboot(0);
/* shouldn't get here */
property_set("vold.encrypt_progress", "error_shutting_down");
@@ -1509,9 +1919,7 @@
int cryptfs_changepw(char *newpw)
{
struct crypt_mnt_ftr crypt_ftr;
- unsigned char encrypted_master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
- unsigned char salt[SALT_LEN];
- char real_blkdev[MAXPATHLEN];
+ unsigned char decrypted_master_key[KEY_LEN_BYTES];
/* This is only allowed after we've successfully decrypted the master key */
if (! master_key_saved) {
@@ -1519,22 +1927,156 @@
return -1;
}
- fs_mgr_get_crypt_info(fstab, 0, real_blkdev, sizeof(real_blkdev));
- if (strlen(real_blkdev) == 0) {
- SLOGE("Can't find real blkdev");
- return -1;
- }
-
/* get key */
- if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
+ if (get_crypt_ftr_and_key(&crypt_ftr)) {
SLOGE("Error getting crypt footer and key");
return -1;
}
- encrypt_master_key(newpw, salt, saved_master_key, encrypted_master_key);
+ encrypt_master_key(newpw, crypt_ftr.salt, saved_master_key, crypt_ftr.master_key, &crypt_ftr);
/* save the key */
- put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt);
+ put_crypt_ftr_and_key(&crypt_ftr);
return 0;
}
+
+static int persist_get_key(char *fieldname, char *value)
+{
+ unsigned int i;
+
+ if (persist_data == NULL) {
+ return -1;
+ }
+ for (i = 0; i < persist_data->persist_valid_entries; i++) {
+ if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
+ /* We found it! */
+ strlcpy(value, persist_data->persist_entry[i].val, PROPERTY_VALUE_MAX);
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+static int persist_set_key(char *fieldname, char *value, int encrypted)
+{
+ unsigned int i;
+ unsigned int num;
+ struct crypt_mnt_ftr crypt_ftr;
+ unsigned int max_persistent_entries;
+ unsigned int dsize;
+
+ if (persist_data == NULL) {
+ return -1;
+ }
+
+ /* If encrypted, use the values from the crypt_ftr, otherwise
+ * use the values for the current spec.
+ */
+ if (encrypted) {
+ if(get_crypt_ftr_and_key(&crypt_ftr)) {
+ return -1;
+ }
+ dsize = crypt_ftr.persist_data_size;
+ } else {
+ dsize = CRYPT_PERSIST_DATA_SIZE;
+ }
+ max_persistent_entries = (dsize - sizeof(struct crypt_persist_data)) /
+ sizeof(struct crypt_persist_entry);
+
+ num = persist_data->persist_valid_entries;
+
+ for (i = 0; i < num; i++) {
+ if (!strncmp(persist_data->persist_entry[i].key, fieldname, PROPERTY_KEY_MAX)) {
+ /* We found an existing entry, update it! */
+ memset(persist_data->persist_entry[i].val, 0, PROPERTY_VALUE_MAX);
+ strlcpy(persist_data->persist_entry[i].val, value, PROPERTY_VALUE_MAX);
+ return 0;
+ }
+ }
+
+ /* We didn't find it, add it to the end, if there is room */
+ if (persist_data->persist_valid_entries < max_persistent_entries) {
+ memset(&persist_data->persist_entry[num], 0, sizeof(struct crypt_persist_entry));
+ strlcpy(persist_data->persist_entry[num].key, fieldname, PROPERTY_KEY_MAX);
+ strlcpy(persist_data->persist_entry[num].val, value, PROPERTY_VALUE_MAX);
+ persist_data->persist_valid_entries++;
+ return 0;
+ }
+
+ return -1;
+}
+
+/* Return the value of the specified field. */
+int cryptfs_getfield(char *fieldname, char *value, int len)
+{
+ char temp_value[PROPERTY_VALUE_MAX];
+ char real_blkdev[MAXPATHLEN];
+ /* 0 is success, 1 is not encrypted,
+ * -1 is value not set, -2 is any other error
+ */
+ int rc = -2;
+
+ if (persist_data == NULL) {
+ load_persistent_data();
+ if (persist_data == NULL) {
+ SLOGE("Getfield error, cannot load persistent data");
+ goto out;
+ }
+ }
+
+ if (!persist_get_key(fieldname, temp_value)) {
+ /* We found it, copy it to the caller's buffer and return */
+ strlcpy(value, temp_value, len);
+ rc = 0;
+ } else {
+ /* Sadness, it's not there. Return the error */
+ rc = -1;
+ }
+
+out:
+ return rc;
+}
+
+/* Set the value of the specified field. */
+int cryptfs_setfield(char *fieldname, char *value)
+{
+ struct crypt_persist_data stored_pdata;
+ struct crypt_persist_data *pdata_p;
+ struct crypt_mnt_ftr crypt_ftr;
+ char encrypted_state[PROPERTY_VALUE_MAX];
+ /* 0 is success, -1 is an error */
+ int rc = -1;
+ int encrypted = 0;
+
+ if (persist_data == NULL) {
+ load_persistent_data();
+ if (persist_data == NULL) {
+ SLOGE("Setfield error, cannot load persistent data");
+ goto out;
+ }
+ }
+
+ property_get("ro.crypto.state", encrypted_state, "");
+ if (!strcmp(encrypted_state, "encrypted") ) {
+ encrypted = 1;
+ }
+
+ if (persist_set_key(fieldname, value, encrypted)) {
+ goto out;
+ }
+
+ /* If we are running encrypted, save the persistent data now */
+ if (encrypted) {
+ if (save_persistent_data()) {
+ SLOGE("Setfield error, cannot save persistent data");
+ goto out;
+ }
+ }
+
+ rc = 0;
+
+out:
+ return rc;
+}
diff --git a/cryptfs.h b/cryptfs.h
index 1c1bc1a..162159e 100644
--- a/cryptfs.h
+++ b/cryptfs.h
@@ -15,22 +15,31 @@
*/
/* This structure starts 16,384 bytes before the end of a hardware
- * partition that is encrypted.
- * Immediately following this structure is the encrypted key.
- * The keysize field tells how long the key is, in bytes.
- * Then there is 32 bytes of padding,
- * Finally there is the salt used with the user password.
- * The salt is fixed at 16 bytes long.
+ * partition that is encrypted, or in a separate partition. It's location
+ * is specified by a property set in init.<device>.rc.
+ * The structure allocates 48 bytes for a key, but the real key size is
+ * specified in the struct. Currently, the code is hardcoded to use 128
+ * bit keys.
+ * The fields after salt are only valid in rev 1.1 and later stuctures.
* Obviously, the filesystem does not include the last 16 kbytes
- * of the partition.
+ * of the partition if the crypt_mnt_ftr lives at the end of the
+ * partition.
*/
+#include <cutils/properties.h>
+
+/* The current cryptfs version */
+#define CURRENT_MAJOR_VERSION 1
+#define CURRENT_MINOR_VERSION 2
+
#define CRYPT_FOOTER_OFFSET 0x4000
+#define CRYPT_FOOTER_TO_PERSIST_OFFSET 0x1000
+#define CRYPT_PERSIST_DATA_SIZE 0x1000
#define MAX_CRYPTO_TYPE_NAME_LEN 64
+#define MAX_KEY_LEN 48
#define SALT_LEN 16
-#define KEY_TO_SALT_PADDING 32
/* definitions of flags in the structure below */
#define CRYPT_MNT_KEY_UNENCRYPTED 0x1 /* The key for the partition is not encrypted. */
@@ -38,9 +47,18 @@
* clear when done before rebooting */
#define CRYPT_MNT_MAGIC 0xD0B5B1C4
+#define PERSIST_DATA_MAGIC 0xE950CD44
+
+#define SCRYPT_PROP "ro.crypto.scrypt_params"
+#define SCRYPT_DEFAULTS { 15, 3, 1 }
+
+/* Key Derivation Function algorithms */
+#define KDF_PBKDF2 1
+#define KDF_SCRYPT 2
#define __le32 unsigned int
-#define __le16 unsigned short int
+#define __le16 unsigned short int
+#define __le8 unsigned char
struct crypt_mnt_ftr {
__le32 magic; /* See above */
@@ -56,6 +74,48 @@
unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
needed to decrypt this
partition, null terminated */
+ __le32 spare2; /* ignored */
+ unsigned char master_key[MAX_KEY_LEN]; /* The encrypted key for decrypting the filesystem */
+ unsigned char salt[SALT_LEN]; /* The salt used for this encryption */
+ __le64 persist_data_offset[2]; /* Absolute offset to both copies of crypt_persist_data
+ * on device with that info, either the footer of the
+ * real_blkdevice or the metadata partition. */
+
+ __le32 persist_data_size; /* The number of bytes allocated to each copy of the
+ * persistent data table*/
+
+ __le8 kdf_type; /* The key derivation function used. */
+
+ /* scrypt parameters. See www.tarsnap.com/scrypt/scrypt.pdf */
+ __le8 N_factor; /* (1 << N) */
+ __le8 r_factor; /* (1 << r) */
+ __le8 p_factor; /* (1 << p) */
+};
+
+/* Persistant data that should be available before decryption.
+ * Things like airplane mode, locale and timezone are kept
+ * here and can be retrieved by the CryptKeeper UI to properly
+ * configure the phone before asking for the password
+ * This is only valid if the major and minor version above
+ * is set to 1.1 or higher.
+ *
+ * This is a 4K structure. There are 2 copies, and the code alternates
+ * writing one and then clearing the previous one. The reading
+ * code reads the first valid copy it finds, based on the magic number.
+ * The absolute offset to the first of the two copies is kept in rev 1.1
+ * and higher crypt_mnt_ftr structures.
+ */
+struct crypt_persist_entry {
+ char key[PROPERTY_KEY_MAX];
+ char val[PROPERTY_VALUE_MAX];
+};
+
+/* Should be exactly 4K in size */
+struct crypt_persist_data {
+ __le32 persist_magic;
+ __le32 persist_valid_entries;
+ __le32 persist_spare[30];
+ struct crypt_persist_entry persist_entry[0];
};
struct volume_info {
@@ -67,12 +127,17 @@
char crypto_blkdev[256];
char label[256];
};
-#define VOL_NONREMOVABLE 0x1
-#define VOL_ENCRYPTABLE 0x2
+#define VOL_NONREMOVABLE 0x1
+#define VOL_ENCRYPTABLE 0x2
+#define VOL_PRIMARY 0x4
+#define VOL_PROVIDES_ASEC 0x8
#ifdef __cplusplus
extern "C" {
#endif
+
+ typedef void (*kdf_func)(char *passwd, unsigned char *salt, unsigned char *ikey, void *params);
+
int cryptfs_crypto_complete(void);
int cryptfs_check_passwd(char *pw);
int cryptfs_verify_passwd(char *newpw);
@@ -83,6 +148,8 @@
char *crypto_dev_path, unsigned int max_pathlen,
int *new_major, int *new_minor);
int cryptfs_revert_volume(const char *label);
+ int cryptfs_getfield(char *fieldname, char *value, int len);
+ int cryptfs_setfield(char *fieldname, char *value);
#ifdef __cplusplus
}
#endif
diff --git a/fstrim.c b/fstrim.c
index 4911778..73705f9 100644
--- a/fstrim.c
+++ b/fstrim.c
@@ -102,8 +102,9 @@
if (ioctl(fd, FITRIM, &range)) {
SLOGE("FITRIM ioctl failed on %s", fstab->recs[i].mount_point);
ret = -1;
+ } else {
+ SLOGI("Trimmed %llu bytes on %s\n", range.len, fstab->recs[i].mount_point);
}
- SLOGI("Trimmed %llu bytes on %s\n", range.len, fstab->recs[i].mount_point);
close(fd);
}
diff --git a/main.cpp b/main.cpp
index 02506e7..d4b7d28 100644
--- a/main.cpp
+++ b/main.cpp
@@ -174,16 +174,6 @@
DirectVolume *dv = NULL;
flags = 0;
- dv = new DirectVolume(vm, fstab->recs[i].label,
- fstab->recs[i].mount_point,
- fstab->recs[i].partnum);
-
- if (dv->addPath(fstab->recs[i].blk_device)) {
- SLOGE("Failed to add devpath %s to volume %s",
- fstab->recs[i].blk_device, fstab->recs[i].label);
- goto out_fail;
- }
-
/* Set any flags that might be set for this volume */
if (fs_mgr_is_nonremovable(&fstab->recs[i])) {
flags |= VOL_NONREMOVABLE;
@@ -191,7 +181,18 @@
if (fs_mgr_is_encryptable(&fstab->recs[i])) {
flags |= VOL_ENCRYPTABLE;
}
- dv->setFlags(flags);
+ /* Only set this flag if there is not an emulated sd card */
+ if (fs_mgr_is_noemulatedsd(&fstab->recs[i]) &&
+ !strcmp(fstab->recs[i].fs_type, "vfat")) {
+ flags |= VOL_PROVIDES_ASEC;
+ }
+ dv = new DirectVolume(vm, &(fstab->recs[i]), flags);
+
+ if (dv->addPath(fstab->recs[i].blk_device)) {
+ SLOGE("Failed to add devpath %s to volume %s",
+ fstab->recs[i].blk_device, fstab->recs[i].label);
+ goto out_fail;
+ }
vm->addVolume(dv);
}