Greenbone Vulnerability Management Libraries 22.32.0
sshutils.c
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2015-2023 Greenbone AG
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later
4 */
5
10
11#include "sshutils.h"
12
13#include <glib.h> /* for g_free, g_strdup, g_strdup_printf */
14#include <gnutls/gnutls.h> /* for gnutls_datum_t */
15#include <gnutls/x509.h> /* for gnutls_x509_privkey_deinit, gnutls_x509_p... */
16#include <libssh/libssh.h> /* for ssh_key_free, ssh_key_type, ssh_key_type_... */
17#include <string.h> /* for strcmp, strlen */
18
19#undef G_LOG_DOMAIN
23#define G_LOG_DOMAIN "libgvm util"
24
33char *
34gvm_ssh_pkcs8_decrypt (const char *pkcs8_key, const char *passphrase)
35{
36 gnutls_datum_t data;
37 gnutls_x509_privkey_t key;
38 char buffer[16 * 2048];
39 int rc;
40 size_t size = sizeof (buffer);
41
42 rc = gnutls_x509_privkey_init (&key);
43 if (rc)
44 return NULL;
45 data.size = strlen (pkcs8_key);
46 data.data = (void *) g_strdup (pkcs8_key);
47 rc = gnutls_x509_privkey_import_pkcs8 (key, &data, GNUTLS_X509_FMT_PEM,
48 passphrase ? passphrase : "", 0);
49 if (rc)
50 {
51 gnutls_x509_privkey_deinit (key);
52 return NULL;
53 }
54 g_free (data.data);
55 rc = gnutls_x509_privkey_export (key, GNUTLS_X509_FMT_PEM, buffer, &size);
56 gnutls_x509_privkey_deinit (key);
57 if (rc)
58 return NULL;
59 return g_strdup (buffer);
60}
61
71char *
72gvm_ssh_public_from_private (const char *private_key, const char *passphrase)
73{
74 ssh_key priv;
75 char *pub_key, *decrypted_priv, *pub_str = NULL;
76 const char *type;
77 int ret;
78
79 if (private_key == NULL)
80 return NULL;
81 decrypted_priv = gvm_ssh_pkcs8_decrypt (private_key, passphrase);
82 ret = ssh_pki_import_privkey_base64 (decrypted_priv ? decrypted_priv
83 : private_key,
84 passphrase, NULL, NULL, &priv);
85 g_free (decrypted_priv);
86 if (ret)
87 return NULL;
88 ret = ssh_pki_export_pubkey_base64 (priv, &pub_key);
89 type = ssh_key_type_to_char (ssh_key_type (priv));
90#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0, 6, 4)
91 if (!strcmp (type, "ssh-ecdsa"))
92 type = ssh_pki_key_ecdsa_name (priv);
93#endif
94 ssh_key_free (priv);
95 if (ret)
96 return NULL;
97 pub_str = g_strdup_printf ("%s %s", type, pub_key);
98 g_free (pub_key);
99 return pub_str;
100}
char * gvm_ssh_pkcs8_decrypt(const char *pkcs8_key, const char *passphrase)
Decrypts a base64 encrypted ssh private key.
Definition sshutils.c:34
char * gvm_ssh_public_from_private(const char *private_key, const char *passphrase)
Exports a base64 encoded public key from a private key and its passphrase.
Definition sshutils.c:72
SSH related API.