Reconcile with gingerbread-release
Change-Id: Ia9383258bc25f7a82628a1c7238140b810e2f3d3
diff --git a/Android.mk b/Android.mk
index e353a4f..bba6122 100644
--- a/Android.mk
+++ b/Android.mk
@@ -1,10 +1,3 @@
-BUILD_VOLD2 := false
-ifneq ($(TARGET_SIMULATOR),true)
- BUILD_VOLD2 := true
-endif
-
-ifeq ($(BUILD_VOLD2),true)
-
LOCAL_PATH:= $(call my-dir)
common_src_files := \
@@ -21,16 +14,19 @@
Loop.cpp \
Devmapper.cpp \
ResponseCode.cpp \
- Xwarp.cpp
+ Xwarp.cpp \
+ cryptfs.c
common_c_includes := \
$(KERNEL_HEADERS) \
+ system/extras/ext4_utils \
external/openssl/include
common_shared_libraries := \
libsysutils \
libcutils \
libdiskconfig \
+ libhardware_legacy \
libcrypto
include $(CLEAR_VARS)
@@ -76,5 +72,3 @@
LOCAL_SHARED_LIBRARIES := libcutils
include $(BUILD_EXECUTABLE)
-
-endif # ifeq ($(BUILD_VOLD,true)
diff --git a/CommandListener.cpp b/CommandListener.cpp
index b0fc551..1672fcc 100644
--- a/CommandListener.cpp
+++ b/CommandListener.cpp
@@ -22,6 +22,7 @@
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
+#include <string.h>
#define LOG_TAG "VoldCmdListener"
#include <cutils/log.h>
@@ -35,6 +36,7 @@
#include "Xwarp.h"
#include "Loop.h"
#include "Devmapper.h"
+#include "cryptfs.h"
CommandListener::CommandListener() :
FrameworkListener("vold") {
@@ -42,9 +44,9 @@
registerCmd(new VolumeCmd());
registerCmd(new AsecCmd());
registerCmd(new ObbCmd());
- registerCmd(new ShareCmd());
registerCmd(new StorageCmd());
registerCmd(new XwarpCmd());
+ registerCmd(new CryptfsCmd());
}
void CommandListener::dumpArgs(int argc, char **argv, int argObscure) {
@@ -54,7 +56,7 @@
memset(buffer, 0, sizeof(buffer));
int i;
for (i = 0; i < argc; i++) {
- int len = strlen(argv[i]) + 1; // Account for space
+ unsigned int len = strlen(argv[i]) + 1; // Account for space
if (i == argObscure) {
len += 2; // Account for {}
}
@@ -197,39 +199,6 @@
return 0;
}
-CommandListener::ShareCmd::ShareCmd() :
- VoldCommand("share") {
-}
-
-int CommandListener::ShareCmd::runCommand(SocketClient *cli,
- int argc, char **argv) {
- dumpArgs(argc, argv, -1);
-
- if (argc < 2) {
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
- return 0;
- }
-
- VolumeManager *vm = VolumeManager::Instance();
- int rc = 0;
-
- if (!strcmp(argv[1], "status")) {
- bool avail = false;
-
- if (vm->shareAvailable(argv[2], &avail)) {
- cli->sendMsg(
- ResponseCode::OperationFailed, "Failed to determine share availability", true);
- } else {
- cli->sendMsg(ResponseCode::ShareStatusResult,
- (avail ? "Share available" : "Share unavailable"), false);
- }
- } else {
- cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown share cmd", false);
- }
-
- return 0;
-}
-
CommandListener::StorageCmd::StorageCmd() :
VoldCommand("storage") {
}
@@ -383,6 +352,18 @@
cli->sendMsg(ResponseCode::AsecPathResult, path, false);
return 0;
}
+ } else if (!strcmp(argv[1], "fspath")) {
+ dumpArgs(argc, argv, -1);
+ if (argc != 3) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: asec fspath <container-id>", false);
+ return 0;
+ }
+ char path[255];
+
+ if (!(rc = vm->getAsecFilesystemPath(argv[2], path, sizeof(path)))) {
+ cli->sendMsg(ResponseCode::AsecPathResult, path, false);
+ return 0;
+ }
} else {
dumpArgs(argc, argv, -1);
cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown asec cmd", false);
@@ -505,3 +486,65 @@
return 0;
}
+CommandListener::CryptfsCmd::CryptfsCmd() :
+ VoldCommand("cryptfs") {
+}
+
+int CommandListener::CryptfsCmd::runCommand(SocketClient *cli,
+ int argc, char **argv) {
+ if (argc < 2) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Missing Argument", false);
+ return 0;
+ }
+
+ int rc = 0;
+
+ if (!strcmp(argv[1], "checkpw")) {
+ if (argc != 3) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs checkpw <passwd>", false);
+ return 0;
+ }
+ dumpArgs(argc, argv, 2);
+ rc = cryptfs_check_passwd(argv[2]);
+ } else if (!strcmp(argv[1], "restart")) {
+ if (argc != 2) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs restart", false);
+ return 0;
+ }
+ dumpArgs(argc, argv, -1);
+ rc = cryptfs_restart();
+ } else if (!strcmp(argv[1], "cryptocomplete")) {
+ if (argc != 2) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs cryptocomplete", false);
+ return 0;
+ }
+ dumpArgs(argc, argv, -1);
+ rc = cryptfs_crypto_complete();
+ } else if (!strcmp(argv[1], "enablecrypto")) {
+ if ( (argc != 4) || (strcmp(argv[2], "wipe") && strcmp(argv[2], "inplace")) ) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs enablecrypto <wipe|inplace> <passwd>", false);
+ return 0;
+ }
+ dumpArgs(argc, argv, 3);
+ rc = cryptfs_enable(argv[2], argv[3]);
+ } else if (!strcmp(argv[1], "changepw")) {
+ if (argc != 3) {
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Usage: cryptfs changepw <newpasswd>", false);
+ return 0;
+ }
+ SLOGD("cryptfs changepw {}");
+ rc = cryptfs_changepw(argv[2]);
+ } else {
+ dumpArgs(argc, argv, -1);
+ cli->sendMsg(ResponseCode::CommandSyntaxError, "Unknown cryptfs cmd", false);
+ }
+
+ // Always report that the command succeeded and return the error code.
+ // The caller will check the return value to see what the error was.
+ char msg[255];
+ snprintf(msg, sizeof(msg), "%d", rc);
+ cli->sendMsg(ResponseCode::CommandOkay, msg, false);
+
+ return 0;
+}
+
diff --git a/CommandListener.h b/CommandListener.h
index 75c7e81..baf7760 100644
--- a/CommandListener.h
+++ b/CommandListener.h
@@ -42,13 +42,6 @@
int runCommand(SocketClient *c, int argc, char ** argv);
};
- class ShareCmd : public VoldCommand {
- public:
- ShareCmd();
- virtual ~ShareCmd() {}
- int runCommand(SocketClient *c, int argc, char ** argv);
- };
-
class AsecCmd : public VoldCommand {
public:
AsecCmd();
@@ -76,6 +69,13 @@
virtual ~XwarpCmd() {}
int runCommand(SocketClient *c, int argc, char ** argv);
};
+
+ class CryptfsCmd : public VoldCommand {
+ public:
+ CryptfsCmd();
+ virtual ~CryptfsCmd() {}
+ int runCommand(SocketClient *c, int argc, char ** argv);
+ };
};
#endif
diff --git a/Devmapper.cpp b/Devmapper.cpp
index c9482bf..7c11d12 100644
--- a/Devmapper.cpp
+++ b/Devmapper.cpp
@@ -15,10 +15,12 @@
*/
#include <stdio.h>
+#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
+#include <stdlib.h>
#include <sys/types.h>
#include <sys/ioctl.h>
@@ -34,6 +36,8 @@
#include "Devmapper.h"
+#define DEVMAPPER_BUFFER_SIZE 4096
+
int Devmapper::dumpState(SocketClient *c) {
char *buffer = (char *) malloc(1024 * 64);
@@ -43,7 +47,7 @@
}
memset(buffer, 0, (1024 * 64));
- char *buffer2 = (char *) malloc(4096);
+ char *buffer2 = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer2) {
SLOGE("Error allocating memory (%s)", strerror(errno));
free(buffer);
@@ -81,9 +85,9 @@
do {
n = (struct dm_name_list *) (((char *) n) + nxt);
- memset(buffer2, 0, 4096);
+ memset(buffer2, 0, DEVMAPPER_BUFFER_SIZE);
struct dm_ioctl *io2 = (struct dm_ioctl *) buffer2;
- ioctlInit(io2, 4096, n->name, 0);
+ ioctlInit(io2, DEVMAPPER_BUFFER_SIZE, n->name, 0);
if (ioctl(fd, DM_DEV_STATUS, io2)) {
if (errno != ENXIO) {
SLOGE("DM_DEV_STATUS ioctl failed (%s)", strerror(errno));
@@ -120,12 +124,14 @@
io->version[2] = 0;
io->flags = flags;
if (name) {
- strncpy(io->name, name, sizeof(io->name));
+ int ret = strlcpy(io->name, name, sizeof(io->name));
+ if (ret >= sizeof(io->name))
+ abort();
}
}
int Devmapper::lookupActive(const char *name, char *ubuffer, size_t len) {
- char *buffer = (char *) malloc(4096);
+ char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer) {
SLOGE("Error allocating memory (%s)", strerror(errno));
return -1;
@@ -140,7 +146,7 @@
struct dm_ioctl *io = (struct dm_ioctl *) buffer;
- ioctlInit(io, 4096, name, 0);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
if (ioctl(fd, DM_DEV_STATUS, io)) {
if (errno != ENXIO) {
SLOGE("DM_DEV_STATUS ioctl failed for lookup (%s)", strerror(errno));
@@ -159,7 +165,7 @@
int Devmapper::create(const char *name, const char *loopFile, const char *key,
unsigned int numSectors, char *ubuffer, size_t len) {
- char *buffer = (char *) malloc(4096);
+ char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer) {
SLOGE("Error allocating memory (%s)", strerror(errno));
return -1;
@@ -175,7 +181,7 @@
struct dm_ioctl *io = (struct dm_ioctl *) buffer;
// Create the DM device
- ioctlInit(io, 4096, name, 0);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
if (ioctl(fd, DM_DEV_CREATE, io)) {
SLOGE("Error creating device mapping (%s)", strerror(errno));
@@ -185,7 +191,7 @@
}
// Set the legacy geometry
- ioctlInit(io, 4096, name, 0);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
char *geoParams = buffer + sizeof(struct dm_ioctl);
// bps=512 spc=8 res=32 nft=2 sec=8190 mid=0xf0 spt=63 hds=64 hid=0 bspf=8 rdcl=2 infs=1 bkbs=2
@@ -200,7 +206,7 @@
}
// Retrieve the device number we were allocated
- ioctlInit(io, 4096, name, 0);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
if (ioctl(fd, DM_DEV_STATUS, io)) {
SLOGE("Error retrieving devmapper status (%s)", strerror(errno));
free(buffer);
@@ -215,17 +221,19 @@
struct dm_target_spec *tgt;
tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
- ioctlInit(io, 4096, name, DM_STATUS_TABLE_FLAG);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, DM_STATUS_TABLE_FLAG);
io->target_count = 1;
tgt->status = 0;
tgt->sector_start = 0;
tgt->length = numSectors;
- strcpy(tgt->target_type, "crypt");
+ strlcpy(tgt->target_type, "crypt", sizeof(tgt->target_type));
char *cryptParams = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
- sprintf(cryptParams, "twofish %s 0 %s 0", key, loopFile);
+ snprintf(cryptParams,
+ DEVMAPPER_BUFFER_SIZE - (sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec)),
+ "twofish %s 0 %s 0", key, loopFile);
cryptParams += strlen(cryptParams) + 1;
cryptParams = (char *) _align(cryptParams, 8);
tgt->next = cryptParams - buffer;
@@ -238,7 +246,7 @@
}
// Resume the new table
- ioctlInit(io, 4096, name, 0);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
if (ioctl(fd, DM_DEV_SUSPEND, io)) {
SLOGE("Error Resuming (%s)", strerror(errno));
@@ -254,7 +262,7 @@
}
int Devmapper::destroy(const char *name) {
- char *buffer = (char *) malloc(4096);
+ char *buffer = (char *) malloc(DEVMAPPER_BUFFER_SIZE);
if (!buffer) {
SLOGE("Error allocating memory (%s)", strerror(errno));
return -1;
@@ -270,7 +278,7 @@
struct dm_ioctl *io = (struct dm_ioctl *) buffer;
// Create the DM device
- ioctlInit(io, 4096, name, 0);
+ ioctlInit(io, DEVMAPPER_BUFFER_SIZE, name, 0);
if (ioctl(fd, DM_DEV_REMOVE, io)) {
if (errno != ENXIO) {
@@ -292,4 +300,3 @@
return (void *) (((unsigned long) ptr + agn) & ~agn);
}
-
diff --git a/DirectVolume.cpp b/DirectVolume.cpp
index 0ac1a0c..2ddd5ab 100644
--- a/DirectVolume.cpp
+++ b/DirectVolume.cpp
@@ -29,6 +29,7 @@
#include "DirectVolume.h"
#include "VolumeManager.h"
#include "ResponseCode.h"
+#include "cryptfs.h"
// #define PARTITION_DEBUG
@@ -61,6 +62,10 @@
return 0;
}
+void DirectVolume::setFlags(int flags) {
+ mFlags = flags;
+}
+
dev_t DirectVolume::getDiskDevice() {
return MKDEV(mDiskMajor, mDiskMinor);
}
@@ -187,8 +192,8 @@
}
if (part_num > MAX_PARTITIONS || part_num < 1) {
- SLOGW("Invalid 'PARTN' value");
- part_num = 1;
+ SLOGE("Invalid 'PARTN' value");
+ return;
}
if (part_num > mDiskNumParts) {
@@ -202,15 +207,23 @@
#ifdef PARTITION_DEBUG
SLOGD("Dv:partAdd: part_num = %d, minor = %d\n", part_num, minor);
#endif
- mPartMinors[part_num -1] = minor;
-
+ if (part_num >= MAX_PARTITIONS) {
+ SLOGE("Dv:partAdd: ignoring part_num = %d (max: %d)\n", part_num, MAX_PARTITIONS-1);
+ } else {
+ mPartMinors[part_num -1] = minor;
+ }
mPendingPartMap &= ~(1 << part_num);
+
if (!mPendingPartMap) {
#ifdef PARTITION_DEBUG
SLOGD("Dv:partAdd: Got all partitions - ready to rock!");
#endif
if (getState() != Volume::State_Formatting) {
setState(Volume::State_Idle);
+ if (mRetryMount == true) {
+ mRetryMount = false;
+ mountVol();
+ }
}
} else {
#ifdef PARTITION_DEBUG
@@ -275,6 +288,7 @@
int major = atoi(evt->findParam("MAJOR"));
int minor = atoi(evt->findParam("MINOR"));
char msg[255];
+ int state;
SLOGD("Volume %s %s partition %d:%d removed\n", getLabel(), getMountpoint(), major, minor);
@@ -284,7 +298,8 @@
* the removal notification will be sent on the Disk
* itself
*/
- if (getState() != Volume::State_Mounted) {
+ state = getState();
+ if (state != Volume::State_Mounted && state != Volume::State_Shared) {
return;
}
@@ -309,6 +324,19 @@
} else {
SLOGD("Crisis averted");
}
+ } else if (state == Volume::State_Shared) {
+ /* removed during mass storage */
+ snprintf(msg, sizeof(msg), "Volume %s bad removal (%d:%d)",
+ getLabel(), major, minor);
+ mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeBadRemoval,
+ msg, false);
+
+ if (mVm->unshareVolume(getLabel(), "ums")) {
+ SLOGE("Failed to unshare volume on bad removal (%s)",
+ strerror(errno));
+ } else {
+ SLOGD("Crisis averted");
+ }
}
}
@@ -335,3 +363,61 @@
devs[0] = MKDEV(mDiskMajor, mPartMinors[mPartIdx -1]);
return 1;
}
+
+/*
+ * Called from base to update device info,
+ * e.g. When setting up an dm-crypt mapping for the sd card.
+ */
+int DirectVolume::updateDeviceInfo(char *new_path, int new_major, int new_minor)
+{
+ PathCollection::iterator it;
+
+ if (mPartIdx == -1) {
+ SLOGE("Can only change device info on a partition\n");
+ return -1;
+ }
+
+ /*
+ * This is to change the sysfs path associated with a partition, in particular,
+ * for an internal SD card partition that is encrypted. Thus, the list is
+ * expected to be only 1 entry long. Check that and bail if not.
+ */
+ if (mPaths->size() != 1) {
+ SLOGE("Cannot change path if there are more than one for a volume\n");
+ return -1;
+ }
+
+ it = mPaths->begin();
+ free(*it); /* Free the string storage */
+ mPaths->erase(it); /* Remove it from the list */
+ addPath(new_path); /* Put the new path on the list */
+
+ mDiskMajor = new_major;
+ mDiskMinor = new_minor;
+ /* Ugh, virual block devices don't use minor 0 for whole disk and minor > 0 for
+ * partition number. They don't have partitions, they are just virtual block
+ * devices, and minor number 0 is the first dm-crypt device. Luckily the first
+ * dm-crypt device is for the userdata partition, which gets minor number 0, and
+ * it is not managed by vold. So the next device is minor number one, which we
+ * will call partition one.
+ */
+ mPartIdx = new_minor;
+ mPartMinors[new_minor-1] = new_minor;
+
+ mIsDecrypted = 1;
+
+ return 0;
+}
+
+/*
+ * Called from base to give cryptfs all the info it needs to encrypt eligible volumes
+ */
+int DirectVolume::getVolInfo(struct volume_info *v)
+{
+ strcpy(v->label, mLabel);
+ strcpy(v->mnt_point, mMountpoint);
+ v->flags=mFlags;
+ /* 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 4bf14ff..ad1b386 100644
--- a/DirectVolume.h
+++ b/DirectVolume.h
@@ -35,6 +35,8 @@
int mPartMinors[MAX_PARTITIONS];
int mDiskNumParts;
unsigned char mPendingPartMap;
+ int mIsDecrypted;
+ int mFlags;
public:
DirectVolume(VolumeManager *vm, const char *label, const char *mount_point, int partIdx);
@@ -47,9 +49,14 @@
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);
+ 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 4754c66..82a3f7a 100644
--- a/Fat.cpp
+++ b/Fat.cpp
@@ -15,6 +15,7 @@
*/
#include <stdio.h>
+#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
@@ -30,6 +31,7 @@
#include <sys/mount.h>
#include <linux/kdev_t.h>
+#include <linux/fs.h>
#define LOG_TAG "Vold"
diff --git a/Loop.cpp b/Loop.cpp
index 98015e2..dad2c3f 100644
--- a/Loop.cpp
+++ b/Loop.cpp
@@ -15,6 +15,7 @@
*/
#include <stdio.h>
+#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
@@ -22,6 +23,7 @@
#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/ioctl.h>
#include <linux/kdev_t.h>
@@ -126,7 +128,7 @@
char filename[256];
for (i = 0; i < LOOP_MAX; i++) {
- struct loop_info li;
+ struct loop_info64 li;
int rc;
sprintf(filename, "/dev/block/loop%d", i);
@@ -149,7 +151,7 @@
return -1;
}
- rc = ioctl(fd, LOOP_GET_STATUS, &li);
+ rc = ioctl(fd, LOOP_GET_STATUS64, &li);
if (rc < 0 && errno == ENXIO)
break;
@@ -188,8 +190,8 @@
struct loop_info64 li;
memset(&li, 0, sizeof(li));
- strncpy((char*) li.lo_crypt_name, id, LO_NAME_SIZE);
- strncpy((char*) li.lo_file_name, loopFile, LO_NAME_SIZE);
+ strlcpy((char*) li.lo_crypt_name, id, LO_NAME_SIZE);
+ strlcpy((char*) li.lo_file_name, loopFile, LO_NAME_SIZE);
if (ioctl(fd, LOOP_SET_STATUS64, &li) < 0) {
SLOGE("Error setting loopback status (%s)", strerror(errno));
diff --git a/NetlinkHandler.cpp b/NetlinkHandler.cpp
index f47d364..ecda2a0 100644
--- a/NetlinkHandler.cpp
+++ b/NetlinkHandler.cpp
@@ -17,6 +17,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
+#include <string.h>
#define LOG_TAG "Vold"
@@ -52,11 +53,5 @@
if (!strcmp(subsys, "block")) {
vm->handleBlockEvent(evt);
- } else if (!strcmp(subsys, "switch")) {
- vm->handleSwitchEvent(evt);
- } else if (!strcmp(subsys, "usb_composite")) {
- vm->handleUsbCompositeEvent(evt);
- } else if (!strcmp(subsys, "battery")) {
- } else if (!strcmp(subsys, "power_supply")) {
}
}
diff --git a/Volume.cpp b/Volume.cpp
index d2b87b6..45db27e 100644
--- a/Volume.cpp
+++ b/Volume.cpp
@@ -25,13 +25,17 @@
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/mount.h>
+#include <sys/param.h>
#include <linux/kdev_t.h>
+#include <linux/fs.h>
#include <cutils/properties.h>
#include <diskconfig/diskconfig.h>
+#include <private/android_filesystem_config.h>
+
#define LOG_TAG "Vold"
#include <cutils/log.h>
@@ -41,6 +45,7 @@
#include "ResponseCode.h"
#include "Fat.h"
#include "Process.h"
+#include "cryptfs.h"
extern "C" void dos_partition_dec(void const *pp, struct dos_partition *d);
extern "C" void dos_partition_enc(void *pp, struct dos_partition *d);
@@ -111,6 +116,7 @@
mState = Volume::State_Init;
mCurrentlyMountedKdev = -1;
mPartIdx = -1;
+ mRetryMount = false;
}
Volume::~Volume() {
@@ -169,6 +175,10 @@
return;
}
+ if ((oldState == Volume::State_Pending) && (state != Volume::State_Idle)) {
+ mRetryMount = false;
+ }
+
mState = state;
SLOGD("Volume %s state changing %d (%s) -> %d (%s)", mLabel,
@@ -218,6 +228,7 @@
setState(Volume::State_Formatting);
+ int ret = -1;
// Only initialize the MBR if we are formatting the entire device
if (formatEntireDevice) {
sprintf(devicePath, "/dev/block/vold/%d:%d",
@@ -241,10 +252,11 @@
goto err;
}
- setState(Volume::State_Idle);
- return 0;
+ ret = 0;
+
err:
- return -1;
+ setState(Volume::State_Idle);
+ return ret;
}
bool Volume::isMountpointMounted(const char *path) {
@@ -277,8 +289,21 @@
dev_t deviceNodes[4];
int n, i, rc = 0;
char errmsg[255];
+ const char* externalStorage = getenv("EXTERNAL_STORAGE");
+ bool primaryStorage = externalStorage && !strcmp(getMountpoint(), externalStorage);
+ char decrypt_state[PROPERTY_VALUE_MAX];
+ char crypto_state[PROPERTY_VALUE_MAX];
+ char encrypt_progress[PROPERTY_VALUE_MAX];
+ int flags;
- if (getState() == Volume::State_NoMedia) {
+ property_get("vold.decrypt", decrypt_state, "");
+ property_get("vold.encrypt_progress", encrypt_progress, "");
+
+ /* Don't try to mount the volumes if we have not yet entered the disk password
+ * or are in the process of encrypting.
+ */
+ if ((getState() == Volume::State_NoMedia) ||
+ ((!strcmp(decrypt_state, "1") || encrypt_progress[0]) && primaryStorage)) {
snprintf(errmsg, sizeof(errmsg),
"Volume %s %s mount failed - no media",
getLabel(), getMountpoint());
@@ -289,6 +314,9 @@
return -1;
} else if (getState() != Volume::State_Idle) {
errno = EBUSY;
+ if (getState() == Volume::State_Pending) {
+ mRetryMount = true;
+ }
return -1;
}
@@ -305,6 +333,56 @@
return -1;
}
+ /* 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
+ * 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 &&
+ ((flags & (VOL_NONREMOVABLE | VOL_ENCRYPTABLE))==(VOL_NONREMOVABLE | VOL_ENCRYPTABLE)) &&
+ !strcmp(crypto_state, "encrypted") && !isDecrypted()) {
+ char new_sys_path[MAXPATHLEN];
+ char nodepath[256];
+ int new_major, new_minor;
+
+ if (n != 1) {
+ /* We only expect one device node returned when mounting encryptable volumes */
+ SLOGE("Too many device nodes returned when mounting %d\n", getMountpoint());
+ return -1;
+ }
+
+ if (cryptfs_setup_volume(getLabel(), MAJOR(deviceNodes[0]), MINOR(deviceNodes[0]),
+ new_sys_path, sizeof(new_sys_path),
+ &new_major, &new_minor)) {
+ SLOGE("Cannot setup encryption mapping for %d\n", getMountpoint());
+ return -1;
+ }
+ /* We now have the new sysfs path for the decrypted block device, and the
+ * majore and minor numbers for it. So, create the device, update the
+ * path to the new sysfs path, and continue.
+ */
+ snprintf(nodepath,
+ sizeof(nodepath), "/dev/block/vold/%d:%d",
+ new_major, new_minor);
+ if (createDeviceNode(nodepath, new_major, new_minor)) {
+ SLOGE("Error making device node '%s' (%s)", nodepath,
+ strerror(errno));
+ }
+
+ // Todo: Either create sys filename from nodepath, or pass in bogus path so
+ // vold ignores state changes on this internal device.
+ updateDeviceInfo(nodepath, new_major, new_minor);
+
+ /* Get the device nodes again, because they just changed */
+ n = getDeviceNodes((dev_t *) &deviceNodes, 4);
+ if (!n) {
+ SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
+ return -1;
+ }
+ }
+
for (i = 0; i < n; i++) {
char devicePath[255];
@@ -333,8 +411,18 @@
* 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,
- 1000, 1015, 0702, true)) {
+ AID_SYSTEM, gid, 0702, true)) {
SLOGE("%s failed to mount via VFAT (%s)\n", devicePath, strerror(errno));
continue;
}
@@ -343,7 +431,8 @@
protectFromAutorunStupidity();
- if (createBindMounts()) {
+ // only create android_secure on primary storage
+ if (primaryStorage && createBindMounts()) {
SLOGE("Failed to create bindmounts (%s)", strerror(errno));
umount("/mnt/secure/staging");
setState(Volume::State_Idle);
@@ -508,7 +597,7 @@
if (getState() != Volume::State_Mounted) {
SLOGE("Volume %s unmount request when not mounted", getLabel());
errno = EINVAL;
- return -1;
+ return UNMOUNT_NOT_MOUNTED_ERR;
}
setState(Volume::State_Unmounting);
diff --git a/Volume.h b/Volume.h
index 64cd7cb..f57ff91 100644
--- a/Volume.h
+++ b/Volume.h
@@ -52,6 +52,7 @@
VolumeManager *mVm;
bool mDebug;
int mPartIdx;
+ bool mRetryMount;
/*
* The major/minor tuple of the currently mounted filesystem.
@@ -77,11 +78,15 @@
virtual void handleVolumeUnshared();
void setDebug(bool enable);
+ virtual int getVolInfo(struct volume_info *v) = 0;
protected:
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 int isDecrypted(void) = 0;
+ virtual int getFlags(void) = 0;
int createDeviceNode(const char *path, int major, int minor);
diff --git a/VolumeManager.cpp b/VolumeManager.cpp
index 32b5679..0f04a06 100644
--- a/VolumeManager.cpp
+++ b/VolumeManager.cpp
@@ -41,6 +41,9 @@
#include "Devmapper.h"
#include "Process.h"
#include "Asec.h"
+#include "cryptfs.h"
+
+#define MASS_STORAGE_FILE_PATH "/sys/class/android_usb/android0/f_mass_storage/lun/file"
VolumeManager *VolumeManager::sInstance = NULL;
@@ -55,47 +58,11 @@
mVolumes = new VolumeCollection();
mActiveContainers = new AsecIdCollection();
mBroadcaster = NULL;
- mUsbMassStorageEnabled = false;
- mUsbConnected = false;
mUmsSharingCount = 0;
mSavedDirtyRatio = -1;
// set dirty ratio to 0 when UMS is active
mUmsDirtyRatio = 0;
-
- readInitialState();
-}
-
-void VolumeManager::readInitialState() {
- FILE *fp;
- char state[255];
-
- /*
- * Read the initial mass storage enabled state
- */
- if ((fp = fopen("/sys/devices/virtual/usb_composite/usb_mass_storage/enable", "r"))) {
- if (fgets(state, sizeof(state), fp)) {
- mUsbMassStorageEnabled = !strncmp(state, "1", 1);
- } else {
- SLOGE("Failed to read usb_mass_storage enabled state (%s)", strerror(errno));
- }
- fclose(fp);
- } else {
- SLOGD("USB mass storage support is not enabled in the kernel");
- }
-
- /*
- * Read the initial USB connected state
- */
- if ((fp = fopen("/sys/devices/virtual/switch/usb_configuration/state", "r"))) {
- if (fgets(state, sizeof(state), fp)) {
- mUsbConnected = !strncmp(state, "1", 1);
- } else {
- SLOGE("Failed to read usb_configuration switch (%s)", strerror(errno));
- }
- fclose(fp);
- } else {
- SLOGD("usb_configuration switch is not enabled in the kernel");
- }
+ mVolManagerDisabled = 0;
}
VolumeManager::~VolumeManager() {
@@ -156,58 +123,6 @@
return 0;
}
-void VolumeManager::notifyUmsAvailable(bool available) {
- char msg[255];
-
- snprintf(msg, sizeof(msg), "Share method ums now %s",
- (available ? "available" : "unavailable"));
- SLOGD(msg);
- getBroadcaster()->sendBroadcast(ResponseCode::ShareAvailabilityChange,
- msg, false);
-}
-
-void VolumeManager::handleSwitchEvent(NetlinkEvent *evt) {
- const char *devpath = evt->findParam("DEVPATH");
- const char *name = evt->findParam("SWITCH_NAME");
- const char *state = evt->findParam("SWITCH_STATE");
-
- if (!name || !state) {
- SLOGW("Switch %s event missing name/state info", devpath);
- return;
- }
-
- bool oldAvailable = massStorageAvailable();
- if (!strcmp(name, "usb_configuration")) {
- mUsbConnected = !strcmp(state, "1");
- SLOGD("USB %s", mUsbConnected ? "connected" : "disconnected");
- bool newAvailable = massStorageAvailable();
- if (newAvailable != oldAvailable) {
- notifyUmsAvailable(newAvailable);
- }
- } else {
- SLOGW("Ignoring unknown switch '%s'", name);
- }
-}
-void VolumeManager::handleUsbCompositeEvent(NetlinkEvent *evt) {
- const char *function = evt->findParam("FUNCTION");
- const char *enabled = evt->findParam("ENABLED");
-
- if (!function || !enabled) {
- SLOGW("usb_composite event missing function/enabled info");
- return;
- }
-
- if (!strcmp(function, "usb_mass_storage")) {
- bool oldAvailable = massStorageAvailable();
- mUsbMassStorageEnabled = !strcmp(enabled, "1");
- SLOGD("usb_mass_storage function %s", mUsbMassStorageEnabled ? "enabled" : "disabled");
- bool newAvailable = massStorageAvailable();
- if (newAvailable != oldAvailable) {
- notifyUmsAvailable(newAvailable);
- }
- }
-}
-
void VolumeManager::handleBlockEvent(NetlinkEvent *evt) {
const char *devpath = evt->findParam("DEVPATH");
@@ -254,6 +169,11 @@
return -1;
}
+ if (mVolManagerDisabled) {
+ errno = EBUSY;
+ return -1;
+ }
+
return v->formatVol();
}
@@ -289,6 +209,20 @@
return 0;
}
+int VolumeManager::getAsecFilesystemPath(const char *id, char *buffer, int maxlen) {
+ char asecFileName[255];
+ snprintf(asecFileName, sizeof(asecFileName), "%s/%s.asec", Volume::SEC_ASECDIR, id);
+
+ memset(buffer, 0, maxlen);
+ if (access(asecFileName, F_OK)) {
+ errno = ENOENT;
+ return -1;
+ }
+
+ snprintf(buffer, maxlen, "%s", asecFileName);
+ return 0;
+}
+
int VolumeManager::createAsec(const char *id, unsigned int numSectors,
const char *fstype, const char *key, int ownerUid) {
struct asec_superblock sb;
@@ -962,17 +896,6 @@
return 0;
}
-int VolumeManager::shareAvailable(const char *method, bool *avail) {
-
- if (strcmp(method, "ums")) {
- errno = ENOSYS;
- return -1;
- }
-
- *avail = massStorageAvailable();
- return 0;
-}
-
int VolumeManager::shareEnabled(const char *label, const char *method, bool *enabled) {
Volume *v = lookupVolume(label);
@@ -994,24 +917,6 @@
return 0;
}
-int VolumeManager::simulate(const char *cmd, const char *arg) {
-
- if (!strcmp(cmd, "ums")) {
- if (!strcmp(arg, "connect")) {
- notifyUmsAvailable(true);
- } else if (!strcmp(arg, "disconnect")) {
- notifyUmsAvailable(false);
- } else {
- errno = EINVAL;
- return -1;
- }
- } else {
- errno = EINVAL;
- return -1;
- }
- return 0;
-}
-
int VolumeManager::shareVolume(const char *label, const char *method) {
Volume *v = lookupVolume(label);
@@ -1041,6 +946,11 @@
return -1;
}
+ if (mVolManagerDisabled) {
+ errno = EBUSY;
+ return -1;
+ }
+
dev_t d = v->getShareDevice();
if ((MAJOR(d) == 0) && (MINOR(d) == 0)) {
// This volume does not support raw disk access
@@ -1054,8 +964,7 @@
sizeof(nodepath), "/dev/block/vold/%d:%d",
MAJOR(d), MINOR(d));
- if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file",
- O_WRONLY)) < 0) {
+ if ((fd = open(MASS_STORAGE_FILE_PATH, O_WRONLY)) < 0) {
SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
return -1;
}
@@ -1105,7 +1014,7 @@
}
int fd;
- if ((fd = open("/sys/devices/platform/usb_mass_storage/lun0/file", O_WRONLY)) < 0) {
+ if ((fd = open(MASS_STORAGE_FILE_PATH, O_WRONLY)) < 0) {
SLOGE("Unable to open ums lunfile (%s)", strerror(errno));
return -1;
}
@@ -1132,6 +1041,52 @@
return 0;
}
+extern "C" int vold_disableVol(const char *label) {
+ VolumeManager *vm = VolumeManager::Instance();
+ vm->disableVolumeManager();
+ vm->unshareVolume(label, "ums");
+ return vm->unmountVolume(label, true);
+}
+
+extern "C" int vold_getNumDirectVolumes(void) {
+ VolumeManager *vm = VolumeManager::Instance();
+ return vm->getNumDirectVolumes();
+}
+
+int VolumeManager::getNumDirectVolumes(void) {
+ VolumeCollection::iterator i;
+ int n=0;
+
+ for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
+ if ((*i)->getShareDevice() != (dev_t)0) {
+ n++;
+ }
+ }
+ return n;
+}
+
+extern "C" int vold_getDirectVolumeList(struct volume_info *vol_list) {
+ VolumeManager *vm = VolumeManager::Instance();
+ return vm->getDirectVolumeList(vol_list);
+}
+
+int VolumeManager::getDirectVolumeList(struct volume_info *vol_list) {
+ VolumeCollection::iterator i;
+ int n=0;
+ dev_t d;
+
+ for (i = mVolumes->begin(); i != mVolumes->end(); ++i) {
+ if ((d=(*i)->getShareDevice()) != (dev_t)0) {
+ (*i)->getVolInfo(&vol_list[n]);
+ snprintf(vol_list[n].blk_dev, sizeof(vol_list[n].blk_dev),
+ "/dev/block/vold/%d:%d",MAJOR(d), MINOR(d));
+ n++;
+ }
+ }
+
+ return 0;
+}
+
int VolumeManager::unmountVolume(const char *label, bool force) {
Volume *v = lookupVolume(label);
@@ -1149,7 +1104,7 @@
SLOGW("Attempt to unmount volume which isn't mounted (%d)\n",
v->getState());
errno = EBUSY;
- return -1;
+ return UNMOUNT_NOT_MOUNTED_ERR;
}
cleanupAsec(v, force);
diff --git a/VolumeManager.h b/VolumeManager.h
index 11b5ed3..caa0b62 100644
--- a/VolumeManager.h
+++ b/VolumeManager.h
@@ -19,6 +19,7 @@
#include <pthread.h>
+#ifdef __cplusplus
#include <utils/List.h>
#include <sysutils/SocketListener.h>
@@ -58,14 +59,13 @@
VolumeCollection *mVolumes;
AsecIdCollection *mActiveContainers;
- bool mUsbMassStorageEnabled;
- bool mUsbConnected;
bool mDebug;
// for adjusting /proc/sys/vm/dirty_ratio when UMS is active
int mUmsSharingCount;
int mSavedDirtyRatio;
int mUmsDirtyRatio;
+ int mVolManagerDisabled;
public:
virtual ~VolumeManager();
@@ -74,8 +74,6 @@
int stop();
void handleBlockEvent(NetlinkEvent *evt);
- void handleSwitchEvent(NetlinkEvent *evt);
- void handleUsbCompositeEvent(NetlinkEvent *evt);
int addVolume(Volume *v);
@@ -84,10 +82,9 @@
int unmountVolume(const char *label, bool force);
int shareVolume(const char *label, const char *method);
int unshareVolume(const char *label, const char *method);
- int shareAvailable(const char *method, bool *avail);
int shareEnabled(const char *path, const char *method, bool *enabled);
- int simulate(const char *cmd, const char *arg);
int formatVolume(const char *label);
+ void disableVolumeManager(void) { mVolManagerDisabled = 1; }
/* ASEC */
int createAsec(const char *id, unsigned numSectors, const char *fstype,
@@ -98,6 +95,7 @@
int unmountAsec(const char *id, bool force);
int renameAsec(const char *id1, const char *id2);
int getAsecMountPath(const char *id, char *buffer, int maxlen);
+ int getAsecFilesystemPath(const char *id, char *buffer, int maxlen);
/* Loopback images */
int listMountedObbs(SocketClient* cli);
@@ -121,13 +119,24 @@
static char *asecHash(const char *id, char *buffer, size_t len);
+ Volume *lookupVolume(const char *label);
+ int getNumDirectVolumes(void);
+ int getDirectVolumeList(struct volume_info *vol_list);
+
private:
VolumeManager();
void readInitialState();
- Volume *lookupVolume(const char *label);
bool isMountpointMounted(const char *mp);
-
- inline bool massStorageAvailable() const { return mUsbMassStorageEnabled && mUsbConnected; }
- void notifyUmsAvailable(bool available);
};
+
+extern "C" {
+#endif /* __cplusplus */
+#define UNMOUNT_NOT_MOUNTED_ERR -2
+ int vold_disableVol(const char *label);
+ int vold_getNumDirectVolumes(void);
+ int vold_getDirectVolumeList(struct volume_info *v);
+#ifdef __cplusplus
+}
+#endif
+
#endif
diff --git a/cryptfs.c b/cryptfs.c
new file mode 100644
index 0000000..50c3e64
--- /dev/null
+++ b/cryptfs.c
@@ -0,0 +1,1373 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+/* TO DO:
+ * 1. Perhaps keep several copies of the encrypted key, in case something
+ * goes horribly wrong?
+ *
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <sys/ioctl.h>
+#include <linux/dm-ioctl.h>
+#include <libgen.h>
+#include <stdlib.h>
+#include <sys/param.h>
+#include <string.h>
+#include <sys/mount.h>
+#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 "cryptfs.h"
+#define LOG_TAG "Cryptfs"
+#include "cutils/log.h"
+#include "cutils/properties.h"
+#include "hardware_legacy/power.h"
+#include "VolumeManager.h"
+
+#define DM_CRYPT_BUF_SIZE 4096
+#define DATA_MNT_POINT "/data"
+
+#define HASH_COUNT 2000
+#define KEY_LEN_BYTES 16
+#define IV_LEN_BYTES 16
+
+#define KEY_LOC_PROP "ro.crypto.keyfile.userdata"
+#define KEY_IN_FOOTER "footer"
+
+#define EXT4_FS 1
+#define FAT_FS 2
+
+char *me = "cryptfs";
+
+static unsigned char saved_master_key[KEY_LEN_BYTES];
+static char *saved_data_blkdev;
+static int master_key_saved = 0;
+
+static void ioctl_init(struct dm_ioctl *io, size_t dataSize, const char *name, unsigned flags)
+{
+ memset(io, 0, dataSize);
+ io->data_size = dataSize;
+ io->data_start = sizeof(struct dm_ioctl);
+ io->version[0] = 4;
+ io->version[1] = 0;
+ io->version[2] = 0;
+ io->flags = flags;
+ if (name) {
+ strncpy(io->name, name, sizeof(io->name));
+ }
+}
+
+static unsigned int get_fs_size(char *dev)
+{
+ int fd, block_size;
+ struct ext4_super_block sb;
+ off64_t len;
+
+ if ((fd = open(dev, O_RDONLY)) < 0) {
+ SLOGE("Cannot open device to get filesystem size ");
+ return 0;
+ }
+
+ if (lseek64(fd, 1024, SEEK_SET) < 0) {
+ SLOGE("Cannot seek to superblock");
+ return 0;
+ }
+
+ if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) {
+ SLOGE("Cannot read superblock");
+ return 0;
+ }
+
+ close(fd);
+
+ block_size = 1024 << sb.s_log_block_size;
+ /* compute length in bytes */
+ len = ( ((off64_t)sb.s_blocks_count_hi << 32) + sb.s_blocks_count_lo) * block_size;
+
+ /* return length in sectors */
+ return (unsigned int) (len / 512);
+}
+
+static unsigned int get_blkdev_size(int fd)
+{
+ unsigned int nr_sec;
+
+ if ( (ioctl(fd, BLKGETSIZE, &nr_sec)) == -1) {
+ nr_sec = 0;
+ }
+
+ return nr_sec;
+}
+
+/* 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)
+{
+ int fd;
+ unsigned int nr_sec, cnt;
+ off64_t off;
+ int rc = -1;
+ char *fname;
+ char key_loc[PROPERTY_VALUE_MAX];
+
+ property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
+
+ 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 {
+ SLOGE("Unexpected value for" KEY_LOC_PROP "\n");
+ return -1;;
+ }
+
+ if ((cnt = write(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
+ SLOGE("Cannot write real block device footer\n");
+ 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;
+ }
+ }
+
+ if (key_loc[0] == '/') {
+ if (ftruncate(fd, 0x4000)) {
+ SLOGE("Cannot set footer file sizen", fname);
+ goto errout;
+ }
+ }
+
+ /* Success! */
+ rc = 0;
+
+errout:
+ close(fd);
+ return rc;
+
+}
+
+static int get_crypt_ftr_and_key(char *real_blk_name, struct crypt_mnt_ftr *crypt_ftr,
+ unsigned char *key, unsigned char *salt)
+{
+ int fd;
+ unsigned int nr_sec, cnt;
+ off64_t off;
+ int rc = -1;
+ char key_loc[PROPERTY_VALUE_MAX];
+ char *fname;
+ struct stat statbuf;
+
+ property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
+
+ 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 (statbuf.st_size != 0x4000) {
+ SLOGE("footer file %s is not the expected size!\n", fname);
+ goto errout;
+ }
+ } else {
+ SLOGE("Unexpected value for" KEY_LOC_PROP "\n");
+ return -1;;
+ }
+
+ if ( (cnt = read(fd, crypt_ftr, sizeof(struct crypt_mnt_ftr))) != sizeof(struct crypt_mnt_ftr)) {
+ SLOGE("Cannot read real block device footer\n");
+ goto errout;
+ }
+
+ if (crypt_ftr->magic != CRYPT_MNT_MAGIC) {
+ SLOGE("Bad magic for real block device %s\n", fname);
+ goto errout;
+ }
+
+ if (crypt_ftr->major_version != 1) {
+ SLOGE("Cannot understand major version %d real block device footer\n",
+ crypt_ftr->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->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;
+ }
+
+ /* Success! */
+ rc = 0;
+
+errout:
+ close(fd);
+ return rc;
+}
+
+/* Convert a binary key of specified length into an ascii hex string equivalent,
+ * without the leading 0x and with null termination
+ */
+void convert_key_to_hex_ascii(unsigned char *master_key, unsigned int keysize,
+ char *master_key_ascii)
+{
+ unsigned int i, a;
+ unsigned char nibble;
+
+ for (i=0, a=0; i<keysize; i++, a+=2) {
+ /* For each byte, write out two ascii hex digits */
+ nibble = (master_key[i] >> 4) & 0xf;
+ master_key_ascii[a] = nibble + (nibble > 9 ? 0x37 : 0x30);
+
+ nibble = master_key[i] & 0xf;
+ master_key_ascii[a+1] = nibble + (nibble > 9 ? 0x37 : 0x30);
+ }
+
+ /* Add the null termination */
+ master_key_ascii[a] = '\0';
+
+}
+
+static int create_crypto_blk_dev(struct crypt_mnt_ftr *crypt_ftr, unsigned char *master_key,
+ char *real_blk_name, char *crypto_blk_name, const char *name)
+{
+ char buffer[DM_CRYPT_BUF_SIZE];
+ char master_key_ascii[129]; /* Large enough to hold 512 bit key and null */
+ char *crypt_params;
+ struct dm_ioctl *io;
+ struct dm_target_spec *tgt;
+ unsigned int minor;
+ int fd;
+ int retval = -1;
+
+ if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
+ SLOGE("Cannot open device-mapper\n");
+ goto errout;
+ }
+
+ io = (struct dm_ioctl *) buffer;
+
+ ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
+ if (ioctl(fd, DM_DEV_CREATE, io)) {
+ SLOGE("Cannot create dm-crypt device\n");
+ goto errout;
+ }
+
+ /* Get the device status, in particular, the name of it's device file */
+ ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
+ if (ioctl(fd, DM_DEV_STATUS, io)) {
+ SLOGE("Cannot retrieve dm-crypt device status\n");
+ goto errout;
+ }
+ minor = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
+ snprintf(crypto_blk_name, MAXPATHLEN, "/dev/block/dm-%u", minor);
+
+ /* Load the mapping table for this device */
+ tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
+
+ ioctl_init(io, 4096, name, 0);
+ io->target_count = 1;
+ tgt->status = 0;
+ tgt->sector_start = 0;
+ tgt->length = crypt_ftr->fs_size;
+ strcpy(tgt->target_type, "crypt");
+
+ crypt_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
+ convert_key_to_hex_ascii(master_key, crypt_ftr->keysize, master_key_ascii);
+ sprintf(crypt_params, "%s %s 0 %s 0", crypt_ftr->crypto_type_name,
+ master_key_ascii, real_blk_name);
+ crypt_params += strlen(crypt_params) + 1;
+ crypt_params = (char *) (((unsigned long)crypt_params + 7) & ~8); /* Align to an 8 byte boundary */
+ tgt->next = crypt_params - buffer;
+
+ if (ioctl(fd, DM_TABLE_LOAD, io)) {
+ SLOGE("Cannot load dm-crypt mapping table.\n");
+ goto errout;
+ }
+
+ /* Resume this device to activate it */
+ ioctl_init(io, 4096, name, 0);
+
+ if (ioctl(fd, DM_DEV_SUSPEND, io)) {
+ SLOGE("Cannot resume the dm-crypt device\n");
+ goto errout;
+ }
+
+ /* We made it here with no errors. Woot! */
+ retval = 0;
+
+errout:
+ close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
+
+ return retval;
+}
+
+static int delete_crypto_blk_dev(char *name)
+{
+ int fd;
+ char buffer[DM_CRYPT_BUF_SIZE];
+ struct dm_ioctl *io;
+ int retval = -1;
+
+ if ((fd = open("/dev/device-mapper", O_RDWR)) < 0 ) {
+ SLOGE("Cannot open device-mapper\n");
+ goto errout;
+ }
+
+ io = (struct dm_ioctl *) buffer;
+
+ ioctl_init(io, DM_CRYPT_BUF_SIZE, name, 0);
+ if (ioctl(fd, DM_DEV_REMOVE, io)) {
+ SLOGE("Cannot remove dm-crypt device\n");
+ goto errout;
+ }
+
+ /* We made it here with no errors. Woot! */
+ retval = 0;
+
+errout:
+ close(fd); /* If fd is <0 from a failed open call, it's safe to just ignore the close error */
+
+ return retval;
+
+}
+
+static void pbkdf2(char *passwd, unsigned char *salt, unsigned char *ikey)
+{
+ /* 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 int encrypt_master_key(char *passwd, unsigned char *salt,
+ unsigned char *decrypted_master_key,
+ unsigned char *encrypted_master_key)
+{
+ 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);
+
+ /* Initialize the decryption engine */
+ if (! EVP_EncryptInit(&e_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
+ SLOGE("EVP_EncryptInit failed\n");
+ return -1;
+ }
+ EVP_CIPHER_CTX_set_padding(&e_ctx, 0); /* Turn off padding as our data is block aligned */
+
+ /* Encrypt the master key */
+ if (! EVP_EncryptUpdate(&e_ctx, encrypted_master_key, &encrypted_len,
+ decrypted_master_key, KEY_LEN_BYTES)) {
+ SLOGE("EVP_EncryptUpdate failed\n");
+ return -1;
+ }
+ if (! EVP_EncryptFinal(&e_ctx, encrypted_master_key + encrypted_len, &final_len)) {
+ SLOGE("EVP_EncryptFinal failed\n");
+ return -1;
+ }
+
+ if (encrypted_len + final_len != KEY_LEN_BYTES) {
+ SLOGE("EVP_Encryption length check failed with %d, %d bytes\n", encrypted_len, final_len);
+ return -1;
+ } else {
+ return 0;
+ }
+}
+
+static int decrypt_master_key(char *passwd, unsigned char *salt,
+ unsigned char *encrypted_master_key,
+ unsigned char *decrypted_master_key)
+{
+ 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);
+
+ /* Initialize the decryption engine */
+ if (! EVP_DecryptInit(&d_ctx, EVP_aes_128_cbc(), ikey, ikey+KEY_LEN_BYTES)) {
+ return -1;
+ }
+ EVP_CIPHER_CTX_set_padding(&d_ctx, 0); /* Turn off padding as our data is block aligned */
+ /* Decrypt the master key */
+ if (! EVP_DecryptUpdate(&d_ctx, decrypted_master_key, &decrypted_len,
+ encrypted_master_key, KEY_LEN_BYTES)) {
+ return -1;
+ }
+ if (! EVP_DecryptFinal(&d_ctx, decrypted_master_key + decrypted_len, &final_len)) {
+ return -1;
+ }
+
+ if (decrypted_len + final_len != KEY_LEN_BYTES) {
+ return -1;
+ } else {
+ return 0;
+ }
+}
+
+static int create_encrypted_random_key(char *passwd, unsigned char *master_key, unsigned char *salt)
+{
+ int fd;
+ unsigned char key_buf[KEY_LEN_BYTES];
+ EVP_CIPHER_CTX e_ctx;
+ int encrypted_len, final_len;
+
+ /* Get some random bits for a key */
+ fd = open("/dev/urandom", O_RDONLY);
+ read(fd, key_buf, sizeof(key_buf));
+ read(fd, salt, SALT_LEN);
+ close(fd);
+
+ /* Now encrypt it with the password */
+ return encrypt_master_key(passwd, salt, key_buf, master_key);
+}
+
+static int get_orig_mount_parms(char *mount_point, char *fs_type, char *real_blkdev,
+ unsigned long *mnt_flags, char *fs_options)
+{
+ char mount_point2[PROPERTY_VALUE_MAX];
+ char fs_flags[PROPERTY_VALUE_MAX];
+
+ property_get("ro.crypto.fs_type", fs_type, "");
+ property_get("ro.crypto.fs_real_blkdev", real_blkdev, "");
+ property_get("ro.crypto.fs_mnt_point", mount_point2, "");
+ property_get("ro.crypto.fs_options", fs_options, "");
+ property_get("ro.crypto.fs_flags", fs_flags, "");
+ *mnt_flags = strtol(fs_flags, 0, 0);
+
+ if (strcmp(mount_point, mount_point2)) {
+ /* Consistency check. These should match. If not, something odd happened. */
+ return -1;
+ }
+
+ return 0;
+}
+
+static int wait_and_unmount(char *mountpoint)
+{
+ int i, rc;
+#define WAIT_UNMOUNT_COUNT 20
+
+ /* Now umount the tmpfs filesystem */
+ for (i=0; i<WAIT_UNMOUNT_COUNT; i++) {
+ if (umount(mountpoint)) {
+ if (errno == EINVAL) {
+ /* EINVAL is returned if the directory is not a mountpoint,
+ * i.e. there is no filesystem mounted there. So just get out.
+ */
+ break;
+ }
+ sleep(1);
+ i++;
+ } else {
+ break;
+ }
+ }
+
+ if (i < WAIT_UNMOUNT_COUNT) {
+ SLOGD("unmounting %s succeeded\n", mountpoint);
+ rc = 0;
+ } else {
+ SLOGE("unmounting %s failed\n", mountpoint);
+ rc = -1;
+ }
+
+ return rc;
+}
+
+#define DATA_PREP_TIMEOUT 100
+static int prep_data_fs(void)
+{
+ int i;
+
+ /* Do the prep of the /data filesystem */
+ property_set("vold.post_fs_data_done", "0");
+ property_set("vold.decrypt", "trigger_post_fs_data");
+ SLOGD("Just triggered post_fs_data\n");
+
+ /* Wait a max of 25 seconds, hopefully it takes much less */
+ for (i=0; i<DATA_PREP_TIMEOUT; i++) {
+ char p[PROPERTY_VALUE_MAX];
+
+ property_get("vold.post_fs_data_done", p, "0");
+ if (*p == '1') {
+ break;
+ } else {
+ usleep(250000);
+ }
+ }
+ if (i == DATA_PREP_TIMEOUT) {
+ /* Ugh, we failed to prep /data in time. Bail. */
+ return -1;
+ } else {
+ SLOGD("post_fs_data done\n");
+ return 0;
+ }
+}
+
+int cryptfs_restart(void)
+{
+ char fs_type[32];
+ char real_blkdev[MAXPATHLEN];
+ char crypto_blkdev[MAXPATHLEN];
+ char fs_options[256];
+ unsigned long mnt_flags;
+ struct stat statbuf;
+ int rc = -1, i;
+ static int restart_successful = 0;
+
+ /* Validate that it's OK to call this routine */
+ if (! master_key_saved) {
+ SLOGE("Encrypted filesystem not validated, aborting");
+ return -1;
+ }
+
+ if (restart_successful) {
+ SLOGE("System already restarted with encrypted disk, aborting");
+ return -1;
+ }
+
+ /* Here is where we shut down the framework. The init scripts
+ * start all services in one of three classes: core, main or late_start.
+ * On boot, we start core and main. Now, we stop main, but not core,
+ * as core includes vold and a few other really important things that
+ * we need to keep running. Once main has stopped, we should be able
+ * to umount the tmpfs /data, then mount the encrypted /data.
+ * We then restart the class main, and also the class late_start.
+ * At the moment, I've only put a few things in late_start that I know
+ * are not needed to bring up the framework, and that also cause problems
+ * with unmounting the tmpfs /data, but I hope to add add more services
+ * to the late_start class as we optimize this to decrease the delay
+ * till the user is asked for the password to the filesystem.
+ */
+
+ /* The init files are setup to stop the class main when vold.decrypt is
+ * set to trigger_reset_main.
+ */
+ property_set("vold.decrypt", "trigger_reset_main");
+ SLOGD("Just asked init to shut down class main\n");
+
+ /* Now that the framework is shutdown, we should be able to umount()
+ * the tmpfs filesystem, and mount the real one.
+ */
+
+ property_get("ro.crypto.fs_crypto_blkdev", crypto_blkdev, "");
+ if (strlen(crypto_blkdev) == 0) {
+ SLOGE("fs_crypto_blkdev not set\n");
+ return -1;
+ }
+
+ if (! get_orig_mount_parms(DATA_MNT_POINT, fs_type, real_blkdev, &mnt_flags, fs_options)) {
+ SLOGD("Just got orig mount parms\n");
+
+ if (! (rc = wait_and_unmount(DATA_MNT_POINT)) ) {
+ /* If that succeeded, then mount the decrypted filesystem */
+ mount(crypto_blkdev, DATA_MNT_POINT, fs_type, mnt_flags, fs_options);
+
+ property_set("vold.decrypt", "trigger_load_persist_props");
+ /* Create necessary paths on /data */
+ if (prep_data_fs()) {
+ return -1;
+ }
+
+ /* startup service classes main and late_start */
+ property_set("vold.decrypt", "trigger_restart_framework");
+ SLOGD("Just triggered restart_framework\n");
+
+ /* Give it a few moments to get started */
+ sleep(1);
+ }
+ }
+
+ if (rc == 0) {
+ restart_successful = 1;
+ }
+
+ return rc;
+}
+
+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 fs_type[PROPERTY_VALUE_MAX];
+ char fs_options[PROPERTY_VALUE_MAX];
+ unsigned long mnt_flags;
+ char encrypted_state[PROPERTY_VALUE_MAX];
+
+ property_get("ro.crypto.state", encrypted_state, "");
+ if (strcmp(encrypted_state, "encrypted") ) {
+ SLOGE("not running with encryption, aborting");
+ return 1;
+ }
+
+ if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
+ SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
+ return -1;
+ }
+
+ if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
+ SLOGE("Error getting crypt footer and key\n");
+ return -1;
+ }
+
+ if (crypt_ftr.flags & CRYPT_ENCRYPTION_IN_PROGRESS) {
+ SLOGE("Encryption process didn't finish successfully\n");
+ return -2; /* -2 is the clue to the UI that there is no usable data on the disk,
+ * and give the user an option to wipe the disk */
+ }
+
+ /* We passed the test! We shall diminish, and return to the west */
+ return 0;
+}
+
+static int test_mount_encrypted_fs(char *passwd, char *mount_point, char *label)
+{
+ 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 crypto_blkdev[MAXPATHLEN];
+ char real_blkdev[MAXPATHLEN];
+ char fs_type[PROPERTY_VALUE_MAX];
+ char fs_options[PROPERTY_VALUE_MAX];
+ char tmp_mount_point[64];
+ unsigned long mnt_flags;
+ unsigned int orig_failed_decrypt_count;
+ char encrypted_state[PROPERTY_VALUE_MAX];
+ int rc;
+
+ property_get("ro.crypto.state", encrypted_state, "");
+ if ( master_key_saved || strcmp(encrypted_state, "encrypted") ) {
+ SLOGE("encrypted fs already validated or not running with encryption, aborting");
+ return -1;
+ }
+
+ if (get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options)) {
+ SLOGE("Error reading original mount parms for mount point %s\n", mount_point);
+ return -1;
+ }
+
+ if (get_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt)) {
+ SLOGE("Error getting crypt footer and key\n");
+ return -1;
+ }
+
+ SLOGD("crypt_ftr->fs_size = %lld\n", crypt_ftr.fs_size);
+ 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 (create_crypto_blk_dev(&crypt_ftr, decrypted_master_key,
+ real_blkdev, crypto_blkdev, label)) {
+ SLOGE("Error creating decrypted block device\n");
+ return -1;
+ }
+
+ /* If init detects an encrypted filesystme, 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
+ * Since we're here, the mount_point should be a tmpfs filesystem, so make
+ * a directory in it to test mount the decrypted filesystem.
+ */
+ sprintf(tmp_mount_point, "%s/tmp_mnt", mount_point);
+ mkdir(tmp_mount_point, 0755);
+ if ( mount(crypto_blkdev, tmp_mount_point, "ext4", MS_RDONLY, "") ) {
+ SLOGE("Error temp mounting decrypted block device\n");
+ delete_crypto_blk_dev(label);
+ crypt_ftr.failed_decrypt_count++;
+ } else {
+ /* Success, so just umount and we'll mount it properly when we restart
+ * the framework.
+ */
+ umount(tmp_mount_point);
+ crypt_ftr.failed_decrypt_count = 0;
+ }
+
+ if (orig_failed_decrypt_count != crypt_ftr.failed_decrypt_count) {
+ put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, 0, 0);
+ }
+
+ if (crypt_ftr.failed_decrypt_count) {
+ /* We failed to mount the device, so return an error */
+ rc = crypt_ftr.failed_decrypt_count;
+
+ } else {
+ /* Woot! Success! Save the name of the crypto block device
+ * so we can mount it when restarting the framework.
+ */
+ property_set("ro.crypto.fs_crypto_blkdev", crypto_blkdev);
+
+ /* Also save a the master key so we can reencrypted the key
+ * 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);
+ master_key_saved = 1;
+ rc = 0;
+ }
+
+ return rc;
+}
+
+/*
+ * Called by vold when it's asked to mount an encrypted, nonremovable volume.
+ * Setup a dm-crypt mapping, use the saved master key from
+ * setting up the /data mapping, and return the new device path.
+ */
+int cryptfs_setup_volume(const char *label, int major, int minor,
+ char *crypto_sys_path, unsigned int max_path,
+ int *new_major, int *new_minor)
+{
+ 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);
+
+ /* Update the fs_size field to be the size of the volume */
+ fd = open(real_blkdev, O_RDONLY);
+ nr_sec = get_blkdev_size(fd);
+ close(fd);
+ if (nr_sec == 0) {
+ SLOGE("Cannot get size of volume %s\n", real_blkdev);
+ return -1;
+ }
+
+ sd_crypt_ftr.fs_size = nr_sec;
+ create_crypto_blk_dev(&sd_crypt_ftr, saved_master_key, real_blkdev,
+ crypto_blkdev, label);
+
+ stat(crypto_blkdev, &statbuf);
+ *new_major = MAJOR(statbuf.st_rdev);
+ *new_minor = MINOR(statbuf.st_rdev);
+
+ /* Create path to sys entry for this block device */
+ snprintf(crypto_sys_path, max_path, "/devices/virtual/block/%s", strrchr(crypto_blkdev, '/')+1);
+
+ return 0;
+}
+
+int cryptfs_crypto_complete(void)
+{
+ return do_crypto_complete("/data");
+}
+
+int cryptfs_check_passwd(char *passwd)
+{
+ int rc = -1;
+
+ rc = test_mount_encrypted_fs(passwd, DATA_MNT_POINT, "userdata");
+
+ return rc;
+}
+
+/* Initialize a crypt_mnt_ftr structure. The keysize is
+ * defaulted to 16 bytes, and the filesystem size to 0.
+ * Presumably, at a minimum, the caller will update the
+ * filesystem size and crypto_type_name after calling this function.
+ */
+static void cryptfs_init_crypt_mnt_ftr(struct crypt_mnt_ftr *ftr)
+{
+ ftr->magic = CRYPT_MNT_MAGIC;
+ ftr->major_version = 1;
+ ftr->minor_version = 0;
+ 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';
+}
+
+static int cryptfs_enable_wipe(char *crypto_blkdev, off64_t size, int type)
+{
+ char cmdline[256];
+ 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);
+ } 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);
+ } 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);
+ } else {
+ SLOGD("Successfully created empty filesystem on %s\n", crypto_blkdev);
+ rc = 0;
+ }
+
+ 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,
+ off64_t *size_already_done, off64_t tot_size)
+{
+ int realfd, cryptofd;
+ char *buf[CRYPT_INPLACE_BUFSIZE];
+ int rc = -1;
+ off64_t numblocks, i, remainder;
+ off64_t one_pct, cur_pct, new_pct;
+ off64_t blocks_already_done, tot_numblocks;
+
+ if ( (realfd = open(real_blkdev, O_RDONLY)) < 0) {
+ SLOGE("Error opening real_blkdev %s for inplace encrypt\n", real_blkdev);
+ return -1;
+ }
+
+ if ( (cryptofd = open(crypto_blkdev, O_WRONLY)) < 0) {
+ SLOGE("Error opening crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
+ close(realfd);
+ return -1;
+ }
+
+ /* This is pretty much a simple loop of reading 4K, and writing 4K.
+ * The size passed in is the number of 512 byte sectors in the filesystem.
+ * So compute the number of whole 4K blocks we should read/write,
+ * and the remainder.
+ */
+ numblocks = size / CRYPT_SECTORS_PER_BUFSIZE;
+ remainder = size % CRYPT_SECTORS_PER_BUFSIZE;
+ tot_numblocks = tot_size / CRYPT_SECTORS_PER_BUFSIZE;
+ blocks_already_done = *size_already_done / CRYPT_SECTORS_PER_BUFSIZE;
+
+ SLOGE("Encrypting filesystem in place...");
+
+ one_pct = tot_numblocks / 100;
+ cur_pct = 0;
+ /* process the majority of the filesystem in blocks */
+ for (i=0; i<numblocks; i++) {
+ new_pct = (i + blocks_already_done) / one_pct;
+ if (new_pct > cur_pct) {
+ char buf[8];
+
+ cur_pct = new_pct;
+ snprintf(buf, sizeof(buf), "%lld", cur_pct);
+ property_set("vold.encrypt_progress", buf);
+ }
+ if (unix_read(realfd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
+ SLOGE("Error reading real_blkdev %s for inplace encrypt\n", crypto_blkdev);
+ goto errout;
+ }
+ if (unix_write(cryptofd, buf, CRYPT_INPLACE_BUFSIZE) <= 0) {
+ SLOGE("Error writing crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
+ goto errout;
+ }
+ }
+
+ /* Do any remaining sectors */
+ for (i=0; i<remainder; i++) {
+ if (unix_read(realfd, buf, 512) <= 0) {
+ SLOGE("Error reading rival sectors from real_blkdev %s for inplace encrypt\n", crypto_blkdev);
+ goto errout;
+ }
+ if (unix_write(cryptofd, buf, 512) <= 0) {
+ SLOGE("Error writing final sectors to crypto_blkdev %s for inplace encrypt\n", crypto_blkdev);
+ goto errout;
+ }
+ }
+
+ *size_already_done += size;
+ rc = 0;
+
+errout:
+ close(realfd);
+ close(cryptofd);
+
+ return rc;
+}
+
+#define CRYPTO_ENABLE_WIPE 1
+#define CRYPTO_ENABLE_INPLACE 2
+
+#define FRAMEWORK_BOOT_WAIT 60
+
+static inline int should_encrypt(struct volume_info *volume)
+{
+ return (volume->flags & (VOL_ENCRYPTABLE | VOL_NONREMOVABLE)) ==
+ (VOL_ENCRYPTABLE | VOL_NONREMOVABLE);
+}
+
+int cryptfs_enable(char *howarg, char *passwd)
+{
+ int how = 0;
+ char crypto_blkdev[MAXPATHLEN], real_blkdev[MAXPATHLEN], sd_crypto_blkdev[MAXPATHLEN];
+ char fs_type[PROPERTY_VALUE_MAX], fs_options[PROPERTY_VALUE_MAX],
+ mount_point[PROPERTY_VALUE_MAX];
+ unsigned long mnt_flags, nr_sec;
+ unsigned char master_key[KEY_LEN_BYTES], decrypted_master_key[KEY_LEN_BYTES];
+ unsigned char salt[SALT_LEN];
+ int rc=-1, fd, i, ret;
+ struct crypt_mnt_ftr crypt_ftr, sd_crypt_ftr;;
+ char tmpfs_options[PROPERTY_VALUE_MAX];
+ char encrypted_state[PROPERTY_VALUE_MAX];
+ char lockid[32] = { 0 };
+ char key_loc[PROPERTY_VALUE_MAX];
+ char fuse_sdcard[PROPERTY_VALUE_MAX];
+ char *sd_mnt_point;
+ char sd_blk_dev[256] = { 0 };
+ int num_vols;
+ struct volume_info *vol_list = 0;
+ off64_t cur_encryption_done=0, tot_encryption_size=0;
+
+ property_get("ro.crypto.state", encrypted_state, "");
+ if (strcmp(encrypted_state, "unencrypted")) {
+ SLOGE("Device is already running encrypted, aborting");
+ goto error_unencrypted;
+ }
+
+ property_get(KEY_LOC_PROP, key_loc, KEY_IN_FOOTER);
+
+ if (!strcmp(howarg, "wipe")) {
+ how = CRYPTO_ENABLE_WIPE;
+ } else if (! strcmp(howarg, "inplace")) {
+ how = CRYPTO_ENABLE_INPLACE;
+ } else {
+ /* Shouldn't happen, as CommandListener vets the args */
+ goto error_unencrypted;
+ }
+
+ get_orig_mount_parms(mount_point, fs_type, real_blkdev, &mnt_flags, fs_options);
+
+ /* Get the size of the real block device */
+ fd = open(real_blkdev, O_RDONLY);
+ if ( (nr_sec = get_blkdev_size(fd)) == 0) {
+ SLOGE("Cannot get size of block device %s\n", real_blkdev);
+ goto error_unencrypted;
+ }
+ close(fd);
+
+ /* If doing inplace encryption, make sure the orig fs doesn't include the crypto footer */
+ if ((how == CRYPTO_ENABLE_INPLACE) && (!strcmp(key_loc, KEY_IN_FOOTER))) {
+ unsigned int fs_size_sec, max_fs_size_sec;
+
+ fs_size_sec = get_fs_size(real_blkdev);
+ max_fs_size_sec = nr_sec - (CRYPT_FOOTER_OFFSET / 512);
+
+ if (fs_size_sec > max_fs_size_sec) {
+ SLOGE("Orig filesystem overlaps crypto footer region. Cannot encrypt in place.");
+ goto error_unencrypted;
+ }
+ }
+
+ /* Get a wakelock as this may take a while, and we don't want the
+ * device to sleep on us. We'll grab a partial wakelock, and if the UI
+ * wants to keep the screen on, it can grab a full wakelock.
+ */
+ snprintf(lockid, sizeof(lockid), "enablecrypto%d", (int) getpid());
+ acquire_wake_lock(PARTIAL_WAKE_LOCK, lockid);
+
+ /* Get the sdcard mount point */
+ sd_mnt_point = getenv("EXTERNAL_STORAGE");
+ if (! sd_mnt_point) {
+ sd_mnt_point = "/mnt/sdcard";
+ }
+
+ num_vols=vold_getNumDirectVolumes();
+ vol_list = malloc(sizeof(struct volume_info) * num_vols);
+ vold_getDirectVolumeList(vol_list);
+
+ for (i=0; i<num_vols; i++) {
+ if (should_encrypt(&vol_list[i])) {
+ fd = open(vol_list[i].blk_dev, O_RDONLY);
+ if ( (vol_list[i].size = get_blkdev_size(fd)) == 0) {
+ SLOGE("Cannot get size of block device %s\n", vol_list[i].blk_dev);
+ goto error_unencrypted;
+ }
+ close(fd);
+
+ ret=vold_disableVol(vol_list[i].label);
+ if ((ret < 0) && (ret != UNMOUNT_NOT_MOUNTED_ERR)) {
+ /* -2 is returned when the device exists but is not currently mounted.
+ * ignore the error and continue. */
+ SLOGE("Failed to unmount volume %s\n", vol_list[i].label);
+ goto error_unencrypted;
+ }
+ }
+ }
+
+ /* The init files are setup to stop the class main and late start when
+ * vold sets trigger_shutdown_framework.
+ */
+ property_set("vold.decrypt", "trigger_shutdown_framework");
+ SLOGD("Just asked init to shut down class main\n");
+
+ property_get("ro.crypto.fuse_sdcard", fuse_sdcard, "");
+ if (!strcmp(fuse_sdcard, "true")) {
+ /* This is a device using the fuse layer to emulate the sdcard semantics
+ * on top of the userdata partition. vold does not manage it, it is managed
+ * by the sdcard service. The sdcard service was killed by the property trigger
+ * above, so just unmount it now. We must do this _AFTER_ killing the framework,
+ * unlike the case for vold managed devices above.
+ */
+ if (wait_and_unmount(sd_mnt_point)) {
+ goto error_shutting_down;
+ }
+ }
+
+ /* Now unmount the /data partition. */
+ if (wait_and_unmount(DATA_MNT_POINT)) {
+ goto error_shutting_down;
+ }
+
+ /* Do extra work for a better UX when doing the long inplace encryption */
+ if (how == CRYPTO_ENABLE_INPLACE) {
+ /* Now that /data is unmounted, we need to mount a tmpfs
+ * /data, set a property saying we're doing inplace encryption,
+ * and restart the framework.
+ */
+ property_get("ro.crypto.tmpfs_options", tmpfs_options, "");
+ if (mount("tmpfs", DATA_MNT_POINT, "tmpfs", MS_NOATIME | MS_NOSUID | MS_NODEV,
+ tmpfs_options) < 0) {
+ goto error_shutting_down;
+ }
+ /* Tells the framework that inplace encryption is starting */
+ property_set("vold.encrypt_progress", "0");
+
+ /* restart the framework. */
+ /* Create necessary paths on /data */
+ if (prep_data_fs()) {
+ goto error_shutting_down;
+ }
+
+ /* startup service classes main and late_start */
+ property_set("vold.decrypt", "trigger_restart_min_framework");
+ SLOGD("Just triggered restart_min_framework\n");
+
+ /* OK, the framework is restarted and will soon be showing a
+ * progress bar. Time to setup an encrypted mapping, and
+ * either write a new filesystem, or encrypt in place updating
+ * the progress bar as we work.
+ */
+ }
+
+ /* 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 {
+ crypt_ftr.fs_size = nr_sec;
+ }
+ crypt_ftr.flags |= CRYPT_ENCRYPTION_IN_PROGRESS;
+ 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)) {
+ 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);
+
+ decrypt_master_key(passwd, salt, master_key, decrypted_master_key);
+ create_crypto_blk_dev(&crypt_ftr, decrypted_master_key, real_blkdev, crypto_blkdev,
+ "userdata");
+
+ /* The size of the userdata partition, and add in the vold volumes below */
+ tot_encryption_size = crypt_ftr.fs_size;
+
+ /* setup crypto mapping for all encryptable volumes handled by vold */
+ for (i=0; i<num_vols; i++) {
+ if (should_encrypt(&vol_list[i])) {
+ vol_list[i].crypt_ftr = crypt_ftr; /* gotta love struct assign */
+ vol_list[i].crypt_ftr.fs_size = vol_list[i].size;
+ create_crypto_blk_dev(&vol_list[i].crypt_ftr, decrypted_master_key,
+ vol_list[i].blk_dev, vol_list[i].crypto_blkdev,
+ vol_list[i].label);
+ tot_encryption_size += vol_list[i].size;
+ }
+ }
+
+ if (how == CRYPTO_ENABLE_WIPE) {
+ rc = cryptfs_enable_wipe(crypto_blkdev, crypt_ftr.fs_size, EXT4_FS);
+ /* Encrypt all encryptable volumes handled by vold */
+ if (!rc) {
+ for (i=0; i<num_vols; i++) {
+ if (should_encrypt(&vol_list[i])) {
+ rc = cryptfs_enable_wipe(vol_list[i].crypto_blkdev,
+ vol_list[i].crypt_ftr.fs_size, FAT_FS);
+ }
+ }
+ }
+ } else if (how == CRYPTO_ENABLE_INPLACE) {
+ rc = cryptfs_enable_inplace(crypto_blkdev, real_blkdev, crypt_ftr.fs_size,
+ &cur_encryption_done, tot_encryption_size);
+ /* Encrypt all encryptable volumes handled by vold */
+ if (!rc) {
+ for (i=0; i<num_vols; i++) {
+ if (should_encrypt(&vol_list[i])) {
+ rc = cryptfs_enable_inplace(vol_list[i].crypto_blkdev,
+ vol_list[i].blk_dev,
+ vol_list[i].crypt_ftr.fs_size,
+ &cur_encryption_done, tot_encryption_size);
+ }
+ }
+ }
+ if (!rc) {
+ /* The inplace routine never actually sets the progress to 100%
+ * due to the round down nature of integer division, so set it here */
+ property_set("vold.encrypt_progress", "100");
+ }
+ } else {
+ /* Shouldn't happen */
+ SLOGE("cryptfs_enable: internal error, unknown option\n");
+ goto error_unencrypted;
+ }
+
+ /* Undo the dm-crypt mapping whether we succeed or not */
+ delete_crypto_blk_dev("userdata");
+ for (i=0; i<num_vols; i++) {
+ if (should_encrypt(&vol_list[i])) {
+ delete_crypto_blk_dev(vol_list[i].label);
+ }
+ }
+
+ free(vol_list);
+
+ if (! rc) {
+ /* Success */
+
+ /* 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);
+
+ sleep(2); /* Give the UI a chance to show 100% progress */
+ android_reboot(ANDROID_RB_RESTART, 0, 0);
+ } else {
+ property_set("vold.encrypt_progress", "error_partially_encrypted");
+ release_wake_lock(lockid);
+ return -1;
+ }
+
+ /* hrm, the encrypt step claims success, but the reboot failed.
+ * This should not happen.
+ * Set the property and return. Hope the framework can deal with it.
+ */
+ property_set("vold.encrypt_progress", "error_reboot_failed");
+ release_wake_lock(lockid);
+ return rc;
+
+error_unencrypted:
+ free(vol_list);
+ property_set("vold.encrypt_progress", "error_not_encrypted");
+ if (lockid[0]) {
+ release_wake_lock(lockid);
+ }
+ return -1;
+
+error_shutting_down:
+ /* we failed, and have not encrypted anthing, so the users's data is still intact,
+ * but the framework is stopped and not restarted to show the error, so it's up to
+ * 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);
+
+ /* shouldn't get here */
+ property_set("vold.encrypt_progress", "error_shutting_down");
+ free(vol_list);
+ if (lockid[0]) {
+ release_wake_lock(lockid);
+ }
+ return -1;
+}
+
+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];
+
+ /* This is only allowed after we've successfully decrypted the master key */
+ if (! master_key_saved) {
+ SLOGE("Key not saved, aborting");
+ return -1;
+ }
+
+ property_get("ro.crypto.fs_real_blkdev", 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)) {
+ SLOGE("Error getting crypt footer and key");
+ return -1;
+ }
+
+ encrypt_master_key(newpw, salt, saved_master_key, encrypted_master_key);
+
+ /* save the key */
+ put_crypt_ftr_and_key(real_blkdev, &crypt_ftr, encrypted_master_key, salt);
+
+ return 0;
+}
diff --git a/cryptfs.h b/cryptfs.h
new file mode 100644
index 0000000..8b4c37b
--- /dev/null
+++ b/cryptfs.h
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+/* 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.
+ * Obviously, the filesystem does not include the last 16 kbytes
+ * of the partition.
+ */
+
+#define CRYPT_FOOTER_OFFSET 0x4000
+
+#define MAX_CRYPTO_TYPE_NAME_LEN 64
+
+#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. */
+#define CRYPT_ENCRYPTION_IN_PROGRESS 0x2 /* Set when starting encryption,
+ * clear when done before rebooting */
+
+#define CRYPT_MNT_MAGIC 0xD0B5B1C4
+
+#define __le32 unsigned int
+#define __le16 unsigned short int
+
+struct crypt_mnt_ftr {
+ __le32 magic; /* See above */
+ __le16 major_version;
+ __le16 minor_version;
+ __le32 ftr_size; /* in bytes, not including key following */
+ __le32 flags; /* See above */
+ __le32 keysize; /* in bytes */
+ __le32 spare1; /* ignored */
+ __le64 fs_size; /* Size of the encrypted fs, in 512 byte sectors */
+ __le32 failed_decrypt_count; /* count of # of failed attempts to decrypt and
+ mount, set to 0 on successful mount */
+ unsigned char crypto_type_name[MAX_CRYPTO_TYPE_NAME_LEN]; /* The type of encryption
+ needed to decrypt this
+ partition, null terminated */
+};
+
+struct volume_info {
+ unsigned int size;
+ unsigned int flags;
+ struct crypt_mnt_ftr crypt_ftr;
+ char mnt_point[256];
+ char blk_dev[256];
+ char crypto_blkdev[256];
+ char label[256];
+};
+#define VOL_NONREMOVABLE 0x1
+#define VOL_ENCRYPTABLE 0x2
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ int cryptfs_crypto_complete(void);
+ int cryptfs_check_passwd(char *pw);
+ int cryptfs_restart(void);
+ int cryptfs_enable(char *flag, char *passwd);
+ int cryptfs_changepw(char *newpw);
+ int cryptfs_setup_volume(const char *label, int major, int minor,
+ char *crypto_dev_path, unsigned int max_pathlen,
+ int *new_major, int *new_minor);
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/logwrapper.c b/logwrapper.c
index b7d2f68..13c076d 100644
--- a/logwrapper.c
+++ b/logwrapper.c
@@ -155,7 +155,6 @@
if (write(fd, text, strlen(text)) < 0) {
LOG(LOG_WARN, "logwrapper",
"Unable to background process (%s)", strerror(errno));
- close(fd);
}
close(fd);
} else {
diff --git a/main.cpp b/main.cpp
index f97632b..5924fe4 100644
--- a/main.cpp
+++ b/main.cpp
@@ -32,6 +32,7 @@
#include "CommandListener.h"
#include "NetlinkManager.h"
#include "DirectVolume.h"
+#include "cryptfs.h"
static int process_config(VolumeManager *vm);
static void coldboot(const char *path);
@@ -141,6 +142,22 @@
}
}
+static int parse_mount_flags(char *mount_flags)
+{
+ char *save_ptr;
+ int flags = 0;
+
+ if (strcasestr(mount_flags, "encryptable")) {
+ flags |= VOL_ENCRYPTABLE;
+ }
+
+ if (strcasestr(mount_flags, "nonremovable")) {
+ flags |= VOL_NONREMOVABLE;
+ }
+
+ return flags;
+}
+
static int process_config(VolumeManager *vm) {
FILE *fp;
int n = 0;
@@ -151,8 +168,10 @@
}
while(fgets(line, sizeof(line), fp)) {
- char *next = line;
- char *type, *label, *mount_point;
+ const char *delim = " \t";
+ char *save_ptr;
+ char *type, *label, *mount_point, *mount_flags, *sysfs_path;
+ int flags;
n++;
line[strlen(line)-1] = '\0';
@@ -160,24 +179,24 @@
if (line[0] == '#' || line[0] == '\0')
continue;
- if (!(type = strsep(&next, " \t"))) {
+ if (!(type = strtok_r(line, delim, &save_ptr))) {
SLOGE("Error parsing type");
goto out_syntax;
}
- if (!(label = strsep(&next, " \t"))) {
+ if (!(label = strtok_r(NULL, delim, &save_ptr))) {
SLOGE("Error parsing label");
goto out_syntax;
}
- if (!(mount_point = strsep(&next, " \t"))) {
+ if (!(mount_point = strtok_r(NULL, delim, &save_ptr))) {
SLOGE("Error parsing mount point");
goto out_syntax;
}
if (!strcmp(type, "dev_mount")) {
DirectVolume *dv = NULL;
- char *part, *sysfs_path;
+ char *part;
- if (!(part = strsep(&next, " \t"))) {
+ if (!(part = strtok_r(NULL, delim, &save_ptr))) {
SLOGE("Error parsing partition");
goto out_syntax;
}
@@ -192,13 +211,27 @@
dv = new DirectVolume(vm, label, mount_point, atoi(part));
}
- while((sysfs_path = strsep(&next, " \t"))) {
+ while ((sysfs_path = strtok_r(NULL, delim, &save_ptr))) {
+ if (*sysfs_path != '/') {
+ /* If the first character is not a '/', it must be flags */
+ break;
+ }
if (dv->addPath(sysfs_path)) {
SLOGE("Failed to add devpath %s to volume %s", sysfs_path,
label);
goto out_fail;
}
}
+
+ /* If sysfs_path is non-null at this point, then it contains
+ * the optional flags for this volume
+ */
+ if (sysfs_path)
+ flags = parse_mount_flags(sysfs_path);
+ else
+ flags = 0;
+ dv->setFlags(flags);
+
vm->addVolume(dv);
} else if (!strcmp(type, "map_mount")) {
} else {
diff --git a/vdc.c b/vdc.c
index 4f94ad3..1eb674c 100644
--- a/vdc.c
+++ b/vdc.c
@@ -21,6 +21,7 @@
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
+#include <stdlib.h>
#include <sys/socket.h>
#include <sys/select.h>
@@ -56,6 +57,7 @@
static int do_cmd(int sock, int argc, char **argv) {
char final_cmd[255] = { '\0' };
int i;
+ int ret;
for (i = 1; i < argc; i++) {
char *cmp;
@@ -65,7 +67,9 @@
else
asprintf(&cmp, "\"%s\"%s", argv[i], (i == (argc -1)) ? "" : " ");
- strcat(final_cmd, cmp);
+ ret = strlcat(final_cmd, cmp, sizeof(final_cmd));
+ if (ret >= sizeof(final_cmd))
+ abort();
free(cmp);
}