From 7542396ef1bcb05749e0f00a68013e663335ac27 Mon Sep 17 00:00:00 2001 From: Julio Montes Date: Thu, 5 Nov 2015 16:28:25 -0600 Subject: [PATCH] add util functions to manipulate files and directories write_sudo_string: add rules to /etc/sudoers.d/ write_ssh_key: add pub keys to ~/.ssh/autorized_keys Signed-off-by: Julio Montes --- src/lib.c | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.h | 2 ++ 2 files changed, 68 insertions(+) diff --git a/src/lib.c b/src/lib.c index 518f67f..6aea351 100644 --- a/src/lib.c +++ b/src/lib.c @@ -44,6 +44,8 @@ #include #include #include +#include +#include #include @@ -96,3 +98,67 @@ int chown_path(const char* pathname, const char* ownername, const char* groupnam return chown(pathname, owner_id, group_id); } + +int write_sudo_string(const gchar* filename, const gchar* data) { + int fd; + gchar sudoers_file[PATH_MAX]; + g_snprintf(sudoers_file, PATH_MAX, "/etc/sudoers.d/"); + if (make_dir(sudoers_file, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) != 0) { + return 1; + } + + g_strlcat(sudoers_file, filename, PATH_MAX); + fd = open(sudoers_file, O_CREAT|O_APPEND|O_WRONLY, S_IRUSR|S_IRGRP); + if (-1 == fd) { + LOG(MOD "Cannot open %s\n", sudoers_file); + return 1; + } + + write(fd, data, strlen(data)); + write(fd, "\n", 1); + + close(fd); + + return 0; +} + +int write_ssh_key(const gchar* ssh_key, const gchar* username) { + int fd; + gchar auth_keys_path[PATH_MAX]; + struct passwd *pw; + + pw = getpwnam(username); + + if (pw && pw->pw_dir) { + g_snprintf(auth_keys_path, PATH_MAX, "%s/.ssh", pw->pw_dir); + + if (make_dir(auth_keys_path, S_IRWXU) != 0) { + LOG(MOD "Cannot create %s.\n", auth_keys_path); + return 1; + } + + if (chown_path(auth_keys_path, username, username) != 0) { + LOG(MOD "Cannot change the owner and group of %s.\n", auth_keys_path); + return 1; + } + + g_strlcat(auth_keys_path, "/authorized_keys", PATH_MAX); + fd = open(auth_keys_path, O_CREAT|O_APPEND|O_WRONLY, S_IRUSR|S_IWUSR); + if (-1 == fd) { + LOG(MOD "Cannot open %s.\n", auth_keys_path); + return 1; + } + + LOG(MOD "Using %s\n", auth_keys_path); + LOG(MOD "Writing %s\n", ssh_key); + write(fd, ssh_key, strlen(ssh_key)); + write(fd, "\n", 1); + close(fd); + + if (chown_path(auth_keys_path, username, username) != 0) { + LOG(MOD "Cannot change the owner and group of %s.\n", auth_keys_path); + return 1; + } + } + return 0; +} diff --git a/src/lib.h b/src/lib.h index c8a0222..7100498 100644 --- a/src/lib.h +++ b/src/lib.h @@ -52,3 +52,5 @@ void exec_task(const gchar* task); void LOG(const char *fmt, ...) __attribute__((format(printf, 1, 2))); int make_dir(const char* pathname, mode_t mode); int chown_path(const char* pathname, const char* ownername, const char* groupname); +int write_sudo_string(const gchar* filename, const gchar* data); +int write_ssh_key(const gchar* ssh_key, const gchar* username);