From f7510fe1d4e20527882b7e973aee44f103ed8b49 Mon Sep 17 00:00:00 2001
From: Arie Peterson <arie@greenhost.nl>
Date: Wed, 28 Jun 2017 13:58:25 +0200
Subject: [PATCH] Repartition and populate config partition on init

Extend the `encryption/add` command to repartition the encrypted container,
copy the authorized_keys file to the configuration partition, generate a new
ssh host key for the dropbear running in the initrd, and reboot after it's
done.
---
 src/api/encryption_add.c       | 211 +++++++++++++++++++++++++++------
 src/api/encryption_unlock.c    |   4 +-
 src/auxiliary.c                |  14 +++
 src/cryptops-api.c             |  12 +-
 src/encryption_functions.c     |  13 +-
 src/includes/common-includes.h |   2 +
 src/includes/settings.h        |  13 +-
 7 files changed, 222 insertions(+), 47 deletions(-)

diff --git a/src/api/encryption_add.c b/src/api/encryption_add.c
index 554300d..bb5ea56 100644
--- a/src/api/encryption_add.c
+++ b/src/api/encryption_add.c
@@ -1,25 +1,36 @@
 /**
  * Callback function for encrypting an unencrypted device.
  * It proceeds as follows:
- * 1. check if the device isn't already encrypted;
- * 2. mount the unencrypted device;
- * 3. determine the total size of the files on the device, and guess if they
- *    will fit into memory;
- * 4. rsync all files from the unencrypted device to memory;
- * 5. unmount the unencrypted device;
- * 6. initialise a new encrypted container on the same device, replacing the
-      unencrypted contents, and unlock it for use;
- * 7. create a new filesystem inside the new container, and mount it;
- * 8. rsync all files back from memory to this newly encrypted device;
- * 9. unmount the new filesystem, and lock the encrypted container.
+ * 1.  check if the device isn't already encrypted;
+ * 2.  mount the unencrypted device;
+ * 3.  determine the total size of the files on the device, and guess if they
+ *     will fit into memory;
+ * 4.  rsync all files from the unencrypted device to memory;
+ * 5.  collect existing authorised ssh keys from the root disk;
+ * 6.  repartition the disk:
+ *     . a small partition to hold unencrypted data for use from the initrd,
+ *       like the dropbear ssh host keys and user's ssh public keys;
+ *     . a big partition for the actual encrypted root disk;
+ * 7.  create a filesystem on the first partition;
+ * 8.  generate ssh host keys for dropbear;
+ * 9.  copy these new ssh host keys and the authorised ssh keys collected
+ *     earlier onto the small partition.
+ * 10. unmount the unencrypted device;
+ * 11. initialise a new encrypted container on the same device, replacing the
+ *     unencrypted contents, and unlock it for use;
+ * 12. create a new filesystem inside the new container, and mount it;
+ * 13. rsync all files back from memory to this newly encrypted device;
+ * 14. unmount the new filesystem, and lock the encrypted container;
+ * 15. reboot.
  * @param[in]   request   incoming HTTP request
  * @param[out]  response  HTTP response to the request
- * @param[in]   user_data extra data to pass between main thread and callbacks
+ * @param[in]   user_data extra data to pass between handler and main thread
  * @return                internal status code
  */
 int callback_encryption_add(const struct _u_request * request,
     struct _u_response * response, void * user_data)
 {
+    bool * reboot = (bool *)user_data;
     int r;
 
     // Read the encryption password from the request body.
@@ -32,7 +43,7 @@ int callback_encryption_add(const struct _u_request * request,
     }
  
     // Check if the device isn't already encrypted.
-    if (is_encrypted_device(CONTAINER_DEVICE))
+    if (is_encrypted_device(ROOT_DEVICE))
     {
         // The device is already encrypted; we don't want to encrypt it again.
         return send_simple_response(response, 500, "error",
@@ -40,11 +51,11 @@ int callback_encryption_add(const struct _u_request * request,
     }
 
     // Mount the filesystem on the unencrypted device.
-    r = temporary_mount(CONTAINER_DEVICE, UNENCRYPTED_MOUNTPOINT,
+    r = temporary_mount(ROOT_DEVICE, UNENCRYPTED_MOUNTPOINT,
         FILESYSTEM_TYPE);
     if (r != 0)
     {
-        printf("mounting root disk failed: return code %d", r);
+        printf("mounting root disk failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "mounting root disk failed");
     }
@@ -54,7 +65,7 @@ int callback_encryption_add(const struct _u_request * request,
     if (size < 0)
     {
         // Something went wrong in determining the filesystem usage.
-        printf("determining filesystem usage failed: return code %lu", size);
+        printf("determining filesystem usage failed: return code %lu\n", size);
         return send_simple_response(response, 500, "error",
            "determining filesystem usage failed");
     }
@@ -79,7 +90,7 @@ int callback_encryption_add(const struct _u_request * request,
     r = system(command);
     if(r != 0)
     {
-        printf("copying rootdisk contents into memory failed: return code %d",
+        printf("copying rootdisk contents into memory failed: return code %d\n",
             r);
         return send_simple_response(response, 500, "error",
             "copying rootdisk contents into memory failed");
@@ -90,27 +101,146 @@ int callback_encryption_add(const struct _u_request * request,
     r = umount(UNENCRYPTED_MOUNTPOINT);
     if (r != 0)
     {
-        printf("unmounting encrypted device failed: return code %d", r);
+        printf("unmounting encrypted device failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "unmounting unencrypted disk failed");
     }
 
+    // Check whether the authorized_keys file exists on root device.
+    char * authorized_keys_path = NULL;
+    asprintf(&authorized_keys_path, "%s/root/.ssh/authorized_keys",
+        TMP_LOCATION);
+    struct stat st = {0};
+    if (stat(authorized_keys_path, &st) == -1)
+    {
+        printf("authorized_keys not found on root disk at %s\n",
+            authorized_keys_path);
+        return send_simple_response(response, 500, "error",
+           "authorized_keys not found on root disk");
+    }
+
+    // Re-partition device.
+    printf("repartitioning device %s\n", ROOT_DEVICE);
+    command = NULL;
+    asprintf(&command, "sgdisk -a 8192 -n 1:0:48M -N 2 %s", ROOT_DEVICE);
+    r = system(command);
+    if (r != 0)
+    {
+        printf("partitioning root device failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "partitioning root device failed");
+    }
+
+    // Inform kernel of partitioning changes.
+    printf("running partprobe\n");
+    command = NULL;
+    asprintf(&command, "partprobe");
+    r = system(command);
+    if (r != 0)
+    {
+        printf("partprobe: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "partprobe failed");
+    }
+    // Sleep for a little while.
+    // This seems necessary for the newly created partitions to appear as
+    // devices.
+    printf("waiting a bit...\n");
+    command = NULL;
+    asprintf(&command, "sleep 2");
+    r = system(command);
+
+    // Create filesystem on the small partition.
+    printf("creating filesystem on unencrypted partition\n");
+    command = NULL;
+    asprintf(&command, "mkfs -t %s %s", FILESYSTEM_TYPE,
+        ROOT_SMALL_PARTITION_DEVICE);
+    printf("command: %s\n", command);
+    r = system(command);
+    if (r != 0)
+    {
+        printf("creating filesystem failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "creating filesystem inside encrypted container failed");
+    }
+
+    // Mount the small partition.
+    printf("mounting small partition\n");
+    r = temporary_mount(ROOT_SMALL_PARTITION_DEVICE, SMALL_MOUNTPOINT,
+        FILESYSTEM_TYPE);
+    if (r != 0)
+    {
+        printf("mounting encrypted disk failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "mounting encrypted root disk failed");
+    }
+
+    // Create some directories in the small partition.
+    printf("creating directories in small partition\n");
+    command = NULL;
+    asprintf(&command, "mkdir -p %s%s %s%s", SMALL_MOUNTPOINT,
+        AUTHORIZED_KEYS_DIR, SMALL_MOUNTPOINT, SSH_HOST_KEY_DIR);
+    r = system(command);
+    if (r != 0)
+    {
+        printf("creating directories failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "creating directories in small partition failed");
+    }
+
+    // Copy authorized_keys file to the small partition.
+    printf("copying authorized_keys to small partition\n");
+    command = NULL;
+    asprintf(&command, "cp %s%s %s%s", TMP_LOCATION,
+        AUTHORIZED_KEYS_PATH, SMALL_MOUNTPOINT, AUTHORIZED_KEYS_PATH);
+    r = system(command);
+    if (r != 0)
+    {
+        printf("copying authorized_keys failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "creating filesystem inside encrypted container failed");
+    }
+
+    // Generate ssh host key and put it in the small partition.
+    printf("generating ssh host key\n");
+    command = NULL;
+    asprintf(&command, "dropbearkey -t rsa -f %s%s", SMALL_MOUNTPOINT,
+        SSH_HOST_KEY_PATH);
+    r = system(command);
+    if (r != 0)
+    {
+        printf("generating ssh host key failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "generating ssh host key failed");
+    }
+
+    // Unmount small partition device.
+    printf("unmounting small partition at %s\n", SMALL_MOUNTPOINT);
+    r = umount(SMALL_MOUNTPOINT);
+    if (r != 0)
+    {
+        printf("unmounting failed: return code %d\n", r);
+        return send_simple_response(response, 500, "error",
+           "unmounting configuration partition failed");
+    }
+
     // Initialise encrypted container, overwriting existing device.
-    printf("creating encrypted container at %s\n", CONTAINER_DEVICE);
-    r = create_encrypted_device(CONTAINER_DEVICE, password);
-    if(r != 0)
+    printf("creating encrypted container at %s\n", ROOT_BIG_PARTITION_DEVICE);
+    r = create_encrypted_device(ROOT_BIG_PARTITION_DEVICE, password);
+    if (r != 0)
     {
-        printf("creating encrypted container failed: return code %d", r);
+        printf("creating encrypted container failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "creating encryption container failed");
     }
 
     // Unlock the new container.
     printf("unlocking encrypted device\n");
-    r = encryption_unlock(CONTAINER_DEVICE, MAPPED_DEVICE_NAME, password);
-    if(r != 0)
+    r = encryption_unlock(ROOT_BIG_PARTITION_DEVICE, MAPPED_DEVICE_NAME,
+        password);
+    if (r != 0)
     {
-        printf("unlocking encrypted container failed: return code %d", r);
+        printf("unlocking encrypted container failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "unlocking new encryption container failed");
     }
@@ -120,20 +250,20 @@ int callback_encryption_add(const struct _u_request * request,
     command = NULL;
     asprintf(&command, "mkfs -t %s %s", FILESYSTEM_TYPE, MAPPED_DEVICE_PATH);
     r = system(command);
-    if(r != 0)
+    if (r != 0)
     {
-        printf("creating filesystem failed: return code %d", r);
+        printf("creating filesystem failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "creating filesystem inside encrypted container failed");
     }
 
     // Mount the unlocked container.
     printf("mounting new filesystem\n");
-    r = temporary_mount(MAPPED_DEVICE_PATH, ENCRYPTED_MOUNTPOINT,
+    r = temporary_mount(MAPPED_DEVICE_PATH, BIG_MOUNTPOINT,
         FILESYSTEM_TYPE);
     if (r != 0)
     {
-        printf("mounting encrypted disk failed: return code %d", r);
+        printf("mounting encrypted disk failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "mounting encrypted root disk failed");
     }
@@ -141,22 +271,22 @@ int callback_encryption_add(const struct _u_request * request,
     // Copy device contents from temporary filesystem to encrypted container.
     printf("copying root disk contents from memory\n");
     command = NULL;
-    asprintf(&command, "rsync -a %s/ %s", TMP_LOCATION, ENCRYPTED_MOUNTPOINT);
+    asprintf(&command, "rsync -a %s/ %s", TMP_LOCATION, BIG_MOUNTPOINT);
     r = system(command);
-    if(r != 0)
+    if (r != 0)
     {
-        printf("copying from memory to encrypted disk failed: return code %d",
+        printf("copying from memory to encrypted disk failed: return code %d\n",
             r);
         return send_simple_response(response, 500, "error",
            "copying rootdisk contents from memory failed");
     }
 
     // Unmount encrypted device.
-    printf("unmounting encrypted device at %s\n", ENCRYPTED_MOUNTPOINT);
-    r = umount(ENCRYPTED_MOUNTPOINT);
+    printf("unmounting encrypted device at %s\n", BIG_MOUNTPOINT);
+    r = umount(BIG_MOUNTPOINT);
     if (r != 0)
     {
-        printf("unmounting encrypted disk failed: return code %d", r);
+        printf("unmounting encrypted disk failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "unmounting encrypted disk failed");
     }
@@ -164,12 +294,17 @@ int callback_encryption_add(const struct _u_request * request,
     // Lock the container.
     printf("locking encrypted device\n");
     r = encryption_lock(MAPPED_DEVICE_NAME);
-    if(r != 0)
+    if (r != 0)
     {
-        printf("locking encrypted container failed: return code %d", r);
+        printf("locking encrypted container failed: return code %d\n", r);
         return send_simple_response(response, 500, "error",
            "locking container failed");
     }
 
-    return send_simple_response(response, 200, "status", "ok");
+    // Record that we want to reboot the machine.
+    *reboot = true;
+
+    r = send_simple_response(response, 200, "status", "ok");
+    stop_server();
+    return r;
 }
diff --git a/src/api/encryption_unlock.c b/src/api/encryption_unlock.c
index fbc7f79..86caee5 100644
--- a/src/api/encryption_unlock.c
+++ b/src/api/encryption_unlock.c
@@ -18,8 +18,8 @@ int callback_encryption_unlock(const struct _u_request * request,
         return send_simple_response(response, 400, "error", "missing password");
     }
   
-    int unlock_status = encryption_unlock(CONTAINER_DEVICE, MAPPED_DEVICE_NAME,
-        password);
+    int unlock_status = encryption_unlock(ROOT_BIG_PARTITION_DEVICE,
+        MAPPED_DEVICE_NAME, password);
   
     if (unlock_status == -1)
     {
diff --git a/src/auxiliary.c b/src/auxiliary.c
index fcbcde6..62ec6ac 100644
--- a/src/auxiliary.c
+++ b/src/auxiliary.c
@@ -131,3 +131,17 @@ int temporary_mount(char * device_path, char * mount_path,
         mount_flags, "");
     return r;
 }
+
+void reboot_initrd()
+{
+    pid_t pid;
+    pid = vfork();
+    if (pid == 0)
+    {
+        // Child.
+        reboot(0x1234567);
+        _exit(EXIT_SUCCESS);
+    }
+    // Parent (init) waits.
+    while (1);
+}
diff --git a/src/cryptops-api.c b/src/cryptops-api.c
index e9c560f..4676261 100644
--- a/src/cryptops-api.c
+++ b/src/cryptops-api.c
@@ -27,8 +27,9 @@ int main(int argc, char ** argv)
     instance.max_post_body_size = 1024;
 
     // Add api endpoints.
+    bool reboot = false;
     ulfius_add_endpoint_by_val(&instance, "POST", PREFIX, "/encryption/add",
-        0, &callback_encryption_add, NULL);
+        0, &callback_encryption_add, &reboot);
     ulfius_add_endpoint_by_val(&instance, "POST", PREFIX, "/encryption/unlock",
         0, &callback_encryption_unlock, NULL);
 
@@ -80,6 +81,13 @@ int main(int argc, char ** argv)
     
     ulfius_stop_framework(&instance);
     ulfius_clean_instance(&instance);
-    
+
+    // Check if the encryption/add said that we should reboot.
+    if (reboot)
+    {
+        printf("rebooting...");
+        reboot_initrd();
+    }
+
     return 0;
 }
diff --git a/src/encryption_functions.c b/src/encryption_functions.c
index 7f1f842..2a47b40 100644
--- a/src/encryption_functions.c
+++ b/src/encryption_functions.c
@@ -10,6 +10,14 @@
 static int container_initialise(struct crypt_device ** cd, const char * path,
      const bool debug)
 {
+    // Check if the device exists.
+    struct stat st = {0};
+    if (stat(path, &st) == -1)
+    {
+        printf("device does not exist: %s.\n", path);
+        return 1;
+    }
+
     // Let LUKS initialise the encrypted device.
     int r = crypt_init(cd, path);
     if (r < 0)
@@ -65,9 +73,10 @@ static int encryption_unlock(const char * path, const char * device_name,
     int r = container_initialise(&cd, path, true);
     if (r < 0)
     {
-        printf("crypt_load() failed on device %s.\n",
-            crypt_get_device_name(cd));
         crypt_free(cd);
+    }
+    if (r != 0)
+    {
         return r;
     }
 
diff --git a/src/includes/common-includes.h b/src/includes/common-includes.h
index b54967d..2626454 100644
--- a/src/includes/common-includes.h
+++ b/src/includes/common-includes.h
@@ -7,6 +7,8 @@
 #include <sys/statvfs.h>
 #include <linux/fs.h>
 #include <fcntl.h>
+#include <unistd.h>
+#include <sys/reboot.h>
 
 #define U_DISABLE_CURL
 #define U_DISABLE_WEBSOCKET
diff --git a/src/includes/settings.h b/src/includes/settings.h
index 33fdc3c..7eb5163 100644
--- a/src/includes/settings.h
+++ b/src/includes/settings.h
@@ -1,10 +1,17 @@
 #define PREFIX "/cryptops/v0"
 #define PORT 8000
-#define CONTAINER_DEVICE "/dev/xvda1"
+#define ROOT_DEVICE "/dev/xvda"
+#define ROOT_SMALL_PARTITION_DEVICE ROOT_DEVICE "1"
+#define ROOT_BIG_PARTITION_DEVICE ROOT_DEVICE "2"
 #define MAPPED_DEVICE_NAME "xvda1_crypt"
 #define MAPPED_DEVICE_PATH "/dev/mapper/" MAPPED_DEVICE_NAME
 #define FILESYSTEM_TYPE "xfs"
-#define MEMORY_USAGE 0.8
+#define MEMORY_USAGE 0.9
 #define UNENCRYPTED_MOUNTPOINT "/tmp/mnt-plain"
-#define ENCRYPTED_MOUNTPOINT "/tmp/mnt-encrypted"
+#define SMALL_MOUNTPOINT "/tmp/mnt-small"
+#define BIG_MOUNTPOINT "/tmp/mnt-big"
 #define TMP_LOCATION "/tmp/" MAPPED_DEVICE_NAME
+#define AUTHORIZED_KEYS_DIR "/root/.ssh"
+#define AUTHORIZED_KEYS_PATH AUTHORIZED_KEYS_DIR "/authorized_keys"
+#define SSH_HOST_KEY_DIR "/dropbear"
+#define SSH_HOST_KEY_PATH SSH_HOST_KEY_DIR "/dropbear_rsa_host_key"
-- 
GitLab