Skip to content
Snippets Groups Projects
encryption_functions.c 2.39 KiB
Newer Older
/**
 * Use cryptsetup to initialise the luks container.
 * It will not be opened (decrypted) yet, but it does check if the container
 * seems usable.
 */
static int container_initialise
(
    struct crypt_device **cd, /* struct to store crypt device context */
    const char *path          /* path to the encrypted container */
)
{
    // Let LUKS initialise the encrypted device.
    int r = crypt_init(cd, path);
    if (r < 0)
    {
        printf("crypt_init() failed for %s.\n", path);
        printf("status: %d.\n", r);
        return r;
    }

    // Load the LUKS header from the block device into the crypt device context.
    r = crypt_load
    (
        *cd,         /* crypt device context */
        CRYPT_LUKS1, /* requested encryption type */
        NULL         /* additional parameters (not used) */
    );
    if (r < 0)
    {
        printf("crypt_load() failed on device %s.\n",
            crypt_get_device_name(*cd));
    }

    return r;
}

/**
 * Use cryptsetup to unlock the luks container.
 * This will create `/dev/mapper/$device_name`.
 */
static int encryption_unlock
(
    const char *path,        /* path to the encrypted container */
    const char *device_name, /* name of the mapping */
    const char *password     /* encryption password of the container */
)
{
    // Let LUKS initialise the encrypted device.
    struct crypt_device *cd;
    int r = container_initialise(&cd, path);
    if (r < 0)
    {
        printf("crypt_load() failed on device %s.\n",
            crypt_get_device_name(cd));
        crypt_free(cd);
        return r;
    }

    // Device activation creates device-mapper devie mapping with namei
    // device_name.
    r = crypt_activate_by_passphrase
    (
        cd,                          /* crypt context */
        device_name,                 /* device name to activate */
        CRYPT_ANY_SLOT,              /* which slot use (ANY - try all) */
        password, strlen(password),  /* passphrase */
        CRYPT_ACTIVATE_READONLY      /* flags */
    );
    if (r < 0)
    {
        printf("Device %s activation failed.\n", device_name);
        crypt_free(cd);
        return r;
    }

    printf("LUKS device %s/%s is active.\n", crypt_get_dir(), device_name);
    printf("\tcipher used: %s\n", crypt_get_cipher(cd));
    printf("\tcipher mode: %s\n", crypt_get_cipher_mode(cd));
    printf("\tdevice UUID: %s\n", crypt_get_uuid(cd));

    crypt_free(cd);
    return 0;
}