1072c8
From 4be6cb23235b29d6ce450c2dacaef09c52d1aeea Mon Sep 17 00:00:00 2001
1072c8
From: =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= <marcandre.lureau@redhat.com>
1072c8
Date: Thu, 29 Jul 2021 04:55:52 -0400
1072c8
Subject: [PATCH 02/14] qga: add ssh-{add, remove}-authorized-keys
1072c8
MIME-Version: 1.0
1072c8
Content-Type: text/plain; charset=UTF-8
1072c8
Content-Transfer-Encoding: 8bit
1072c8
1072c8
RH-Author: Marc-André Lureau <marcandre.lureau@redhat.com>
1072c8
Message-id: <20210609100615.2501448-3-marcandre.lureau@redhat.com>
1072c8
Patchwork-id: 101688
1072c8
O-Subject: [RHEL-8.5.0 qemu-kvm PATCH 2/4] qga: add ssh-{add, remove}-authorized-keys
1072c8
Bugzilla: 1967716
1072c8
RH-Acked-by: Miroslav Rezanina <mrezanin@redhat.com>
1072c8
RH-Acked-by: Philippe Mathieu-Daudé <philmd@redhat.com>
1072c8
RH-Acked-by: Michal Privoznik <mprivozn@redhat.com>
1072c8
1072c8
From: Marc-André Lureau <marcandre.lureau@redhat.com>
1072c8
1072c8
Add new commands to add and remove SSH public keys from
1072c8
~/.ssh/authorized_keys.
1072c8
1072c8
I took a different approach for testing, including the unit tests right
1072c8
with the code. I wanted to overwrite the function to get the user
1072c8
details, I couldn't easily do that over QMP. Furthermore, I prefer
1072c8
having unit tests very close to the code, and unit files that are domain
1072c8
specific (commands-posix is too crowded already). FWIW, that
1072c8
coding/testing style is Rust-style (where tests can or should even be
1072c8
part of the documentation!).
1072c8
1072c8
Fixes:
1072c8
https://bugzilla.redhat.com/show_bug.cgi?id=1885332
1072c8
1072c8
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
1072c8
Reviewed-by: Michal Privoznik <mprivozn@redhat.com>
1072c8
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
1072c8
*squashed in fix-ups for setting file ownership and use of QAPI
1072c8
 conditionals for CONFIG_POSIX instead of stub definitions
1072c8
*disable qga-ssh-test for now due to G_TEST_OPTION_ISOLATE_DIRS
1072c8
 triggering leak detector in build-oss-fuzz
1072c8
*fix disallowed g_assert* usage reported by checkpatch
1072c8
Signed-off-by: Michael Roth <michael.roth@amd.com>
1072c8
1072c8
(cherry picked from commit 8d769ec777dccbff199711aba43aa6297fe4a0e0)
1072c8
[ Fixes trivial backport conflicts and use Makefile.objs build-sys ]
1072c8
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
1072c8
Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
1072c8
---
1072c8
 qga/Makefile.objs        |   2 +-
1072c8
 qga/commands-posix-ssh.c | 407 +++++++++++++++++++++++++++++++++++++++
1072c8
 qga/qapi-schema.json     |  35 ++++
1072c8
 3 files changed, 443 insertions(+), 1 deletion(-)
1072c8
 create mode 100644 qga/commands-posix-ssh.c
1072c8
1072c8
diff --git a/qga/Makefile.objs b/qga/Makefile.objs
1072c8
index 80e6bb3c2e..c8da634db0 100644
1072c8
--- a/qga/Makefile.objs
1072c8
+++ b/qga/Makefile.objs
1072c8
@@ -1,6 +1,6 @@
1072c8
 commands-posix.o-libs := $(LIBUDEV_LIBS)
1072c8
 qga-obj-y = commands.o guest-agent-command-state.o main.o
