From c39181437b10fb49cd236f625c599c01af41f1b2 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 16 Aug 2011 22:45:42 +0200 Subject: [PATCH] pki: Add ssh_pki_export_publickey_file(). --- include/libssh/libssh.h | 2 ++ src/pki.c | 61 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/include/libssh/libssh.h b/include/libssh/libssh.h index 12c52cb1..630938b2 100644 --- a/include/libssh/libssh.h +++ b/include/libssh/libssh.h @@ -459,6 +459,8 @@ LIBSSH_API int ssh_pki_import_pubkey_file(const char *filename, ssh_key *pkey); LIBSSH_API int ssh_pki_export_publickey_base64(const ssh_key key, char **b64_key); +LIBSSH_API int ssh_pki_export_publickey_file(const ssh_key key, + const char *filename); LIBSSH_API int ssh_userauth_pki_pubkey(ssh_session session, const char *username, ssh_string publickey, ssh_key privatekey); diff --git a/src/pki.c b/src/pki.c index 867d1243..2fe1528d 100644 --- a/src/pki.c +++ b/src/pki.c @@ -3,6 +3,7 @@ * This file is part of the SSH Library * * Copyright (c) 2010 by Aris Adamantiadis + * Copyright (c) 2011-2011 Andreas Schneider * * The SSH Library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by @@ -40,12 +41,12 @@ #include #include "libssh/libssh.h" -#include "libssh/callbacks.h" #include "libssh/session.h" #include "libssh/priv.h" #include "libssh/pki.h" #include "libssh/keys.h" #include "libssh/buffer.h" +#include "libssh/misc.h" void ssh_pki_log(const char *format, ...) { @@ -755,6 +756,64 @@ int ssh_pki_export_publickey_base64(const ssh_key key, return SSH_OK; } +int ssh_pki_export_publickey_file(const ssh_key key, + const char *filename) +{ + char key_buf[4096]; + char host[256]; + char *b64_key; + char *user; + FILE *fp; + int rc; + + if (key == NULL || filename == NULL || *filename == '\0') { + return SSH_ERROR; + } + + user = ssh_get_local_username(); + if (user == NULL) { + return SSH_ERROR; + } + + rc = gethostname(host, sizeof(host)); + if (rc < 0) { + free(user); + return SSH_ERROR; + } + + rc = ssh_pki_export_publickey_base64(key, &b64_key); + if (rc < 0) { + free(user); + return SSH_ERROR; + } + + rc = snprintf(key_buf, sizeof(key_buf), + "%s %s %s@%s\n", + key->type_c, + b64_key, + user, + host); + free(user); + free(b64_key); + if (rc < 0) { + return SSH_ERROR; + } + + fp = fopen(filename, "w+"); + if (fp == NULL) { + return SSH_ERROR; + } + rc = fwrite(key_buf, strlen(key_buf), 1, fp); + if (rc != 1 || ferror(fp)) { + fclose(fp); + unlink(filename); + return SSH_ERROR; + } + fclose(fp); + + return SSH_OK; +} + /* * This function signs the session id (known as H) as a string then * the content of sigbuf */