From 39e5cf07b1579be8e3615f5dc7cdaf8d1d1e0dfb Mon Sep 17 00:00:00 2001
From: Arie Peterson <arie@greenhost.nl>
Date: Wed, 21 Jun 2017 17:34:32 +0200
Subject: [PATCH] Add endpoint for listing ssh keys

---
 src/api/ssh_keys_get.c | 53 ++++++++++++++++++++++++++++++++++++++++++
 src/cryptops-api.c     |  3 +++
 2 files changed, 56 insertions(+)
 create mode 100644 src/api/ssh_keys_get.c

diff --git a/src/api/ssh_keys_get.c b/src/api/ssh_keys_get.c
new file mode 100644
index 0000000..04b1a08
--- /dev/null
+++ b/src/api/ssh_keys_get.c
@@ -0,0 +1,53 @@
+/**
+ * Callback function that lists the current ssh keys authorised for access
+ * to the initrd.
+ * @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_ssh_keys_get(const struct _u_request * request,
+    struct _u_response * response, void * user_data)
+{
+    FILE * authorized_keys;
+    char * line = NULL;
+    size_t line_length = 0;
+    ssize_t read;
+
+    json_t * keys = json_array();
+
+    // Open file.
+    authorized_keys = fopen("/root/.ssh/authorized_keys", "r");
+    // Check if that succeeded.
+    if (authorized_keys == NULL)
+    {
+        printf("Could not open authorized_keys file\n");
+        return send_simple_response(response, 500, "error",
+            "error reading authorized_keys");
+    }
+
+    // Read file line by line.
+    while ((read = getline(&line, &line_length, authorized_keys)) != -1)
+    {
+        // Remove trailing newline.
+        line[strcspn(line, "\n")] = 0;
+        json_array_append(keys, json_string(line));
+    }
+
+    // Close file and clean up.
+    fclose(authorized_keys);
+    if (line)
+    {
+        free(line);
+    }
+
+    // Create json response.
+    json_t * json_body = NULL;
+    json_body = json_object();
+    json_object_set_new(json_body, "ssh-keys", keys);
+
+    // Send response.
+    ulfius_set_json_body_response(response, 200, json_body);
+    json_decref(json_body);
+    return U_CALLBACK_CONTINUE;
+}
diff --git a/src/cryptops-api.c b/src/cryptops-api.c
index e9c560f..ba0711d 100644
--- a/src/cryptops-api.c
+++ b/src/cryptops-api.c
@@ -8,6 +8,7 @@
 #include <api/default.c>
 #include <api/encryption_add.c>
 #include <api/encryption_unlock.c>
+#include <api/ssh_keys_get.c>
 
 int main(int argc, char ** argv)
 {
@@ -31,6 +32,8 @@ int main(int argc, char ** argv)
         0, &callback_encryption_add, NULL);
     ulfius_add_endpoint_by_val(&instance, "POST", PREFIX, "/encryption/unlock",
         0, &callback_encryption_unlock, NULL);
+    ulfius_add_endpoint_by_val(&instance, "GET" , PREFIX, "/ssh/keys",
+        0, &callback_ssh_keys_get, NULL);
 
     // Add default endpoint.
     ulfius_set_default_endpoint(&instance, &callback_default, NULL);
-- 
GitLab