summaryrefslogtreecommitdiff
path: root/libfscrypt
diff options
context:
space:
mode:
authorEric Biggers <ebiggers@google.com>2018-10-23 13:39:07 -0700
committerEric Biggers <ebiggers@google.com>2018-10-25 17:10:15 -0700
commitb46c3591e1e2b091d0fb727715a8d617dfc80aa6 (patch)
tree8336261d742bfe2a0dbe7467cf3093efec4f38ee /libfscrypt
parent67f1b299ade36c4b419d15fd1d63e1dfb5b222f2 (diff)
downloadextras-b46c3591e1e2b091d0fb727715a8d617dfc80aa6.tar.gz
Refactor "ext4 encryption" code into libfscrypt
File-based encryption related code no longer belongs in ext4_utils, as it is now used on both ext4 and f2fs, since both filesystems share the same kernel API for encryption. Refactor it into its own library, libfscrypt. Note that the keyring is renamed from "e4crypt" to "fscrypt", which is technically a user-visible change, but as far as I know nothing depends on it other than vold which is being updated too. Test: built, booted device with f2fs encryption Change-Id: I3c302564262412a5d5e672bd213e7cfada5f49cc
Diffstat (limited to 'libfscrypt')
-rw-r--r--libfscrypt/Android.bp17
-rw-r--r--libfscrypt/MODULE_LICENSE_APACHE20
-rw-r--r--libfscrypt/NOTICE190
-rw-r--r--libfscrypt/fscrypt.cpp285
-rw-r--r--libfscrypt/fscrypt_init_extensions.cpp136
-rw-r--r--libfscrypt/include/fscrypt/fscrypt.h39
-rw-r--r--libfscrypt/include/fscrypt/fscrypt_init_extensions.h33
7 files changed, 700 insertions, 0 deletions
diff --git a/libfscrypt/Android.bp b/libfscrypt/Android.bp
new file mode 100644
index 00000000..cca38235
--- /dev/null
+++ b/libfscrypt/Android.bp
@@ -0,0 +1,17 @@
+// Copyright 2018 The Android Open Source Project
+
+cc_library {
+ name: "libfscrypt",
+ recovery_available: true,
+ srcs: [
+ "fscrypt.cpp",
+ "fscrypt_init_extensions.cpp",
+ ],
+ export_include_dirs: ["include"],
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "libkeyutils",
+ "liblogwrap",
+ ],
+}
diff --git a/libfscrypt/MODULE_LICENSE_APACHE2 b/libfscrypt/MODULE_LICENSE_APACHE2
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/libfscrypt/MODULE_LICENSE_APACHE2
diff --git a/libfscrypt/NOTICE b/libfscrypt/NOTICE
new file mode 100644
index 00000000..8530865d
--- /dev/null
+++ b/libfscrypt/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2015, 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.
+
+ 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.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/libfscrypt/fscrypt.cpp b/libfscrypt/fscrypt.cpp
new file mode 100644
index 00000000..59297318
--- /dev/null
+++ b/libfscrypt/fscrypt.cpp
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2015 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 "fscrypt/fscrypt.h"
+
+#include <array>
+
+#include <asm/ioctl.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/syscall.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <cutils/properties.h>
+#include <logwrap/logwrap.h>
+#include <utils/misc.h>
+
+// TODO Include these definitions from <linux/fs.h>
+
+#define FS_KEY_DESCRIPTOR_SIZE 8
+#define FS_KEY_DESCRIPTOR_SIZE_HEX 17
+
+struct fscrypt_policy {
+ uint8_t version;
+ uint8_t contents_encryption_mode;
+ uint8_t filenames_encryption_mode;
+ uint8_t flags;
+ uint8_t master_key_descriptor[FS_KEY_DESCRIPTOR_SIZE];
+} __attribute__((__packed__));
+
+#define FS_ENCRYPTION_MODE_AES_256_XTS 1
+#define FS_ENCRYPTION_MODE_AES_256_CTS 4
+#define FS_ENCRYPTION_MODE_AES_256_HEH 126
+#define FS_ENCRYPTION_MODE_PRIVATE 127
+
+#define FS_POLICY_FLAGS_PAD_4 0x00
+#define FS_POLICY_FLAGS_PAD_8 0x01
+#define FS_POLICY_FLAGS_PAD_16 0x02
+#define FS_POLICY_FLAGS_PAD_32 0x03
+#define FS_POLICY_FLAGS_PAD_MASK 0x03
+#define FS_POLICY_FLAGS_VALID 0x03
+
+#define FS_IOC_SET_ENCRYPTION_POLICY _IOR('f', 19, struct fscrypt_policy)
+#define FS_IOC_GET_ENCRYPTION_POLICY _IOW('f', 21, struct fscrypt_policy)
+
+#define HEX_LOOKUP "0123456789abcdef"
+
+bool fscrypt_is_native() {
+ char value[PROPERTY_VALUE_MAX];
+ property_get("ro.crypto.type", value, "none");
+ return !strcmp(value, "file");
+}
+
+static void log_ls(const char* dirname) {
+ std::array<const char*, 3> argv = {"ls", "-laZ", dirname};
+ int status = 0;
+ auto res =
+ android_fork_execvp(argv.size(), const_cast<char**>(argv.data()), &status, false, true);
+ if (res != 0) {
+ PLOG(ERROR) << argv[0] << " " << argv[1] << " " << argv[2] << "failed";
+ return;
+ }
+ if (!WIFEXITED(status)) {
+ LOG(ERROR) << argv[0] << " " << argv[1] << " " << argv[2]
+ << " did not exit normally, status: " << status;
+ return;
+ }
+ if (WEXITSTATUS(status) != 0) {
+ LOG(ERROR) << argv[0] << " " << argv[1] << " " << argv[2]
+ << " returned failure: " << WEXITSTATUS(status);
+ return;
+ }
+}
+
+static void policy_to_hex(const char* policy, char* hex) {
+ for (size_t i = 0, j = 0; i < FS_KEY_DESCRIPTOR_SIZE; i++) {
+ hex[j++] = HEX_LOOKUP[(policy[i] & 0xF0) >> 4];
+ hex[j++] = HEX_LOOKUP[policy[i] & 0x0F];
+ }
+ hex[FS_KEY_DESCRIPTOR_SIZE_HEX - 1] = '\0';
+}
+
+static bool is_dir_empty(const char *dirname, bool *is_empty)
+{
+ int n = 0;
+ auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(dirname), closedir);
+ if (!dirp) {
+ PLOG(ERROR) << "Unable to read directory: " << dirname;
+ return false;
+ }
+ for (;;) {
+ errno = 0;
+ auto entry = readdir(dirp.get());
+ if (!entry) {
+ if (errno) {
+ PLOG(ERROR) << "Unable to read directory: " << dirname;
+ return false;
+ }
+ break;
+ }
+ if (strcmp(entry->d_name, "lost+found") != 0) { // Skip lost+found
+ ++n;
+ if (n > 2) {
+ *is_empty = false;
+ return true;
+ }
+ }
+ }
+ *is_empty = true;
+ return true;
+}
+
+static uint8_t fscrypt_get_policy_flags(int filenames_encryption_mode) {
+ if (filenames_encryption_mode == FS_ENCRYPTION_MODE_AES_256_CTS) {
+ // Use legacy padding with our original filenames encryption mode.
+ return FS_POLICY_FLAGS_PAD_4;
+ }
+ // With a new mode we can use the better padding flag without breaking existing devices: pad
+ // filenames with zeroes to the next 16-byte boundary. This is more secure (helps hide the
+ // length of filenames) and makes the inputs evenly divisible into blocks which is more
+ // efficient for encryption and decryption.
+ return FS_POLICY_FLAGS_PAD_16;
+}
+
+static bool fscrypt_policy_set(const char *directory, const char *policy,
+ size_t policy_length,
+ int contents_encryption_mode,
+ int filenames_encryption_mode) {
+ if (policy_length != FS_KEY_DESCRIPTOR_SIZE) {
+ LOG(ERROR) << "Policy wrong length: " << policy_length;
+ return false;
+ }
+ char policy_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
+ policy_to_hex(policy, policy_hex);
+
+ int fd = open(directory, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd == -1) {
+ PLOG(ERROR) << "Failed to open directory " << directory;
+ return false;
+ }
+
+ fscrypt_policy fp;
+ fp.version = 0;
+ fp.contents_encryption_mode = contents_encryption_mode;
+ fp.filenames_encryption_mode = filenames_encryption_mode;
+ fp.flags = fscrypt_get_policy_flags(filenames_encryption_mode);
+ memcpy(fp.master_key_descriptor, policy, FS_KEY_DESCRIPTOR_SIZE);
+ if (ioctl(fd, FS_IOC_SET_ENCRYPTION_POLICY, &fp)) {
+ PLOG(ERROR) << "Failed to set encryption policy for " << directory << " to " << policy_hex
+ << " modes " << contents_encryption_mode << "/" << filenames_encryption_mode;
+ close(fd);
+ return false;
+ }
+ close(fd);
+
+ LOG(INFO) << "Policy for " << directory << " set to " << policy_hex
+ << " modes " << contents_encryption_mode << "/" << filenames_encryption_mode;
+ return true;
+}
+
+static bool fscrypt_policy_get(const char *directory, char *policy,
+ size_t policy_length,
+ int contents_encryption_mode,
+ int filenames_encryption_mode) {
+ if (policy_length != FS_KEY_DESCRIPTOR_SIZE) {
+ LOG(ERROR) << "Policy wrong length: " << policy_length;
+ return false;
+ }
+
+ int fd = open(directory, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd == -1) {
+ PLOG(ERROR) << "Failed to open directory " << directory;
+ return false;
+ }
+
+ fscrypt_policy fp;
+ memset(&fp, 0, sizeof(fscrypt_policy));
+ if (ioctl(fd, FS_IOC_GET_ENCRYPTION_POLICY, &fp) != 0) {
+ PLOG(ERROR) << "Failed to get encryption policy for " << directory;
+ close(fd);
+ log_ls(directory);
+ return false;
+ }
+ close(fd);
+
+ if ((fp.version != 0)
+ || (fp.contents_encryption_mode != contents_encryption_mode)
+ || (fp.filenames_encryption_mode != filenames_encryption_mode)
+ || (fp.flags !=
+ fscrypt_get_policy_flags(filenames_encryption_mode))) {
+ LOG(ERROR) << "Failed to find matching encryption policy for " << directory;
+ return false;
+ }
+ memcpy(policy, fp.master_key_descriptor, FS_KEY_DESCRIPTOR_SIZE);
+
+ return true;
+}
+
+static bool fscrypt_policy_check(const char *directory, const char *policy,
+ size_t policy_length,
+ int contents_encryption_mode,
+ int filenames_encryption_mode) {
+ if (policy_length != FS_KEY_DESCRIPTOR_SIZE) {
+ LOG(ERROR) << "Policy wrong length: " << policy_length;
+ return false;
+ }
+ char existing_policy[FS_KEY_DESCRIPTOR_SIZE];
+ if (!fscrypt_policy_get(directory, existing_policy, FS_KEY_DESCRIPTOR_SIZE,
+ contents_encryption_mode,
+ filenames_encryption_mode)) return false;
+ char existing_policy_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
+
+ policy_to_hex(existing_policy, existing_policy_hex);
+
+ if (memcmp(policy, existing_policy, FS_KEY_DESCRIPTOR_SIZE) != 0) {
+ char policy_hex[FS_KEY_DESCRIPTOR_SIZE_HEX];
+ policy_to_hex(policy, policy_hex);
+ LOG(ERROR) << "Found policy " << existing_policy_hex << " at " << directory
+ << " which doesn't match expected value " << policy_hex;
+ log_ls(directory);
+ return false;
+ }
+ LOG(INFO) << "Found policy " << existing_policy_hex << " at " << directory
+ << " which matches expected value";
+ return true;
+}
+
+int fscrypt_policy_ensure(const char *directory, const char *policy,
+ size_t policy_length,
+ const char *contents_encryption_mode,
+ const char *filenames_encryption_mode) {
+ int contents_mode = 0;
+ int filenames_mode = 0;
+
+ if (!strcmp(contents_encryption_mode, "software") ||
+ !strcmp(contents_encryption_mode, "aes-256-xts")) {
+ contents_mode = FS_ENCRYPTION_MODE_AES_256_XTS;
+ } else if (!strcmp(contents_encryption_mode, "ice")) {
+ contents_mode = FS_ENCRYPTION_MODE_PRIVATE;
+ } else {
+ LOG(ERROR) << "Invalid file contents encryption mode: "
+ << contents_encryption_mode;
+ return -1;
+ }
+
+ if (!strcmp(filenames_encryption_mode, "aes-256-cts")) {
+ filenames_mode = FS_ENCRYPTION_MODE_AES_256_CTS;
+ } else if (!strcmp(filenames_encryption_mode, "aes-256-heh")) {
+ filenames_mode = FS_ENCRYPTION_MODE_AES_256_HEH;
+ } else {
+ LOG(ERROR) << "Invalid file names encryption mode: "
+ << filenames_encryption_mode;
+ return -1;
+ }
+
+ bool is_empty;
+ if (!is_dir_empty(directory, &is_empty)) return -1;
+ if (is_empty) {
+ if (!fscrypt_policy_set(directory, policy, policy_length,
+ contents_mode, filenames_mode)) return -1;
+ } else {
+ if (!fscrypt_policy_check(directory, policy, policy_length,
+ contents_mode, filenames_mode)) return -1;
+ }
+ return 0;
+}
diff --git a/libfscrypt/fscrypt_init_extensions.cpp b/libfscrypt/fscrypt_init_extensions.cpp
new file mode 100644
index 00000000..af50a0f8
--- /dev/null
+++ b/libfscrypt/fscrypt_init_extensions.cpp
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2016 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 "fscrypt/fscrypt.h"
+#include "fscrypt/fscrypt_init_extensions.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <string>
+#include <vector>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
+#include <cutils/properties.h>
+#include <cutils/sockets.h>
+#include <keyutils.h>
+#include <logwrap/logwrap.h>
+
+#define TAG "fscrypt"
+
+static const std::string arbitrary_sequence_number = "42";
+
+static int set_system_de_policy_on(char const* dir);
+
+int fscrypt_install_keyring()
+{
+ key_serial_t device_keyring = add_key("keyring", "fscrypt", 0, 0,
+ KEY_SPEC_SESSION_KEYRING);
+
+ if (device_keyring == -1) {
+ PLOG(ERROR) << "Failed to create keyring";
+ return -1;
+ }
+
+ LOG(INFO) << "Keyring created with id " << device_keyring << " in process " << getpid();
+
+ return 0;
+}
+
+int fscrypt_set_directory_policy(const char* dir)
+{
+ if (!dir || strncmp(dir, "/data/", 6)) {
+ return 0;
+ }
+
+ // Special-case /data/media/obb per b/64566063
+ if (strcmp(dir, "/data/media/obb") == 0) {
+ // Try to set policy on this directory, but if it is non-empty this may fail.
+ set_system_de_policy_on(dir);
+ return 0;
+ }
+
+ // Only set policy on first level /data directories
+ // To make this less restrictive, consider using a policy file.
+ // However this is overkill for as long as the policy is simply
+ // to apply a global policy to all /data folders created via makedir
+ if (strchr(dir + 6, '/')) {
+ return 0;
+ }
+
+ // Special case various directories that must not be encrypted,
+ // often because their subdirectories must be encrypted.
+ // This isn't a nice way to do this, see b/26641735
+ std::vector<std::string> directories_to_exclude = {
+ "lost+found",
+ "system_ce", "system_de",
+ "misc_ce", "misc_de",
+ "vendor_ce", "vendor_de",
+ "media",
+ "data", "user", "user_de",
+ "apex",
+ };
+ std::string prefix = "/data/";
+ for (auto d: directories_to_exclude) {
+ if ((prefix + d) == dir) {
+ LOG(INFO) << "Not setting policy on " << dir;
+ return 0;
+ }
+ }
+ return set_system_de_policy_on(dir);
+}
+
+static int set_system_de_policy_on(char const* dir) {
+ std::string ref_filename = std::string("/data") + fscrypt_key_ref;
+ std::string policy;
+ if (!android::base::ReadFileToString(ref_filename, &policy)) {
+ LOG(ERROR) << "Unable to read system policy to set on " << dir;
+ return -1;
+ }
+
+ auto type_filename = std::string("/data") + fscrypt_key_mode;
+ std::string modestring;
+ if (!android::base::ReadFileToString(type_filename, &modestring)) {
+ LOG(ERROR) << "Cannot read mode";
+ }
+
+ std::vector<std::string> modes = android::base::Split(modestring, ":");
+
+ if (modes.size() < 1 || modes.size() > 2) {
+ LOG(ERROR) << "Invalid encryption mode string: " << modestring;
+ return -1;
+ }
+
+ LOG(INFO) << "Setting policy on " << dir;
+ int result = fscrypt_policy_ensure(dir, policy.c_str(), policy.length(),
+ modes[0].c_str(),
+ modes.size() >= 2 ?
+ modes[1].c_str() : "aes-256-cts");
+ if (result) {
+ LOG(ERROR) << android::base::StringPrintf(
+ "Setting %02x%02x%02x%02x policy on %s failed!",
+ policy[0], policy[1], policy[2], policy[3], dir);
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/libfscrypt/include/fscrypt/fscrypt.h b/libfscrypt/include/fscrypt/fscrypt.h
new file mode 100644
index 00000000..8a68b935
--- /dev/null
+++ b/libfscrypt/include/fscrypt/fscrypt.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef _FSCRYPT_H_
+#define _FSCRYPT_H_
+
+#include <sys/cdefs.h>
+#include <stdbool.h>
+#include <cutils/multiuser.h>
+
+__BEGIN_DECLS
+
+bool fscrypt_is_native();
+
+int fscrypt_policy_ensure(const char *directory, const char *policy,
+ size_t policy_length,
+ const char *contents_encryption_mode,
+ const char *filenames_encryption_mode);
+
+static const char* fscrypt_unencrypted_folder = "/unencrypted";
+static const char* fscrypt_key_ref = "/unencrypted/ref";
+static const char* fscrypt_key_mode = "/unencrypted/mode";
+
+__END_DECLS
+
+#endif // _FSCRYPT_H_
diff --git a/libfscrypt/include/fscrypt/fscrypt_init_extensions.h b/libfscrypt/include/fscrypt/fscrypt_init_extensions.h
new file mode 100644
index 00000000..2b6c46e1
--- /dev/null
+++ b/libfscrypt/include/fscrypt/fscrypt_init_extensions.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#ifndef _FSCRYPT_INIT_EXTENSIONS_H_
+#define _FSCRYPT_INIT_EXTENSIONS_H_
+
+#include <sys/cdefs.h>
+#include <stdbool.h>
+#include <cutils/multiuser.h>
+
+__BEGIN_DECLS
+
+// These functions assume they are being called from init
+// They will not operate properly outside of init
+int fscrypt_install_keyring();
+int fscrypt_set_directory_policy(const char* path);
+
+__END_DECLS
+
+#endif // _FSCRYPT_INIT_EXTENSIONS_H_