Skip to content
Snippets Groups Projects
encryption_keys_get.c 2.75 KiB
Newer Older
/**
 * Callback function to view luks encryption slot usage.
 * @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
 * @return                internal status code
 */
int callback_encryption_keys_get(const struct _u_request * request,
    struct _u_response * response, void * user_data)
{
    int r;

    // Initialise encrypted container.
    struct crypt_device * cd = NULL;
    r = container_initialise(&cd, DATA_PARTITION_DEVICE, true);
Arie Peterson's avatar
Arie Peterson committed
    // A negative return code indicates that something went wrong with the
    // initialisation of the encrypted container, so we need to free it.
    // A positive return code means we couldn't even attempt the initialisation,
    // so there is nothing to clean up.
    if (r < 0)
    {
        crypt_free(cd);
    }
    if (r != 0)
    {
        printf("container_initialise failed with status %d\n", r);
        return send_simple_response(response, 500, "error",
            "initialising encrypted container failed");
    }

    json_t * keys = json_object();
    json_t * key;
    char * field;
    bool in_use;
    bool last_used;
    int keyslot = 0;
    int keyslot_max = crypt_keyslot_max(CRYPT_LUKS1);
    if (keyslot_max < 0)
    {
        return send_simple_response(response, 500, "error",
            "crypt_keyslot_max failed");
    }

    for (keyslot = 0; keyslot < keyslot_max; keyslot++)
    {
        // Create new json object containing info for this keyslot.
        key = json_object();

        // Get keyslot status.
        crypt_keyslot_info keyslot_status = crypt_keyslot_status(cd, keyslot);

        // Convert info to our format of two booleans.
        switch (keyslot_status)
        {
            case CRYPT_SLOT_ACTIVE:
                in_use = true;
                last_used = false;
                break;
            case CRYPT_SLOT_ACTIVE_LAST:
                in_use = true;
                last_used = true;
                break;
            default:
                in_use = false;
                last_used = false;
        }

        // Populate keyslot json object with info.
        json_object_set_new(key, "in-use",
            in_use ? json_true() : json_false());
        json_object_set_new(key, "last-used",
            last_used ? json_true() : json_false());

        // Add keyslot json object to json response.
        asprintf(&field, "%d", keyslot);
        json_object_set_new(keys, field, key);
    }

    // Create json response.
Arie Peterson's avatar
Arie Peterson committed
    json_t * json_body = json_object();
    json_object_set_new(json_body, "encryption-keys", keys);

    // Send response.
    ulfius_set_json_body_response(response, 200, json_body);
    json_decref(json_body);
    return U_CALLBACK_CONTINUE;
}