1072c8
-qga-obj-$(CONFIG_POSIX) += commands-posix.o channel-posix.o
1072c8
+qga-obj-$(CONFIG_POSIX) += commands-posix.o channel-posix.o commands-posix-ssh.o
1072c8
 qga-obj-$(CONFIG_WIN32) += commands-win32.o channel-win32.o service-win32.o
1072c8
 qga-obj-$(CONFIG_WIN32) += vss-win32.o
1072c8
 qga-obj-y += qapi-generated/qga-qapi-types.o qapi-generated/qga-qapi-visit.o
1072c8
diff --git a/qga/commands-posix-ssh.c b/qga/commands-posix-ssh.c
1072c8
new file mode 100644
1072c8
index 0000000000..f74d89679c
1072c8
--- /dev/null
1072c8
+++ b/qga/commands-posix-ssh.c
1072c8
@@ -0,0 +1,407 @@
1072c8
+ /*
1072c8
+  * This work is licensed under the terms of the GNU GPL, version 2 or later.
1072c8
+  * See the COPYING file in the top-level directory.
1072c8
+  */
1072c8
+#include "qemu/osdep.h"
1072c8
+
1072c8
+#include <glib-unix.h>
1072c8
+#include <glib/gstdio.h>
1072c8
+#include <locale.h>
1072c8
+#include <pwd.h>
1072c8
+
1072c8
+#include "qapi/error.h"
1072c8
+#include "qga-qapi-commands.h"
1072c8
+
1072c8
+#ifdef QGA_BUILD_UNIT_TEST
1072c8
+static struct passwd *
1072c8
+test_get_passwd_entry(const gchar *user_name, GError **error)
1072c8
+{
1072c8
+    struct passwd *p;
1072c8
+    int ret;
1072c8
+
1072c8
+    if (!user_name || g_strcmp0(user_name, g_get_user_name())) {
1072c8
+        g_set_error(error, G_UNIX_ERROR, 0, "Invalid user name");
1072c8
+        return NULL;
1072c8
+    }
1072c8
+
1072c8
+    p = g_new0(struct passwd, 1);
1072c8
+    p->pw_dir = (char *)g_get_home_dir();
1072c8
+    p->pw_uid = geteuid();
1072c8
+    p->pw_gid = getegid();
1072c8
+
1072c8
+    ret = g_mkdir_with_parents(p->pw_dir, 0700);
1072c8
+    g_assert(ret == 0);
1072c8
+
1072c8
+    return p;
1072c8
+}
1072c8
+
1072c8
+#define g_unix_get_passwd_entry_qemu(username, err) \
1072c8
+   test_get_passwd_entry(username, err)
1072c8
+#endif
1072c8
+
1072c8
+static struct passwd *
1072c8
+get_passwd_entry(const char *username, Error **errp)
1072c8
+{
1072c8
+    g_autoptr(GError) err = NULL;
1072c8
+    struct passwd *p;
1072c8
+
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    p = g_unix_get_passwd_entry_qemu(username, &err;;
1072c8
+    if (p == NULL) {
1072c8
+        error_setg(errp, "failed to lookup user '%s': %s",
1072c8
+                   username, err->message);
1072c8
+        return NULL;
1072c8
+    }
1072c8
+
1072c8
+    return p;
1072c8
+}
1072c8
+
1072c8
+static bool
1072c8
+mkdir_for_user(const char *path, const struct passwd *p,
1072c8
+               mode_t mode, Error **errp)
1072c8
+{
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    if (g_mkdir(path, mode) == -1) {
1072c8
+        error_setg(errp, "failed to create directory '%s': %s",
1072c8
+                   path, g_strerror(errno));
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    if (chown(path, p->pw_uid, p->pw_gid) == -1) {
1072c8
+        error_setg(errp, "failed to set ownership of directory '%s': %s",
1072c8
+                   path, g_strerror(errno));
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    if (chmod(path, mode) == -1) {
1072c8
+        error_setg(errp, "failed to set permissions of directory '%s': %s",
1072c8
+                   path, g_strerror(errno));
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    return true;
1072c8
+}
1072c8
+
1072c8
+static bool
1072c8
+check_openssh_pub_key(const char *key, Error **errp)
1072c8
+{
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    /* simple sanity-check, we may want more? */
1072c8
+    if (!key || key[0] == '#' || strchr(key, '\n')) {
1072c8
+        error_setg(errp, "invalid OpenSSH public key: '%s'", key);
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    return true;
1072c8
+}
1072c8
+
1072c8
+static bool
1072c8
+check_openssh_pub_keys(strList *keys, size_t *nkeys, Error **errp)
1072c8
+{
1072c8
+    size_t n = 0;
1072c8
+    strList *k;
1072c8
+
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    for (k = keys; k != NULL; k = k->next) {
1072c8
+        if (!check_openssh_pub_key(k->value, errp)) {
1072c8
+            return false;
1072c8
+        }
1072c8
+        n++;
1072c8
+    }
1072c8
+
1072c8
+    if (nkeys) {
1072c8
+        *nkeys = n;
1072c8
+    }
1072c8
+    return true;
1072c8
+}
1072c8
+
1072c8
+static bool
1072c8
+write_authkeys(const char *path, const GStrv keys,
1072c8
+               const struct passwd *p, Error **errp)
1072c8
+{
1072c8
+    g_autofree char *contents = NULL;
1072c8
+    g_autoptr(GError) err = NULL;
1072c8
+
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    contents = g_strjoinv("\n", keys);
1072c8
+    if (!g_file_set_contents(path, contents, -1, &err)) {
1072c8
+        error_setg(errp, "failed to write to '%s': %s", path, err->message);
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    if (chown(path, p->pw_uid, p->pw_gid) == -1) {
1072c8
+        error_setg(errp, "failed to set ownership of directory '%s': %s",
1072c8
+                   path, g_strerror(errno));
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    if (chmod(path, 0600) == -1) {
1072c8
+        error_setg(errp, "failed to set permissions of '%s': %s",
1072c8
+                   path, g_strerror(errno));
1072c8
+        return false;
1072c8
+    }
1072c8
+
1072c8
+    return true;
1072c8
+}
1072c8
+
1072c8
+static GStrv
1072c8
+read_authkeys(const char *path, Error **errp)
1072c8
+{
1072c8
+    g_autoptr(GError) err = NULL;
1072c8
+    g_autofree char *contents = NULL;
1072c8
+
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    if (!g_file_get_contents(path, &contents, NULL, &err)) {
1072c8
+        error_setg(errp, "failed to read '%s': %s", path, err->message);
1072c8
+        return NULL;
1072c8
+    }
1072c8
+
1072c8
+    return g_strsplit(contents, "\n", -1);
1072c8
+
1072c8
+}
1072c8
+
1072c8
+void
1072c8
+qmp_guest_ssh_add_authorized_keys(const char *username, strList *keys,
1072c8
+                                  Error **errp)
1072c8
+{
1072c8
+    g_autofree struct passwd *p = NULL;
1072c8
+    g_autofree char *ssh_path = NULL;
1072c8
+    g_autofree char *authkeys_path = NULL;
1072c8
+    g_auto(GStrv) authkeys = NULL;
1072c8
+    strList *k;
1072c8
+    size_t nkeys, nauthkeys;
1072c8
+
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    if (!check_openssh_pub_keys(keys, &nkeys, errp)) {
1072c8
+        return;
1072c8
+    }
1072c8
+
1072c8
+    p = get_passwd_entry(username, errp);
1072c8
+    if (p == NULL) {
1072c8
+        return;
1072c8
+    }
1072c8
+
1072c8
+    ssh_path = g_build_filename(p->pw_dir, ".ssh", NULL);
1072c8
+    authkeys_path = g_build_filename(ssh_path, "authorized_keys", NULL);
1072c8
+
1072c8
+    authkeys = read_authkeys(authkeys_path, NULL);
1072c8
+    if (authkeys == NULL) {
1072c8
+        if (!g_file_test(ssh_path, G_FILE_TEST_IS_DIR) &&
1072c8
+            !mkdir_for_user(ssh_path, p, 0700, errp)) {
1072c8
+            return;
1072c8
+        }
1072c8
+    }
1072c8
+
1072c8
+    nauthkeys = authkeys ? g_strv_length(authkeys) : 0;
1072c8
+    authkeys = g_realloc_n(authkeys, nauthkeys + nkeys + 1, sizeof(char *));
1072c8
+    memset(authkeys + nauthkeys, 0, (nkeys + 1) * sizeof(char *));
1072c8
+
1072c8
+    for (k = keys; k != NULL; k = k->next) {
1072c8
+        if (g_strv_contains((const gchar * const *)authkeys, k->value)) {
1072c8
+            continue;
1072c8
+        }
1072c8
+        authkeys[nauthkeys++] = g_strdup(k->value);
1072c8
+    }
1072c8
+
1072c8
+    write_authkeys(authkeys_path, authkeys, p, errp);
1072c8
+}
1072c8
+
1072c8
+void
1072c8
+qmp_guest_ssh_remove_authorized_keys(const char *username, strList *keys,
1072c8
+                                     Error **errp)
1072c8
+{
1072c8
+    g_autofree struct passwd *p = NULL;
1072c8
+    g_autofree char *authkeys_path = NULL;
1072c8
+    g_autofree GStrv new_keys = NULL; /* do not own the strings */
1072c8
+    g_auto(GStrv) authkeys = NULL;
1072c8
+    GStrv a;
1072c8
+    size_t nkeys = 0;
1072c8
+
1072c8
+    ERRP_GUARD();
1072c8
+
1072c8
+    if (!check_openssh_pub_keys(keys, NULL, errp)) {
1072c8
+        return;
1072c8
+    }
1072c8
+
1072c8
+    p = get_passwd_entry(username, errp);
1072c8
+    if (p == NULL) {
1072c8
+        return;
1072c8
+    }
1072c8
+
1072c8
+    authkeys_path = g_build_filename(p->pw_dir, ".ssh",
1072c8
+                                     "authorized_keys", NULL);
1072c8
+    if (!g_file_test(authkeys_path, G_FILE_TEST_EXISTS)) {
1072c8
+        return;
1072c8
+    }
1072c8
+    authkeys = read_authkeys(authkeys_path, errp);
1072c8
+    if (authkeys == NULL) {
1072c8
+        return;
1072c8
+    }
1072c8
+
1072c8
+    new_keys = g_new0(char *, g_strv_length(authkeys) + 1);
1072c8
+    for (a = authkeys; *a != NULL; a++) {
1072c8
+        strList *k;
1072c8
+
1072c8
+        for (k = keys; k != NULL; k = k->next) {
1072c8
+            if (g_str_equal(k->value, *a)) {
1072c8
+                break;
1072c8
+            }
1072c8
+        }
1072c8
+        if (k != NULL) {
1072c8
+            continue;
1072c8
+        }
1072c8
+
1072c8
+        new_keys[nkeys++] = *a;
1072c8
+    }
1072c8
+
1072c8
+    write_authkeys(authkeys_path, new_keys, p, errp);
1072c8
+}
1072c8
+
1072c8
+
1072c8
+#ifdef QGA_BUILD_UNIT_TEST
1072c8
+#if GLIB_CHECK_VERSION(2, 60, 0)
1072c8
+static const strList test_key2 = {
1072c8
+    .value = (char *)"algo key2 comments"
1072c8
+};
1072c8
+
1072c8
+static const strList test_key1_2 = {
1072c8
+    .value = (char *)"algo key1 comments",
1072c8
+    .next = (strList *)&test_key2,
1072c8
+};
1072c8
+
1072c8
+static char *
1072c8
+test_get_authorized_keys_path(void)
1072c8
+{
1072c8
+    return g_build_filename(g_get_home_dir(), ".ssh", "authorized_keys", NULL);
1072c8
+}
1072c8
+
1072c8
+static void
1072c8
+test_authorized_keys_set(const char *contents)
1072c8
+{
1072c8
+    g_autoptr(GError) err = NULL;
1072c8
+    g_autofree char *path = NULL;
1072c8
+    int ret;
1072c8
+
1072c8
+    path = g_build_filename(g_get_home_dir(), ".ssh", NULL);
1072c8
+    ret = g_mkdir_with_parents(path, 0700);
1072c8
+    g_assert(ret == 0);
1072c8
+    g_free(path);
1072c8
+
1072c8
+    path = test_get_authorized_keys_path();
1072c8
+    g_file_set_contents(path, contents, -1, &err;;
1072c8
+    g_assert(err == NULL);
1072c8
+}
1072c8
+
1072c8
+static void
1072c8
+test_authorized_keys_equal(const char *expected)
1072c8
+{
1072c8
+    g_autoptr(GError) err = NULL;
1072c8
+    g_autofree char *path = NULL;
1072c8
+    g_autofree char *contents = NULL;
1072c8
+
1072c8
+    path = test_get_authorized_keys_path();
1072c8
+    g_file_get_contents(path, &contents, NULL, &err;;
1072c8
+    g_assert(err == NULL);
1072c8
+
1072c8
+    g_assert(g_strcmp0(contents, expected) == 0);
1072c8
+}
1072c8
+
1072c8
+static void
1072c8
+test_invalid_user(void)
1072c8
+{
1072c8
+    Error *err = NULL;
1072c8
+
1072c8
+    qmp_guest_ssh_add_authorized_keys("", NULL, &err;;
1072c8
+    error_free_or_abort(&err;;
1072c8
+
1072c8
+    qmp_guest_ssh_remove_authorized_keys("", NULL, &err;;
1072c8
+    error_free_or_abort(&err;;
1072c8
+}
1072c8
+
1072c8
+static void
1072c8
+test_invalid_key(void)
1072c8
+{
1072c8
+    strList key = {
1072c8
+        .value = (char *)"not a valid\nkey"
1072c8
+    };
1072c8
+    Error *err = NULL;
1072c8
+
1072c8
+    qmp_guest_ssh_add_authorized_keys(g_get_user_name(), &key, &err;;
1072c8
+    error_free_or_abort(&err;;
1072c8
+
1072c8
+    qmp_guest_ssh_remove_authorized_keys(g_get_user_name(), &key, &err;;
1072c8
+    error_free_or_abort(&err;;
1072c8
+}
1072c8
+
1072c8
+static void
1072c8
+test_add_keys(void)
1072c8
+{
1072c8
+    Error *err = NULL;
1072c8
+
1072c8
+    qmp_guest_ssh_add_authorized_keys(g_get_user_name(),
1072c8
+                                      (strList *)&test_key2, &err;;
1072c8
+    g_assert(err == NULL);
1072c8
+
1072c8
+    test_authorized_keys_equal("algo key2 comments");
1072c8
+
1072c8
+    qmp_guest_ssh_add_authorized_keys(g_get_user_name(),
1072c8
+                                      (strList *)&test_key1_2, &err;;
1072c8
+    g_assert(err == NULL);
1072c8
+
1072c8
+    /*  key2 came first, and should'nt be duplicated */
1072c8
+    test_authorized_keys_equal("algo key2 comments\n"
1072c8
+                               "algo key1 comments");
1072c8
+}
1072c8
+
1072c8
+static void
1072c8
+test_remove_keys(void)
1072c8
+{
1072c8
+    Error *err = NULL;
1072c8
+    static const char *authkeys =
1072c8
+        "algo key1 comments\n"
1072c8
+        /* originally duplicated */
1072c8
+        "algo key1 comments\n"
1072c8
+        "# a commented line\n"
1072c8
+        "algo some-key another\n";
1072c8
+
1072c8
+    test_authorized_keys_set(authkeys);
1072c8
+    qmp_guest_ssh_remove_authorized_keys(g_get_user_name(),
1072c8
+                                         (strList *)&test_key2, &err;;
1072c8
+    g_assert(err == NULL);
1072c8
+    test_authorized_keys_equal(authkeys);
1072c8
+
1072c8
+    qmp_guest_ssh_remove_authorized_keys(g_get_user_name(),
1072c8
+                                         (strList *)&test_key1_2, &err;;
1072c8
+    g_assert(err == NULL);
1072c8
+    test_authorized_keys_equal("# a commented line\n"
1072c8
+                               "algo some-key another\n");
1072c8
+}
1072c8
+
1072c8
+int main(int argc, char *argv[])
1072c8
+{
1072c8
+    setlocale(LC_ALL, "");
1072c8
+
1072c8
+    g_test_init(&argc, &argv, G_TEST_OPTION_ISOLATE_DIRS, NULL);
1072c8
+
1072c8
+    g_test_add_func("/qga/ssh/invalid_user", test_invalid_user);
1072c8
+    g_test_add_func("/qga/ssh/invalid_key", test_invalid_key);
1072c8
+    g_test_add_func("/qga/ssh/add_keys", test_add_keys);
1072c8
+    g_test_add_func("/qga/ssh/remove_keys", test_remove_keys);
1072c8
+
1072c8
+    return g_test_run();
1072c8
+}
1072c8
+#else
1072c8
+int main(int argc, char *argv[])
1072c8
+{
1072c8
+    g_test_message("test skipped, needs glib >= 2.60");
1072c8
+    return 0;
1072c8
+}
1072c8
+#endif /* GLIB_2_60 */
1072c8
+#endif /* BUILD_UNIT_TEST */
1072c8
diff --git a/qga/qapi-schema.json b/qga/qapi-schema.json
1072c8
index 4222cb92d3..3b85f5a03f 100644
1072c8
--- a/qga/qapi-schema.json
1072c8
+++ b/qga/qapi-schema.json
1072c8
@@ -1273,3 +1273,38 @@
1072c8
 ##
1072c8
 { 'command': 'guest-get-osinfo',
1072c8
   'returns': 'GuestOSInfo' }
1072c8
+
1072c8
+##
1072c8
+# @guest-ssh-add-authorized-keys:
1072c8
+#
1072c8
+# @username: the user account to add the authorized keys
1072c8
+# @keys: the public keys to add (in OpenSSH/sshd(8) authorized_keys format)
1072c8
+#
1072c8
+# Append public keys to user .ssh/authorized_keys on Unix systems (not
1072c8
+# implemented for other systems).
1072c8
+#
1072c8
+# Returns: Nothing on success.
1072c8
+#
1072c8
+# Since: 5.2
1072c8
+##
1072c8
+{ 'command': 'guest-ssh-add-authorized-keys',
1072c8
+  'data': { 'username': 'str', 'keys': ['str'] },
1072c8
+  'if': 'defined(CONFIG_POSIX)' }
1072c8
+
1072c8
+##
1072c8
+# @guest-ssh-remove-authorized-keys:
1072c8
+#
1072c8
+# @username: the user account to remove the authorized keys
1072c8
+# @keys: the public keys to remove (in OpenSSH/sshd(8) authorized_keys format)
1072c8
+#
1072c8
+# Remove public keys from the user .ssh/authorized_keys on Unix systems (not
1072c8
+# implemented for other systems). It's not an error if the key is already
1072c8
+# missing.
1072c8
+#
1072c8
+# Returns: Nothing on success.
1072c8
+#
1072c8
+# Since: 5.2
1072c8
+##
1072c8
+{ 'command': 'guest-ssh-remove-authorized-keys',
1072c8
+  'data': { 'username': 'str', 'keys': ['str'] },
1072c8
+  'if': 'defined(CONFIG_POSIX)' }
1072c8
-- 
1072c8
2.27.0
1072c8