[BACK]Return to ssh-keygen.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/ssh-keygen.c, Revision 1.322

1.322   ! djm         1: /* $OpenBSD: ssh-keygen.c,v 1.321 2018/09/13 02:08:33 djm Exp $ */
1.1       deraadt     2: /*
1.13      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Identity and host key generation and maintenance.
1.31      deraadt     7:  *
                      8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
1.13      deraadt    13:  */
1.1       deraadt    14:
1.136     stevesk    15: #include <sys/types.h>
1.174     dtucker    16: #include <sys/socket.h>
1.136     stevesk    17: #include <sys/stat.h>
1.19      markus     18:
                     19: #include <openssl/evp.h>
                     20: #include <openssl/pem.h>
1.145     stevesk    21:
1.148     stevesk    22: #include <errno.h>
1.147     stevesk    23: #include <fcntl.h>
1.248     djm        24: #include <netdb.h>
1.145     stevesk    25: #include <pwd.h>
1.153     stevesk    26: #include <stdio.h>
1.152     stevesk    27: #include <stdlib.h>
1.150     stevesk    28: #include <string.h>
1.149     stevesk    29: #include <unistd.h>
1.253     deraadt    30: #include <limits.h>
1.294     djm        31: #include <locale.h>
1.1       deraadt    32:
                     33: #include "xmalloc.h"
1.252     djm        34: #include "sshkey.h"
1.19      markus     35: #include "authfile.h"
                     36: #include "uuencode.h"
1.252     djm        37: #include "sshbuf.h"
1.40      markus     38: #include "pathnames.h"
1.41      markus     39: #include "log.h"
1.114     djm        40: #include "misc.h"
1.119     djm        41: #include "match.h"
                     42: #include "hostfile.h"
1.146     stevesk    43: #include "dns.h"
1.223     djm        44: #include "ssh.h"
1.179     djm        45: #include "ssh2.h"
1.252     djm        46: #include "ssherr.h"
1.223     djm        47: #include "atomicio.h"
                     48: #include "krl.h"
1.251     djm        49: #include "digest.h"
1.294     djm        50: #include "utf8.h"
1.305     djm        51: #include "authfd.h"
1.32      markus     52:
1.177     markus     53: #ifdef ENABLE_PKCS11
                     54: #include "ssh-pkcs11.h"
1.106     djm        55: #endif
1.66      markus     56:
1.273     djm        57: #ifdef WITH_OPENSSL
                     58: # define DEFAULT_KEY_TYPE_NAME "rsa"
                     59: #else
                     60: # define DEFAULT_KEY_TYPE_NAME "ed25519"
                     61: #endif
                     62:
1.130     markus     63: /* Number of bits in the RSA/DSA key.  This value can be set on the command line. */
                     64: #define DEFAULT_BITS           2048
                     65: #define DEFAULT_BITS_DSA       1024
1.203     naddy      66: #define DEFAULT_BITS_ECDSA     256
1.130     markus     67: u_int32_t bits = 0;
1.1       deraadt    68:
1.14      markus     69: /*
                     70:  * Flag indicating that we just want to change the passphrase.  This can be
                     71:  * set on the command line.
                     72:  */
1.1       deraadt    73: int change_passphrase = 0;
                     74:
1.14      markus     75: /*
                     76:  * Flag indicating that we just want to change the comment.  This can be set
                     77:  * on the command line.
                     78:  */
1.1       deraadt    79: int change_comment = 0;
                     80:
1.2       provos     81: int quiet = 0;
                     82:
1.169     grunk      83: int log_level = SYSLOG_LEVEL_INFO;
                     84:
1.119     djm        85: /* Flag indicating that we want to hash a known_hosts file */
                     86: int hash_hosts = 0;
                     87: /* Flag indicating that we want lookup a host in known_hosts file */
                     88: int find_host = 0;
                     89: /* Flag indicating that we want to delete a host from a known_hosts file */
                     90: int delete_host = 0;
                     91:
1.182     djm        92: /* Flag indicating that we want to show the contents of a certificate */
                     93: int show_cert = 0;
                     94:
1.8       markus     95: /* Flag indicating that we just want to see the key fingerprint */
                     96: int print_fingerprint = 0;
1.49      markus     97: int print_bubblebabble = 0;
1.8       markus     98:
1.251     djm        99: /* Hash algorithm to use for fingerprints. */
                    100: int fingerprint_hash = SSH_FP_HASH_DEFAULT;
                    101:
1.10      markus    102: /* The identity file name, given on the command line or entered by the user. */
                    103: char identity_file[1024];
                    104: int have_identity = 0;
1.1       deraadt   105:
                    106: /* This is set to the passphrase if given on the command line. */
                    107: char *identity_passphrase = NULL;
                    108:
                    109: /* This is set to the new passphrase if given on the command line. */
                    110: char *identity_new_passphrase = NULL;
                    111:
                    112: /* This is set to the new comment if given on the command line. */
                    113: char *identity_comment = NULL;
                    114:
1.179     djm       115: /* Path to CA key when certifying keys. */
                    116: char *ca_key_path = NULL;
                    117:
1.305     djm       118: /* Prefer to use agent keys for CA signing */
                    119: int prefer_agent = 0;
                    120:
1.186     djm       121: /* Certificate serial number */
1.220     djm       122: unsigned long long cert_serial = 0;
1.186     djm       123:
1.179     djm       124: /* Key type when certifying */
                    125: u_int cert_key_type = SSH2_CERT_TYPE_USER;
                    126:
                    127: /* "key ID" of signed key */
                    128: char *cert_key_id = NULL;
                    129:
                    130: /* Comma-separated list of principal names for certifying keys */
                    131: char *cert_principals = NULL;
                    132:
                    133: /* Validity period for certificates */
                    134: u_int64_t cert_valid_from = 0;
                    135: u_int64_t cert_valid_to = ~0ULL;
                    136:
1.186     djm       137: /* Certificate options */
1.190     djm       138: #define CERTOPT_X_FWD  (1)
                    139: #define CERTOPT_AGENT_FWD      (1<<1)
                    140: #define CERTOPT_PORT_FWD       (1<<2)
                    141: #define CERTOPT_PTY            (1<<3)
                    142: #define CERTOPT_USER_RC        (1<<4)
                    143: #define CERTOPT_DEFAULT        (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
                    144:                         CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
                    145: u_int32_t certflags_flags = CERTOPT_DEFAULT;
                    146: char *certflags_command = NULL;
                    147: char *certflags_src_addr = NULL;
1.179     djm       148:
1.300     djm       149: /* Arbitrary extensions specified by user */
                    150: struct cert_userext {
                    151:        char *key;
                    152:        char *val;
                    153:        int crit;
                    154: };
                    155: struct cert_userext *cert_userext;
                    156: size_t ncert_userext;
                    157:
1.193     djm       158: /* Conversion to/from various formats */
                    159: int convert_to = 0;
                    160: int convert_from = 0;
                    161: enum {
                    162:        FMT_RFC4716,
                    163:        FMT_PKCS8,
                    164:        FMT_PEM
                    165: } convert_format = FMT_RFC4716;
1.19      markus    166: int print_public = 0;
1.105     jakob     167: int print_generic = 0;
1.33      markus    168:
1.87      djm       169: char *key_type_name = NULL;
1.19      markus    170:
1.197     djm       171: /* Load key from this PKCS#11 provider */
                    172: char *pkcs11provider = NULL;
1.193     djm       173:
1.237     markus    174: /* Use new OpenSSH private key format when writing SSH2 keys instead of PEM */
1.319     djm       175: int use_new_format = 1;
1.237     markus    176:
                    177: /* Cipher for new-format private keys */
                    178: char *new_format_cipher = NULL;
                    179:
                    180: /*
                    181:  * Number of KDF rounds to derive new format keys /
                    182:  * number of primality trials when screening moduli.
                    183:  */
                    184: int rounds = 0;
                    185:
1.10      markus    186: /* argv0 */
                    187: extern char *__progname;
1.1       deraadt   188:
1.248     djm       189: char hostname[NI_MAXHOST];
1.19      markus    190:
1.274     djm       191: #ifdef WITH_OPENSSL
1.115     djm       192: /* moduli.c */
1.124     avsm      193: int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
1.215     dtucker   194: int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
                    195:     unsigned long);
1.274     djm       196: #endif
1.115     djm       197:
1.63      itojun    198: static void
1.255     djm       199: type_bits_valid(int type, const char *name, u_int32_t *bitsp)
1.206     stevesk   200: {
1.271     djm       201: #ifdef WITH_OPENSSL
1.255     djm       202:        u_int maxbits, nid;
1.271     djm       203: #endif
1.206     stevesk   204:
1.269     djm       205:        if (type == KEY_UNSPEC)
                    206:                fatal("unknown key type %s", key_type_name);
1.209     djm       207:        if (*bitsp == 0) {
1.271     djm       208: #ifdef WITH_OPENSSL
1.206     stevesk   209:                if (type == KEY_DSA)
1.209     djm       210:                        *bitsp = DEFAULT_BITS_DSA;
1.255     djm       211:                else if (type == KEY_ECDSA) {
                    212:                        if (name != NULL &&
                    213:                            (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
                    214:                                *bitsp = sshkey_curve_nid_to_bits(nid);
                    215:                        if (*bitsp == 0)
                    216:                                *bitsp = DEFAULT_BITS_ECDSA;
1.291     dtucker   217:                } else
1.271     djm       218: #endif
1.209     djm       219:                        *bitsp = DEFAULT_BITS;
1.206     stevesk   220:        }
1.271     djm       221: #ifdef WITH_OPENSSL
1.206     stevesk   222:        maxbits = (type == KEY_DSA) ?
                    223:            OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
1.269     djm       224:        if (*bitsp > maxbits)
                    225:                fatal("key bits exceeds maximum %d", maxbits);
1.303     djm       226:        switch (type) {
                    227:        case KEY_DSA:
                    228:                if (*bitsp != 1024)
                    229:                        fatal("Invalid DSA key length: must be 1024 bits");
                    230:                break;
                    231:        case KEY_RSA:
                    232:                if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
                    233:                        fatal("Invalid RSA key length: minimum is %d bits",
                    234:                            SSH_RSA_MINIMUM_MODULUS_SIZE);
                    235:                break;
                    236:        case KEY_ECDSA:
                    237:                if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
                    238:                        fatal("Invalid ECDSA key length: valid lengths are "
                    239:                            "256, 384 or 521 bits");
                    240:        }
1.246     markus    241: #endif
1.206     stevesk   242: }
                    243:
                    244: static void
1.10      markus    245: ask_filename(struct passwd *pw, const char *prompt)
1.1       deraadt   246: {
1.12      markus    247:        char buf[1024];
1.35      markus    248:        char *name = NULL;
                    249:
1.92      stevesk   250:        if (key_type_name == NULL)
1.40      markus    251:                name = _PATH_SSH_CLIENT_ID_RSA;
1.140     deraadt   252:        else {
1.252     djm       253:                switch (sshkey_type_from_name(key_type_name)) {
1.186     djm       254:                case KEY_DSA_CERT:
1.92      stevesk   255:                case KEY_DSA:
                    256:                        name = _PATH_SSH_CLIENT_ID_DSA;
                    257:                        break;
1.200     djm       258:                case KEY_ECDSA_CERT:
                    259:                case KEY_ECDSA:
                    260:                        name = _PATH_SSH_CLIENT_ID_ECDSA;
                    261:                        break;
1.186     djm       262:                case KEY_RSA_CERT:
1.92      stevesk   263:                case KEY_RSA:
                    264:                        name = _PATH_SSH_CLIENT_ID_RSA;
                    265:                        break;
1.238     markus    266:                case KEY_ED25519:
                    267:                case KEY_ED25519_CERT:
                    268:                        name = _PATH_SSH_CLIENT_ID_ED25519;
                    269:                        break;
1.313     markus    270:                case KEY_XMSS:
                    271:                case KEY_XMSS_CERT:
                    272:                        name = _PATH_SSH_CLIENT_ID_XMSS;
                    273:                        break;
1.92      stevesk   274:                default:
1.269     djm       275:                        fatal("bad key type");
1.92      stevesk   276:                }
1.140     deraadt   277:        }
1.269     djm       278:        snprintf(identity_file, sizeof(identity_file),
                    279:            "%s/%s", pw->pw_dir, name);
                    280:        printf("%s (%s): ", prompt, identity_file);
                    281:        fflush(stdout);
1.12      markus    282:        if (fgets(buf, sizeof(buf), stdin) == NULL)
                    283:                exit(1);
1.162     gilles    284:        buf[strcspn(buf, "\n")] = '\0';
1.12      markus    285:        if (strcmp(buf, "") != 0)
                    286:                strlcpy(identity_file, buf, sizeof(identity_file));
                    287:        have_identity = 1;
1.7       markus    288: }
                    289:
1.252     djm       290: static struct sshkey *
1.61      markus    291: load_identity(char *filename)
1.19      markus    292: {
1.52      markus    293:        char *pass;
1.252     djm       294:        struct sshkey *prv;
                    295:        int r;
1.52      markus    296:
1.252     djm       297:        if ((r = sshkey_load_private(filename, "", &prv, NULL)) == 0)
                    298:                return prv;
                    299:        if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
                    300:                fatal("Load key \"%s\": %s", filename, ssh_err(r));
                    301:        if (identity_passphrase)
                    302:                pass = xstrdup(identity_passphrase);
                    303:        else
                    304:                pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
                    305:        r = sshkey_load_private(filename, pass, &prv, NULL);
                    306:        explicit_bzero(pass, strlen(pass));
                    307:        free(pass);
                    308:        if (r != 0)
                    309:                fatal("Load key \"%s\": %s", filename, ssh_err(r));
1.52      markus    310:        return prv;
1.19      markus    311: }
                    312:
1.32      markus    313: #define SSH_COM_PUBLIC_BEGIN           "---- BEGIN SSH2 PUBLIC KEY ----"
1.100     deraadt   314: #define SSH_COM_PUBLIC_END             "---- END SSH2 PUBLIC KEY ----"
1.32      markus    315: #define SSH_COM_PRIVATE_BEGIN          "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
1.42      stevesk   316: #define        SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
1.19      markus    317:
1.246     markus    318: #ifdef WITH_OPENSSL
1.63      itojun    319: static void
1.252     djm       320: do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
1.19      markus    321: {
1.252     djm       322:        size_t len;
1.36      markus    323:        u_char *blob;
1.176     djm       324:        char comment[61];
1.252     djm       325:        int r;
1.19      markus    326:
1.269     djm       327:        if ((r = sshkey_to_blob(k, &blob, &len)) != 0)
                    328:                fatal("key_to_blob failed: %s", ssh_err(r));
1.176     djm       329:        /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
                    330:        snprintf(comment, sizeof(comment),
                    331:            "%u-bit %s, converted by %s@%s from OpenSSH",
1.252     djm       332:            sshkey_size(k), sshkey_type(k),
1.19      markus    333:            pw->pw_name, hostname);
1.176     djm       334:
                    335:        fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
                    336:        fprintf(stdout, "Comment: \"%s\"\n", comment);
1.19      markus    337:        dump_base64(stdout, blob, len);
1.32      markus    338:        fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
1.252     djm       339:        sshkey_free(k);
1.227     djm       340:        free(blob);
1.19      markus    341:        exit(0);
                    342: }
                    343:
1.63      itojun    344: static void
1.252     djm       345: do_convert_to_pkcs8(struct sshkey *k)
1.193     djm       346: {
1.252     djm       347:        switch (sshkey_type_plain(k->type)) {
1.193     djm       348:        case KEY_RSA:
                    349:                if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
                    350:                        fatal("PEM_write_RSA_PUBKEY failed");
                    351:                break;
                    352:        case KEY_DSA:
                    353:                if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
                    354:                        fatal("PEM_write_DSA_PUBKEY failed");
                    355:                break;
1.200     djm       356:        case KEY_ECDSA:
                    357:                if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
                    358:                        fatal("PEM_write_EC_PUBKEY failed");
                    359:                break;
1.193     djm       360:        default:
1.252     djm       361:                fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
1.193     djm       362:        }
                    363:        exit(0);
                    364: }
                    365:
                    366: static void
1.252     djm       367: do_convert_to_pem(struct sshkey *k)
1.193     djm       368: {
1.252     djm       369:        switch (sshkey_type_plain(k->type)) {
1.193     djm       370:        case KEY_RSA:
                    371:                if (!PEM_write_RSAPublicKey(stdout, k->rsa))
                    372:                        fatal("PEM_write_RSAPublicKey failed");
                    373:                break;
                    374:        default:
1.252     djm       375:                fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
1.193     djm       376:        }
                    377:        exit(0);
                    378: }
                    379:
                    380: static void
                    381: do_convert_to(struct passwd *pw)
                    382: {
1.252     djm       383:        struct sshkey *k;
1.193     djm       384:        struct stat st;
1.252     djm       385:        int r;
1.193     djm       386:
                    387:        if (!have_identity)
                    388:                ask_filename(pw, "Enter file in which the key is");
                    389:        if (stat(identity_file, &st) < 0)
                    390:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1.252     djm       391:        if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
                    392:                k = load_identity(identity_file);
1.193     djm       393:        switch (convert_format) {
                    394:        case FMT_RFC4716:
                    395:                do_convert_to_ssh2(pw, k);
                    396:                break;
                    397:        case FMT_PKCS8:
                    398:                do_convert_to_pkcs8(k);
                    399:                break;
                    400:        case FMT_PEM:
                    401:                do_convert_to_pem(k);
                    402:                break;
                    403:        default:
                    404:                fatal("%s: unknown key format %d", __func__, convert_format);
                    405:        }
                    406:        exit(0);
                    407: }
                    408:
1.252     djm       409: /*
                    410:  * This is almost exactly the bignum1 encoding, but with 32 bit for length
                    411:  * instead of 16.
                    412:  */
1.193     djm       413: static void
1.252     djm       414: buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
1.32      markus    415: {
1.252     djm       416:        u_int bytes, bignum_bits;
                    417:        int r;
1.53      markus    418:
1.252     djm       419:        if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
                    420:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    421:        bytes = (bignum_bits + 7) / 8;
                    422:        if (sshbuf_len(b) < bytes)
                    423:                fatal("%s: input buffer too small: need %d have %zu",
                    424:                    __func__, bytes, sshbuf_len(b));
                    425:        if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
                    426:                fatal("%s: BN_bin2bn failed", __func__);
                    427:        if ((r = sshbuf_consume(b, bytes)) != 0)
                    428:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.32      markus    429: }
                    430:
1.252     djm       431: static struct sshkey *
1.93      markus    432: do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
1.32      markus    433: {
1.252     djm       434:        struct sshbuf *b;
                    435:        struct sshkey *key = NULL;
1.64      markus    436:        char *type, *cipher;
1.252     djm       437:        u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
                    438:        int r, rlen, ktype;
                    439:        u_int magic, i1, i2, i3, i4;
                    440:        size_t slen;
1.62      markus    441:        u_long e;
1.321     djm       442:        BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
                    443:        BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
                    444:        BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
                    445:        BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
1.252     djm       446:        if ((b = sshbuf_from(blob, blen)) == NULL)
                    447:                fatal("%s: sshbuf_from failed", __func__);
                    448:        if ((r = sshbuf_get_u32(b, &magic)) != 0)
                    449:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.32      markus    450:
                    451:        if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
1.252     djm       452:                error("bad magic 0x%x != 0x%x", magic,
                    453:                    SSH_COM_PRIVATE_KEY_MAGIC);
                    454:                sshbuf_free(b);
1.32      markus    455:                return NULL;
                    456:        }
1.252     djm       457:        if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
                    458:            (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
                    459:            (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
                    460:            (r = sshbuf_get_u32(b, &i2)) != 0 ||
                    461:            (r = sshbuf_get_u32(b, &i3)) != 0 ||
                    462:            (r = sshbuf_get_u32(b, &i4)) != 0)
                    463:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.158     stevesk   464:        debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
1.32      markus    465:        if (strcmp(cipher, "none") != 0) {
                    466:                error("unsupported cipher %s", cipher);
1.227     djm       467:                free(cipher);
1.252     djm       468:                sshbuf_free(b);
1.227     djm       469:                free(type);
1.32      markus    470:                return NULL;
                    471:        }
1.227     djm       472:        free(cipher);
1.32      markus    473:
1.53      markus    474:        if (strstr(type, "dsa")) {
                    475:                ktype = KEY_DSA;
                    476:        } else if (strstr(type, "rsa")) {
                    477:                ktype = KEY_RSA;
                    478:        } else {
1.252     djm       479:                sshbuf_free(b);
1.227     djm       480:                free(type);
1.32      markus    481:                return NULL;
                    482:        }
1.322   ! djm       483:        if ((key = sshkey_new(ktype)) == NULL)
        !           484:                fatal("sshkey_new failed");
1.227     djm       485:        free(type);
1.53      markus    486:
                    487:        switch (key->type) {
                    488:        case KEY_DSA:
1.321     djm       489:                if ((dsa_p = BN_new()) == NULL ||
                    490:                    (dsa_q = BN_new()) == NULL ||
                    491:                    (dsa_g = BN_new()) == NULL ||
                    492:                    (dsa_pub_key = BN_new()) == NULL ||
                    493:                    (dsa_priv_key = BN_new()) == NULL)
                    494:                        fatal("%s: BN_new", __func__);
                    495:                buffer_get_bignum_bits(b, dsa_p);
                    496:                buffer_get_bignum_bits(b, dsa_g);
                    497:                buffer_get_bignum_bits(b, dsa_q);
                    498:                buffer_get_bignum_bits(b, dsa_pub_key);
                    499:                buffer_get_bignum_bits(b, dsa_priv_key);
                    500:                if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
                    501:                        fatal("%s: DSA_set0_pqg failed", __func__);
                    502:                dsa_p = dsa_q = dsa_g = NULL; /* transferred */
                    503:                if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
                    504:                        fatal("%s: DSA_set0_key failed", __func__);
                    505:                dsa_pub_key = dsa_priv_key = NULL; /* transferred */
1.53      markus    506:                break;
                    507:        case KEY_RSA:
1.252     djm       508:                if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
                    509:                    (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
                    510:                    (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
                    511:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
                    512:                e = e1;
1.62      markus    513:                debug("e %lx", e);
                    514:                if (e < 30) {
                    515:                        e <<= 8;
1.252     djm       516:                        e += e2;
1.62      markus    517:                        debug("e %lx", e);
                    518:                        e <<= 8;
1.252     djm       519:                        e += e3;
1.62      markus    520:                        debug("e %lx", e);
                    521:                }
1.321     djm       522:                if ((rsa_e = BN_new()) == NULL)
                    523:                        fatal("%s: BN_new", __func__);
                    524:                if (!BN_set_word(rsa_e, e)) {
                    525:                        BN_clear_free(rsa_e);
1.252     djm       526:                        sshbuf_free(b);
                    527:                        sshkey_free(key);
1.53      markus    528:                        return NULL;
                    529:                }
1.321     djm       530:                if ((rsa_n = BN_new()) == NULL ||
                    531:                    (rsa_d = BN_new()) == NULL ||
                    532:                    (rsa_p = BN_new()) == NULL ||
                    533:                    (rsa_q = BN_new()) == NULL ||
                    534:                    (rsa_iqmp = BN_new()) == NULL)
                    535:                        fatal("%s: BN_new", __func__);
                    536:                buffer_get_bignum_bits(b, rsa_d);
                    537:                buffer_get_bignum_bits(b, rsa_n);
                    538:                buffer_get_bignum_bits(b, rsa_iqmp);
                    539:                buffer_get_bignum_bits(b, rsa_q);
                    540:                buffer_get_bignum_bits(b, rsa_p);
                    541:                if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
                    542:                        fatal("%s: RSA_set0_key failed", __func__);
                    543:                rsa_n = rsa_e = rsa_d = NULL; /* transferred */
                    544:                if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
                    545:                        fatal("%s: RSA_set0_factors failed", __func__);
                    546:                rsa_p = rsa_q = NULL; /* transferred */
                    547:                if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
1.252     djm       548:                        fatal("generate RSA parameters failed: %s", ssh_err(r));
1.321     djm       549:                BN_clear_free(rsa_iqmp);
1.53      markus    550:                break;
                    551:        }
1.252     djm       552:        rlen = sshbuf_len(b);
1.85      deraadt   553:        if (rlen != 0)
1.53      markus    554:                error("do_convert_private_ssh2_from_blob: "
                    555:                    "remaining bytes in key blob %d", rlen);
1.252     djm       556:        sshbuf_free(b);
1.64      markus    557:
                    558:        /* try the key */
1.285     markus    559:        if (sshkey_sign(key, &sig, &slen, data, sizeof(data), NULL, 0) != 0 ||
1.309     djm       560:            sshkey_verify(key, sig, slen, data, sizeof(data), NULL, 0) != 0) {
1.252     djm       561:                sshkey_free(key);
                    562:                free(sig);
                    563:                return NULL;
                    564:        }
1.227     djm       565:        free(sig);
1.32      markus    566:        return key;
                    567: }
                    568:
1.137     dtucker   569: static int
                    570: get_line(FILE *fp, char *line, size_t len)
                    571: {
                    572:        int c;
                    573:        size_t pos = 0;
                    574:
                    575:        line[0] = '\0';
                    576:        while ((c = fgetc(fp)) != EOF) {
1.269     djm       577:                if (pos >= len - 1)
                    578:                        fatal("input line too long.");
1.140     deraadt   579:                switch (c) {
1.137     dtucker   580:                case '\r':
                    581:                        c = fgetc(fp);
1.269     djm       582:                        if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
                    583:                                fatal("unget: %s", strerror(errno));
1.137     dtucker   584:                        return pos;
                    585:                case '\n':
                    586:                        return pos;
                    587:                }
                    588:                line[pos++] = c;
                    589:                line[pos] = '\0';
                    590:        }
1.157     stevesk   591:        /* We reached EOF */
                    592:        return -1;
1.137     dtucker   593: }
                    594:
1.63      itojun    595: static void
1.252     djm       596: do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
1.19      markus    597: {
1.252     djm       598:        int r, blen, escaped = 0;
1.98      markus    599:        u_int len;
1.137     dtucker   600:        char line[1024];
1.80      stevesk   601:        u_char blob[8096];
1.19      markus    602:        char encoded[8096];
                    603:        FILE *fp;
                    604:
1.191     djm       605:        if ((fp = fopen(identity_file, "r")) == NULL)
                    606:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1.19      markus    607:        encoded[0] = '\0';
1.137     dtucker   608:        while ((blen = get_line(fp, line, sizeof(line))) != -1) {
1.228     djm       609:                if (blen > 0 && line[blen - 1] == '\\')
1.25      markus    610:                        escaped++;
1.19      markus    611:                if (strncmp(line, "----", 4) == 0 ||
                    612:                    strstr(line, ": ") != NULL) {
1.32      markus    613:                        if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
1.193     djm       614:                                *private = 1;
1.64      markus    615:                        if (strstr(line, " END ") != NULL) {
                    616:                                break;
                    617:                        }
1.60      markus    618:                        /* fprintf(stderr, "ignore: %s", line); */
1.19      markus    619:                        continue;
                    620:                }
1.25      markus    621:                if (escaped) {
                    622:                        escaped--;
1.60      markus    623:                        /* fprintf(stderr, "escaped: %s", line); */
1.25      markus    624:                        continue;
1.19      markus    625:                }
                    626:                strlcat(encoded, line, sizeof(encoded));
                    627:        }
1.98      markus    628:        len = strlen(encoded);
                    629:        if (((len % 4) == 3) &&
                    630:            (encoded[len-1] == '=') &&
                    631:            (encoded[len-2] == '=') &&
                    632:            (encoded[len-3] == '='))
                    633:                encoded[len-3] = '\0';
1.91      stevesk   634:        blen = uudecode(encoded, blob, sizeof(blob));
1.269     djm       635:        if (blen < 0)
                    636:                fatal("uudecode failed.");
1.252     djm       637:        if (*private)
                    638:                *k = do_convert_private_ssh2_from_blob(blob, blen);
1.269     djm       639:        else if ((r = sshkey_from_blob(blob, blen, k)) != 0)
                    640:                fatal("decode blob failed: %s", ssh_err(r));
1.193     djm       641:        fclose(fp);
                    642: }
                    643:
                    644: static void
1.252     djm       645: do_convert_from_pkcs8(struct sshkey **k, int *private)
1.193     djm       646: {
                    647:        EVP_PKEY *pubkey;
                    648:        FILE *fp;
                    649:
                    650:        if ((fp = fopen(identity_file, "r")) == NULL)
                    651:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    652:        if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
                    653:                fatal("%s: %s is not a recognised public key format", __func__,
                    654:                    identity_file);
                    655:        }
                    656:        fclose(fp);
1.321     djm       657:        switch (EVP_PKEY_base_id(pubkey)) {
1.193     djm       658:        case EVP_PKEY_RSA:
1.252     djm       659:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    660:                        fatal("sshkey_new failed");
1.193     djm       661:                (*k)->type = KEY_RSA;
                    662:                (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
                    663:                break;
                    664:        case EVP_PKEY_DSA:
1.252     djm       665:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    666:                        fatal("sshkey_new failed");
1.193     djm       667:                (*k)->type = KEY_DSA;
                    668:                (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
                    669:                break;
1.200     djm       670:        case EVP_PKEY_EC:
1.252     djm       671:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    672:                        fatal("sshkey_new failed");
1.200     djm       673:                (*k)->type = KEY_ECDSA;
                    674:                (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
1.252     djm       675:                (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
1.200     djm       676:                break;
1.193     djm       677:        default:
                    678:                fatal("%s: unsupported pubkey type %d", __func__,
1.321     djm       679:                    EVP_PKEY_base_id(pubkey));
1.193     djm       680:        }
                    681:        EVP_PKEY_free(pubkey);
                    682:        return;
                    683: }
                    684:
                    685: static void
1.252     djm       686: do_convert_from_pem(struct sshkey **k, int *private)
1.193     djm       687: {
                    688:        FILE *fp;
                    689:        RSA *rsa;
                    690:
                    691:        if ((fp = fopen(identity_file, "r")) == NULL)
                    692:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    693:        if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
1.252     djm       694:                if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
                    695:                        fatal("sshkey_new failed");
1.193     djm       696:                (*k)->type = KEY_RSA;
                    697:                (*k)->rsa = rsa;
                    698:                fclose(fp);
                    699:                return;
                    700:        }
                    701:        fatal("%s: unrecognised raw private key format", __func__);
                    702: }
                    703:
                    704: static void
                    705: do_convert_from(struct passwd *pw)
                    706: {
1.252     djm       707:        struct sshkey *k = NULL;
                    708:        int r, private = 0, ok = 0;
1.193     djm       709:        struct stat st;
                    710:
                    711:        if (!have_identity)
                    712:                ask_filename(pw, "Enter file in which the key is");
                    713:        if (stat(identity_file, &st) < 0)
                    714:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                    715:
                    716:        switch (convert_format) {
                    717:        case FMT_RFC4716:
                    718:                do_convert_from_ssh2(pw, &k, &private);
                    719:                break;
                    720:        case FMT_PKCS8:
                    721:                do_convert_from_pkcs8(&k, &private);
                    722:                break;
                    723:        case FMT_PEM:
                    724:                do_convert_from_pem(&k, &private);
                    725:                break;
                    726:        default:
                    727:                fatal("%s: unknown key format %d", __func__, convert_format);
                    728:        }
                    729:
1.260     djm       730:        if (!private) {
1.252     djm       731:                if ((r = sshkey_write(k, stdout)) == 0)
                    732:                        ok = 1;
1.193     djm       733:                if (ok)
                    734:                        fprintf(stdout, "\n");
1.260     djm       735:        } else {
1.193     djm       736:                switch (k->type) {
                    737:                case KEY_DSA:
                    738:                        ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
                    739:                            NULL, 0, NULL, NULL);
                    740:                        break;
1.200     djm       741:                case KEY_ECDSA:
                    742:                        ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
                    743:                            NULL, 0, NULL, NULL);
                    744:                        break;
1.193     djm       745:                case KEY_RSA:
                    746:                        ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
                    747:                            NULL, 0, NULL, NULL);
                    748:                        break;
                    749:                default:
                    750:                        fatal("%s: unsupported key type %s", __func__,
1.252     djm       751:                            sshkey_type(k));
1.193     djm       752:                }
                    753:        }
                    754:
1.269     djm       755:        if (!ok)
                    756:                fatal("key write failed");
1.252     djm       757:        sshkey_free(k);
1.19      markus    758:        exit(0);
                    759: }
1.246     markus    760: #endif
1.19      markus    761:
1.63      itojun    762: static void
1.19      markus    763: do_print_public(struct passwd *pw)
                    764: {
1.252     djm       765:        struct sshkey *prv;
1.19      markus    766:        struct stat st;
1.252     djm       767:        int r;
1.19      markus    768:
                    769:        if (!have_identity)
                    770:                ask_filename(pw, "Enter file in which the key is");
1.269     djm       771:        if (stat(identity_file, &st) < 0)
                    772:                fatal("%s: %s", identity_file, strerror(errno));
1.61      markus    773:        prv = load_identity(identity_file);
1.252     djm       774:        if ((r = sshkey_write(prv, stdout)) != 0)
1.304     markus    775:                error("sshkey_write failed: %s", ssh_err(r));
1.252     djm       776:        sshkey_free(prv);
1.19      markus    777:        fprintf(stdout, "\n");
                    778:        exit(0);
                    779: }
                    780:
1.66      markus    781: static void
1.197     djm       782: do_download(struct passwd *pw)
1.75      markus    783: {
1.177     markus    784: #ifdef ENABLE_PKCS11
1.252     djm       785:        struct sshkey **keys = NULL;
1.177     markus    786:        int i, nkeys;
1.252     djm       787:        enum sshkey_fp_rep rep;
1.251     djm       788:        int fptype;
1.221     djm       789:        char *fp, *ra;
1.222     djm       790:
1.251     djm       791:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                    792:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.75      markus    793:
1.177     markus    794:        pkcs11_init(0);
                    795:        nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
                    796:        if (nkeys <= 0)
                    797:                fatal("cannot read public key from pkcs11");
                    798:        for (i = 0; i < nkeys; i++) {
1.221     djm       799:                if (print_fingerprint) {
1.252     djm       800:                        fp = sshkey_fingerprint(keys[i], fptype, rep);
                    801:                        ra = sshkey_fingerprint(keys[i], fingerprint_hash,
1.221     djm       802:                            SSH_FP_RANDOMART);
1.259     djm       803:                        if (fp == NULL || ra == NULL)
                    804:                                fatal("%s: sshkey_fingerprint fail", __func__);
1.252     djm       805:                        printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
                    806:                            fp, sshkey_type(keys[i]));
1.221     djm       807:                        if (log_level >= SYSLOG_LEVEL_VERBOSE)
                    808:                                printf("%s\n", ra);
1.227     djm       809:                        free(ra);
                    810:                        free(fp);
1.221     djm       811:                } else {
1.252     djm       812:                        (void) sshkey_write(keys[i], stdout); /* XXX check */
1.221     djm       813:                        fprintf(stdout, "\n");
                    814:                }
1.252     djm       815:                sshkey_free(keys[i]);
1.97      markus    816:        }
1.227     djm       817:        free(keys);
1.177     markus    818:        pkcs11_terminate();
1.75      markus    819:        exit(0);
1.177     markus    820: #else
                    821:        fatal("no pkcs11 support");
                    822: #endif /* ENABLE_PKCS11 */
1.75      markus    823: }
1.66      markus    824:
1.279     djm       825: static struct sshkey *
                    826: try_read_key(char **cpp)
                    827: {
                    828:        struct sshkey *ret;
                    829:        int r;
                    830:
                    831:        if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
                    832:                fatal("sshkey_new failed");
                    833:        if ((r = sshkey_read(ret, cpp)) == 0)
                    834:                return ret;
                    835:        /* Not a key */
                    836:        sshkey_free(ret);
                    837:        return NULL;
                    838: }
                    839:
1.63      itojun    840: static void
1.279     djm       841: fingerprint_one_key(const struct sshkey *public, const char *comment)
1.8       markus    842: {
1.279     djm       843:        char *fp = NULL, *ra = NULL;
1.252     djm       844:        enum sshkey_fp_rep rep;
1.251     djm       845:        int fptype;
1.12      markus    846:
1.251     djm       847:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                    848:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.279     djm       849:        fp = sshkey_fingerprint(public, fptype, rep);
                    850:        ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
                    851:        if (fp == NULL || ra == NULL)
                    852:                fatal("%s: sshkey_fingerprint failed", __func__);
1.294     djm       853:        mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
1.279     djm       854:            comment ? comment : "no comment", sshkey_type(public));
                    855:        if (log_level >= SYSLOG_LEVEL_VERBOSE)
                    856:                printf("%s\n", ra);
                    857:        free(ra);
                    858:        free(fp);
                    859: }
                    860:
                    861: static void
                    862: fingerprint_private(const char *path)
                    863: {
                    864:        struct stat st;
                    865:        char *comment = NULL;
                    866:        struct sshkey *public = NULL;
                    867:        int r;
                    868:
                    869:        if (stat(identity_file, &st) < 0)
                    870:                fatal("%s: %s", path, strerror(errno));
1.280     djm       871:        if ((r = sshkey_load_public(path, &public, &comment)) != 0) {
                    872:                debug("load public \"%s\": %s", path, ssh_err(r));
                    873:                if ((r = sshkey_load_private(path, NULL,
                    874:                    &public, &comment)) != 0) {
                    875:                        debug("load private \"%s\": %s", path, ssh_err(r));
                    876:                        fatal("%s is not a key file.", path);
                    877:                }
                    878:        }
                    879:
1.279     djm       880:        fingerprint_one_key(public, comment);
                    881:        sshkey_free(public);
                    882:        free(comment);
                    883: }
                    884:
                    885: static void
                    886: do_fingerprint(struct passwd *pw)
                    887: {
                    888:        FILE *f;
                    889:        struct sshkey *public = NULL;
1.317     markus    890:        char *comment = NULL, *cp, *ep, *line = NULL;
                    891:        size_t linesize = 0;
1.279     djm       892:        int i, invalid = 1;
                    893:        const char *path;
1.289     djm       894:        u_long lnum = 0;
1.279     djm       895:
1.12      markus    896:        if (!have_identity)
                    897:                ask_filename(pw, "Enter file in which the key is");
1.279     djm       898:        path = identity_file;
1.15      markus    899:
1.279     djm       900:        if (strcmp(identity_file, "-") == 0) {
                    901:                f = stdin;
                    902:                path = "(stdin)";
                    903:        } else if ((f = fopen(path, "r")) == NULL)
                    904:                fatal("%s: %s: %s", __progname, path, strerror(errno));
                    905:
1.317     markus    906:        while (getline(&line, &linesize, f) != -1) {
                    907:                lnum++;
1.279     djm       908:                cp = line;
                    909:                cp[strcspn(cp, "\n")] = '\0';
                    910:                /* Trim leading space and comments */
                    911:                cp = line + strspn(line, " \t");
                    912:                if (*cp == '#' || *cp == '\0')
                    913:                        continue;
1.191     djm       914:
1.279     djm       915:                /*
                    916:                 * Input may be plain keys, private keys, authorized_keys
                    917:                 * or known_hosts.
                    918:                 */
                    919:
                    920:                /*
                    921:                 * Try private keys first. Assume a key is private if
                    922:                 * "SSH PRIVATE KEY" appears on the first line and we're
                    923:                 * not reading from stdin (XXX support private keys on stdin).
                    924:                 */
                    925:                if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
1.280     djm       926:                    strstr(cp, "PRIVATE KEY") != NULL) {
1.317     markus    927:                        free(line);
1.279     djm       928:                        fclose(f);
                    929:                        fingerprint_private(path);
                    930:                        exit(0);
                    931:                }
                    932:
                    933:                /*
                    934:                 * If it's not a private key, then this must be prepared to
                    935:                 * accept a public key prefixed with a hostname or options.
                    936:                 * Try a bare key first, otherwise skip the leading stuff.
                    937:                 */
                    938:                if ((public = try_read_key(&cp)) == NULL) {
                    939:                        i = strtol(cp, &ep, 10);
                    940:                        if (i == 0 || ep == NULL ||
                    941:                            (*ep != ' ' && *ep != '\t')) {
                    942:                                int quoted = 0;
                    943:
                    944:                                comment = cp;
                    945:                                for (; *cp && (quoted || (*cp != ' ' &&
                    946:                                    *cp != '\t')); cp++) {
                    947:                                        if (*cp == '\\' && cp[1] == '"')
                    948:                                                cp++;   /* Skip both */
                    949:                                        else if (*cp == '"')
                    950:                                                quoted = !quoted;
                    951:                                }
                    952:                                if (!*cp)
                    953:                                        continue;
                    954:                                *cp++ = '\0';
                    955:                        }
1.191     djm       956:                }
1.279     djm       957:                /* Retry after parsing leading hostname/key options */
                    958:                if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1.289     djm       959:                        debug("%s:%lu: not a public key", path, lnum);
1.191     djm       960:                        continue;
                    961:                }
                    962:
1.279     djm       963:                /* Find trailing comment, if any */
                    964:                for (; *cp == ' ' || *cp == '\t'; cp++)
1.191     djm       965:                        ;
1.279     djm       966:                if (*cp != '\0' && *cp != '#')
1.191     djm       967:                        comment = cp;
1.279     djm       968:
                    969:                fingerprint_one_key(public, comment);
1.252     djm       970:                sshkey_free(public);
1.279     djm       971:                invalid = 0; /* One good key in the file is sufficient */
1.15      markus    972:        }
1.191     djm       973:        fclose(f);
1.317     markus    974:        free(line);
1.191     djm       975:
1.269     djm       976:        if (invalid)
1.279     djm       977:                fatal("%s is not a public key file.", path);
1.12      markus    978:        exit(0);
1.8       markus    979: }
                    980:
1.119     djm       981: static void
1.206     stevesk   982: do_gen_all_hostkeys(struct passwd *pw)
                    983: {
                    984:        struct {
                    985:                char *key_type;
                    986:                char *key_type_display;
                    987:                char *path;
                    988:        } key_types[] = {
1.267     djm       989: #ifdef WITH_OPENSSL
1.206     stevesk   990:                { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
                    991:                { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
                    992:                { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1.267     djm       993: #endif /* WITH_OPENSSL */
1.238     markus    994:                { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1.313     markus    995: #ifdef WITH_XMSS
                    996:                { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
                    997: #endif /* WITH_XMSS */
1.206     stevesk   998:                { NULL, NULL, NULL }
                    999:        };
                   1000:
                   1001:        int first = 0;
                   1002:        struct stat st;
1.252     djm      1003:        struct sshkey *private, *public;
1.307     djm      1004:        char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1.252     djm      1005:        int i, type, fd, r;
1.206     stevesk  1006:        FILE *f;
                   1007:
                   1008:        for (i = 0; key_types[i].key_type; i++) {
1.307     djm      1009:                public = private = NULL;
                   1010:                prv_tmp = pub_tmp = prv_file = pub_file = NULL;
                   1011:
                   1012:                xasprintf(&prv_file, "%s%s",
                   1013:                    identity_file, key_types[i].path);
                   1014:
                   1015:                /* Check whether private key exists and is not zero-length */
                   1016:                if (stat(prv_file, &st) == 0) {
                   1017:                        if (st.st_size != 0)
                   1018:                                goto next;
                   1019:                } else if (errno != ENOENT) {
1.269     djm      1020:                        error("Could not stat %s: %s", key_types[i].path,
1.206     stevesk  1021:                            strerror(errno));
1.307     djm      1022:                        goto failnext;
1.206     stevesk  1023:                }
                   1024:
1.307     djm      1025:                /*
                   1026:                 * Private key doesn't exist or is invalid; proceed with
                   1027:                 * key generation.
                   1028:                 */
                   1029:                xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
                   1030:                    identity_file, key_types[i].path);
                   1031:                xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
                   1032:                    identity_file, key_types[i].path);
                   1033:                xasprintf(&pub_file, "%s%s.pub",
                   1034:                    identity_file, key_types[i].path);
                   1035:
1.206     stevesk  1036:                if (first == 0) {
                   1037:                        first = 1;
                   1038:                        printf("%s: generating new host keys: ", __progname);
                   1039:                }
                   1040:                printf("%s ", key_types[i].key_type_display);
                   1041:                fflush(stdout);
1.252     djm      1042:                type = sshkey_type_from_name(key_types[i].key_type);
1.307     djm      1043:                if ((fd = mkstemp(prv_tmp)) == -1) {
                   1044:                        error("Could not save your public key in %s: %s",
                   1045:                            prv_tmp, strerror(errno));
                   1046:                        goto failnext;
                   1047:                }
                   1048:                close(fd); /* just using mkstemp() to generate/reserve a name */
1.206     stevesk  1049:                bits = 0;
1.255     djm      1050:                type_bits_valid(type, NULL, &bits);
1.252     djm      1051:                if ((r = sshkey_generate(type, bits, &private)) != 0) {
1.304     markus   1052:                        error("sshkey_generate failed: %s", ssh_err(r));
1.307     djm      1053:                        goto failnext;
1.206     stevesk  1054:                }
1.252     djm      1055:                if ((r = sshkey_from_private(private, &public)) != 0)
                   1056:                        fatal("sshkey_from_private failed: %s", ssh_err(r));
1.206     stevesk  1057:                snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
                   1058:                    hostname);
1.307     djm      1059:                if ((r = sshkey_save_private(private, prv_tmp, "",
1.252     djm      1060:                    comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      1061:                        error("Saving key \"%s\" failed: %s",
1.307     djm      1062:                            prv_tmp, ssh_err(r));
                   1063:                        goto failnext;
1.206     stevesk  1064:                }
1.307     djm      1065:                if ((fd = mkstemp(pub_tmp)) == -1) {
                   1066:                        error("Could not save your public key in %s: %s",
                   1067:                            pub_tmp, strerror(errno));
                   1068:                        goto failnext;
1.206     stevesk  1069:                }
1.307     djm      1070:                (void)fchmod(fd, 0644);
1.206     stevesk  1071:                f = fdopen(fd, "w");
                   1072:                if (f == NULL) {
1.307     djm      1073:                        error("fdopen %s failed: %s", pub_tmp, strerror(errno));
1.250     doug     1074:                        close(fd);
1.307     djm      1075:                        goto failnext;
1.206     stevesk  1076:                }
1.254     djm      1077:                if ((r = sshkey_write(public, f)) != 0) {
1.269     djm      1078:                        error("write key failed: %s", ssh_err(r));
1.250     doug     1079:                        fclose(f);
1.307     djm      1080:                        goto failnext;
                   1081:                }
                   1082:                fprintf(f, " %s\n", comment);
                   1083:                if (ferror(f) != 0) {
                   1084:                        error("write key failed: %s", strerror(errno));
                   1085:                        fclose(f);
                   1086:                        goto failnext;
                   1087:                }
                   1088:                if (fclose(f) != 0) {
                   1089:                        error("key close failed: %s", strerror(errno));
                   1090:                        goto failnext;
                   1091:                }
                   1092:
                   1093:                /* Rename temporary files to their permanent locations. */
                   1094:                if (rename(pub_tmp, pub_file) != 0) {
                   1095:                        error("Unable to move %s into position: %s",
                   1096:                            pub_file, strerror(errno));
                   1097:                        goto failnext;
                   1098:                }
                   1099:                if (rename(prv_tmp, prv_file) != 0) {
                   1100:                        error("Unable to move %s into position: %s",
                   1101:                            key_types[i].path, strerror(errno));
                   1102:  failnext:
1.206     stevesk  1103:                        first = 0;
1.307     djm      1104:                        goto next;
1.206     stevesk  1105:                }
1.307     djm      1106:  next:
                   1107:                sshkey_free(private);
1.252     djm      1108:                sshkey_free(public);
1.307     djm      1109:                free(prv_tmp);
                   1110:                free(pub_tmp);
                   1111:                free(prv_file);
                   1112:                free(pub_file);
1.206     stevesk  1113:        }
                   1114:        if (first != 0)
                   1115:                printf("\n");
                   1116: }
                   1117:
1.256     djm      1118: struct known_hosts_ctx {
1.257     djm      1119:        const char *host;       /* Hostname searched for in find/delete case */
                   1120:        FILE *out;              /* Output file, stdout for find_hosts case */
                   1121:        int has_unhashed;       /* When hashing, original had unhashed hosts */
                   1122:        int found_key;          /* For find/delete, host was found */
                   1123:        int invalid;            /* File contained invalid items; don't delete */
1.256     djm      1124: };
                   1125:
                   1126: static int
                   1127: known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1.119     djm      1128: {
1.256     djm      1129:        struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
                   1130:        char *hashed, *cp, *hosts, *ohosts;
                   1131:        int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1.298     dtucker  1132:        int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1.256     djm      1133:
1.262     djm      1134:        switch (l->status) {
                   1135:        case HKF_STATUS_OK:
                   1136:        case HKF_STATUS_MATCHED:
                   1137:                /*
                   1138:                 * Don't hash hosts already already hashed, with wildcard
                   1139:                 * characters or a CA/revocation marker.
                   1140:                 */
1.296     djm      1141:                if (was_hashed || has_wild || l->marker != MRK_NONE) {
1.262     djm      1142:                        fprintf(ctx->out, "%s\n", l->line);
                   1143:                        if (has_wild && !find_host) {
1.297     dtucker  1144:                                logit("%s:%lu: ignoring host name "
1.269     djm      1145:                                    "with wildcard: %.64s", l->path,
1.262     djm      1146:                                    l->linenum, l->hosts);
                   1147:                        }
                   1148:                        return 0;
                   1149:                }
                   1150:                /*
                   1151:                 * Split any comma-separated hostnames from the host list,
                   1152:                 * hash and store separately.
                   1153:                 */
                   1154:                ohosts = hosts = xstrdup(l->hosts);
                   1155:                while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1.299     djm      1156:                        lowercase(cp);
1.262     djm      1157:                        if ((hashed = host_hash(cp, NULL, 0)) == NULL)
                   1158:                                fatal("hash_host failed");
                   1159:                        fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
                   1160:                        ctx->has_unhashed = 1;
                   1161:                }
                   1162:                free(ohosts);
                   1163:                return 0;
                   1164:        case HKF_STATUS_INVALID:
                   1165:                /* Retain invalid lines, but mark file as invalid. */
1.256     djm      1166:                ctx->invalid = 1;
1.297     dtucker  1167:                logit("%s:%lu: invalid line", l->path, l->linenum);
1.262     djm      1168:                /* FALLTHROUGH */
                   1169:        default:
1.256     djm      1170:                fprintf(ctx->out, "%s\n", l->line);
                   1171:                return 0;
                   1172:        }
1.262     djm      1173:        /* NOTREACHED */
                   1174:        return -1;
1.256     djm      1175: }
                   1176:
                   1177: static int
                   1178: known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
                   1179: {
                   1180:        struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1.272     djm      1181:        enum sshkey_fp_rep rep;
                   1182:        int fptype;
                   1183:        char *fp;
                   1184:
                   1185:        fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
                   1186:        rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1.256     djm      1187:
1.262     djm      1188:        if (l->status == HKF_STATUS_MATCHED) {
1.256     djm      1189:                if (delete_host) {
                   1190:                        if (l->marker != MRK_NONE) {
                   1191:                                /* Don't remove CA and revocation lines */
                   1192:                                fprintf(ctx->out, "%s\n", l->line);
                   1193:                        } else {
                   1194:                                /*
                   1195:                                 * Hostname matches and has no CA/revoke
                   1196:                                 * marker, delete it by *not* writing the
                   1197:                                 * line to ctx->out.
                   1198:                                 */
                   1199:                                ctx->found_key = 1;
                   1200:                                if (!quiet)
1.297     dtucker  1201:                                        printf("# Host %s found: line %lu\n",
1.256     djm      1202:                                            ctx->host, l->linenum);
                   1203:                        }
                   1204:                        return 0;
                   1205:                } else if (find_host) {
                   1206:                        ctx->found_key = 1;
                   1207:                        if (!quiet) {
1.297     dtucker  1208:                                printf("# Host %s found: line %lu %s\n",
1.256     djm      1209:                                    ctx->host,
                   1210:                                    l->linenum, l->marker == MRK_CA ? "CA" :
                   1211:                                    (l->marker == MRK_REVOKE ? "REVOKED" : ""));
                   1212:                        }
                   1213:                        if (hash_hosts)
                   1214:                                known_hosts_hash(l, ctx);
1.272     djm      1215:                        else if (print_fingerprint) {
                   1216:                                fp = sshkey_fingerprint(l->key, fptype, rep);
1.294     djm      1217:                                mprintf("%s %s %s %s\n", ctx->host,
1.272     djm      1218:                                    sshkey_type(l->key), fp, l->comment);
                   1219:                                free(fp);
                   1220:                        } else
1.256     djm      1221:                                fprintf(ctx->out, "%s\n", l->line);
                   1222:                        return 0;
                   1223:                }
                   1224:        } else if (delete_host) {
                   1225:                /* Retain non-matching hosts when deleting */
                   1226:                if (l->status == HKF_STATUS_INVALID) {
                   1227:                        ctx->invalid = 1;
1.297     dtucker  1228:                        logit("%s:%lu: invalid line", l->path, l->linenum);
1.256     djm      1229:                }
                   1230:                fprintf(ctx->out, "%s\n", l->line);
1.166     djm      1231:        }
1.256     djm      1232:        return 0;
1.119     djm      1233: }
                   1234:
                   1235: static void
                   1236: do_known_hosts(struct passwd *pw, const char *name)
                   1237: {
1.258     deraadt  1238:        char *cp, tmp[PATH_MAX], old[PATH_MAX];
1.257     djm      1239:        int r, fd, oerrno, inplace = 0;
1.256     djm      1240:        struct known_hosts_ctx ctx;
1.272     djm      1241:        u_int foreach_options;
1.119     djm      1242:
                   1243:        if (!have_identity) {
                   1244:                cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
                   1245:                if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
                   1246:                    sizeof(identity_file))
                   1247:                        fatal("Specified known hosts path too long");
1.227     djm      1248:                free(cp);
1.119     djm      1249:                have_identity = 1;
                   1250:        }
                   1251:
1.256     djm      1252:        memset(&ctx, 0, sizeof(ctx));
                   1253:        ctx.out = stdout;
                   1254:        ctx.host = name;
                   1255:
1.119     djm      1256:        /*
                   1257:         * Find hosts goes to stdout, hash and deletions happen in-place
                   1258:         * A corner case is ssh-keygen -HF foo, which should go to stdout
                   1259:         */
                   1260:        if (!find_host && (hash_hosts || delete_host)) {
                   1261:                if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
                   1262:                    strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
                   1263:                    strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
                   1264:                    strlcat(old, ".old", sizeof(old)) >= sizeof(old))
                   1265:                        fatal("known_hosts path too long");
                   1266:                umask(077);
1.256     djm      1267:                if ((fd = mkstemp(tmp)) == -1)
1.119     djm      1268:                        fatal("mkstemp: %s", strerror(errno));
1.256     djm      1269:                if ((ctx.out = fdopen(fd, "w")) == NULL) {
                   1270:                        oerrno = errno;
1.119     djm      1271:                        unlink(tmp);
1.256     djm      1272:                        fatal("fdopen: %s", strerror(oerrno));
1.119     djm      1273:                }
1.257     djm      1274:                inplace = 1;
1.119     djm      1275:        }
1.256     djm      1276:        /* XXX support identity_file == "-" for stdin */
1.272     djm      1277:        foreach_options = find_host ? HKF_WANT_MATCH : 0;
                   1278:        foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1.316     djm      1279:        if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1.315     djm      1280:            known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
                   1281:            foreach_options)) != 0) {
1.284     deraadt  1282:                if (inplace)
                   1283:                        unlink(tmp);
1.256     djm      1284:                fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1.284     deraadt  1285:        }
1.119     djm      1286:
1.257     djm      1287:        if (inplace)
1.256     djm      1288:                fclose(ctx.out);
1.119     djm      1289:
1.256     djm      1290:        if (ctx.invalid) {
1.269     djm      1291:                error("%s is not a valid known_hosts file.", identity_file);
1.257     djm      1292:                if (inplace) {
1.269     djm      1293:                        error("Not replacing existing known_hosts "
                   1294:                            "file because of errors");
1.119     djm      1295:                        unlink(tmp);
                   1296:                }
                   1297:                exit(1);
1.256     djm      1298:        } else if (delete_host && !ctx.found_key) {
1.269     djm      1299:                logit("Host %s not found in %s", name, identity_file);
1.277     djm      1300:                if (inplace)
                   1301:                        unlink(tmp);
1.257     djm      1302:        } else if (inplace) {
1.119     djm      1303:                /* Backup existing file */
                   1304:                if (unlink(old) == -1 && errno != ENOENT)
                   1305:                        fatal("unlink %.100s: %s", old, strerror(errno));
                   1306:                if (link(identity_file, old) == -1)
                   1307:                        fatal("link %.100s to %.100s: %s", identity_file, old,
                   1308:                            strerror(errno));
                   1309:                /* Move new one into place */
                   1310:                if (rename(tmp, identity_file) == -1) {
                   1311:                        error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
                   1312:                            strerror(errno));
                   1313:                        unlink(tmp);
                   1314:                        unlink(old);
                   1315:                        exit(1);
                   1316:                }
                   1317:
1.269     djm      1318:                printf("%s updated.\n", identity_file);
                   1319:                printf("Original contents retained as %s\n", old);
1.256     djm      1320:                if (ctx.has_unhashed) {
1.269     djm      1321:                        logit("WARNING: %s contains unhashed entries", old);
                   1322:                        logit("Delete this file to ensure privacy "
                   1323:                            "of hostnames");
1.119     djm      1324:                }
                   1325:        }
                   1326:
1.256     djm      1327:        exit (find_host && !ctx.found_key);
1.119     djm      1328: }
                   1329:
1.13      deraadt  1330: /*
                   1331:  * Perform changing a passphrase.  The argument is the passwd structure
                   1332:  * for the current user.
                   1333:  */
1.63      itojun   1334: static void
1.7       markus   1335: do_change_passphrase(struct passwd *pw)
                   1336: {
1.12      markus   1337:        char *comment;
                   1338:        char *old_passphrase, *passphrase1, *passphrase2;
                   1339:        struct stat st;
1.252     djm      1340:        struct sshkey *private;
                   1341:        int r;
1.12      markus   1342:
                   1343:        if (!have_identity)
                   1344:                ask_filename(pw, "Enter file in which the key is");
1.269     djm      1345:        if (stat(identity_file, &st) < 0)
                   1346:                fatal("%s: %s", identity_file, strerror(errno));
1.12      markus   1347:        /* Try to load the file with empty passphrase. */
1.252     djm      1348:        r = sshkey_load_private(identity_file, "", &private, &comment);
                   1349:        if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1.12      markus   1350:                if (identity_passphrase)
                   1351:                        old_passphrase = xstrdup(identity_passphrase);
                   1352:                else
1.65      markus   1353:                        old_passphrase =
                   1354:                            read_passphrase("Enter old passphrase: ",
                   1355:                            RP_ALLOW_STDIN);
1.252     djm      1356:                r = sshkey_load_private(identity_file, old_passphrase,
                   1357:                    &private, &comment);
1.240     djm      1358:                explicit_bzero(old_passphrase, strlen(old_passphrase));
1.227     djm      1359:                free(old_passphrase);
1.252     djm      1360:                if (r != 0)
                   1361:                        goto badkey;
                   1362:        } else if (r != 0) {
                   1363:  badkey:
1.269     djm      1364:                fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1.12      markus   1365:        }
1.266     djm      1366:        if (comment)
1.294     djm      1367:                mprintf("Key has comment '%s'\n", comment);
1.12      markus   1368:
                   1369:        /* Ask the new passphrase (twice). */
                   1370:        if (identity_new_passphrase) {
                   1371:                passphrase1 = xstrdup(identity_new_passphrase);
                   1372:                passphrase2 = NULL;
                   1373:        } else {
                   1374:                passphrase1 =
1.65      markus   1375:                        read_passphrase("Enter new passphrase (empty for no "
                   1376:                            "passphrase): ", RP_ALLOW_STDIN);
                   1377:                passphrase2 = read_passphrase("Enter same passphrase again: ",
1.86      deraadt  1378:                    RP_ALLOW_STDIN);
1.12      markus   1379:
                   1380:                /* Verify that they are the same. */
                   1381:                if (strcmp(passphrase1, passphrase2) != 0) {
1.240     djm      1382:                        explicit_bzero(passphrase1, strlen(passphrase1));
                   1383:                        explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      1384:                        free(passphrase1);
                   1385:                        free(passphrase2);
1.12      markus   1386:                        printf("Pass phrases do not match.  Try again.\n");
                   1387:                        exit(1);
                   1388:                }
                   1389:                /* Destroy the other copy. */
1.240     djm      1390:                explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      1391:                free(passphrase2);
1.12      markus   1392:        }
                   1393:
                   1394:        /* Save the file using the new passphrase. */
1.252     djm      1395:        if ((r = sshkey_save_private(private, identity_file, passphrase1,
                   1396:            comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      1397:                error("Saving key \"%s\" failed: %s.",
1.252     djm      1398:                    identity_file, ssh_err(r));
1.240     djm      1399:                explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      1400:                free(passphrase1);
1.252     djm      1401:                sshkey_free(private);
1.227     djm      1402:                free(comment);
1.12      markus   1403:                exit(1);
                   1404:        }
                   1405:        /* Destroy the passphrase and the copy of the key in memory. */
1.240     djm      1406:        explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      1407:        free(passphrase1);
1.252     djm      1408:        sshkey_free(private);            /* Destroys contents */
1.227     djm      1409:        free(comment);
1.1       deraadt  1410:
1.12      markus   1411:        printf("Your identification has been saved with the new passphrase.\n");
                   1412:        exit(0);
1.1       deraadt  1413: }
                   1414:
1.105     jakob    1415: /*
                   1416:  * Print the SSHFP RR.
                   1417:  */
1.138     jakob    1418: static int
                   1419: do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1.105     jakob    1420: {
1.252     djm      1421:        struct sshkey *public;
1.105     jakob    1422:        char *comment = NULL;
                   1423:        struct stat st;
1.252     djm      1424:        int r;
1.105     jakob    1425:
1.138     jakob    1426:        if (fname == NULL)
1.229     djm      1427:                fatal("%s: no filename", __func__);
1.138     jakob    1428:        if (stat(fname, &st) < 0) {
                   1429:                if (errno == ENOENT)
                   1430:                        return 0;
1.269     djm      1431:                fatal("%s: %s", fname, strerror(errno));
1.105     jakob    1432:        }
1.269     djm      1433:        if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
                   1434:                fatal("Failed to read v2 public key from \"%s\": %s.",
1.252     djm      1435:                    fname, ssh_err(r));
                   1436:        export_dns_rr(hname, public, stdout, print_generic);
                   1437:        sshkey_free(public);
                   1438:        free(comment);
                   1439:        return 1;
1.105     jakob    1440: }
                   1441:
1.13      deraadt  1442: /*
                   1443:  * Change the comment of a private key file.
                   1444:  */
1.63      itojun   1445: static void
1.2       provos   1446: do_change_comment(struct passwd *pw)
1.1       deraadt  1447: {
1.46      deraadt  1448:        char new_comment[1024], *comment, *passphrase;
1.252     djm      1449:        struct sshkey *private;
                   1450:        struct sshkey *public;
1.12      markus   1451:        struct stat st;
                   1452:        FILE *f;
1.252     djm      1453:        int r, fd;
1.12      markus   1454:
                   1455:        if (!have_identity)
                   1456:                ask_filename(pw, "Enter file in which the key is");
1.269     djm      1457:        if (stat(identity_file, &st) < 0)
                   1458:                fatal("%s: %s", identity_file, strerror(errno));
1.252     djm      1459:        if ((r = sshkey_load_private(identity_file, "",
                   1460:            &private, &comment)) == 0)
                   1461:                passphrase = xstrdup("");
1.269     djm      1462:        else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
                   1463:                fatal("Cannot load private key \"%s\": %s.",
1.252     djm      1464:                    identity_file, ssh_err(r));
1.269     djm      1465:        else {
1.12      markus   1466:                if (identity_passphrase)
                   1467:                        passphrase = xstrdup(identity_passphrase);
                   1468:                else if (identity_new_passphrase)
                   1469:                        passphrase = xstrdup(identity_new_passphrase);
                   1470:                else
1.65      markus   1471:                        passphrase = read_passphrase("Enter passphrase: ",
                   1472:                            RP_ALLOW_STDIN);
1.12      markus   1473:                /* Try to load using the passphrase. */
1.252     djm      1474:                if ((r = sshkey_load_private(identity_file, passphrase,
                   1475:                    &private, &comment)) != 0) {
1.240     djm      1476:                        explicit_bzero(passphrase, strlen(passphrase));
1.227     djm      1477:                        free(passphrase);
1.269     djm      1478:                        fatal("Cannot load private key \"%s\": %s.",
1.252     djm      1479:                            identity_file, ssh_err(r));
1.12      markus   1480:                }
                   1481:        }
1.283     halex    1482:
1.313     markus   1483:        if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
                   1484:            !use_new_format) {
1.302     djm      1485:                error("Comments are only supported for keys stored in "
1.283     halex    1486:                    "the new format (-o).");
1.268     tobias   1487:                explicit_bzero(passphrase, strlen(passphrase));
1.252     djm      1488:                sshkey_free(private);
1.52      markus   1489:                exit(1);
1.86      deraadt  1490:        }
1.293     millert  1491:        if (comment)
                   1492:                printf("Key now has comment '%s'\n", comment);
                   1493:        else
                   1494:                printf("Key now has no comment\n");
1.12      markus   1495:
                   1496:        if (identity_comment) {
                   1497:                strlcpy(new_comment, identity_comment, sizeof(new_comment));
                   1498:        } else {
                   1499:                printf("Enter new comment: ");
                   1500:                fflush(stdout);
                   1501:                if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1.240     djm      1502:                        explicit_bzero(passphrase, strlen(passphrase));
1.252     djm      1503:                        sshkey_free(private);
1.12      markus   1504:                        exit(1);
                   1505:                }
1.162     gilles   1506:                new_comment[strcspn(new_comment, "\n")] = '\0';
1.12      markus   1507:        }
                   1508:
                   1509:        /* Save the file using the new passphrase. */
1.252     djm      1510:        if ((r = sshkey_save_private(private, identity_file, passphrase,
                   1511:            new_comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      1512:                error("Saving key \"%s\" failed: %s",
1.252     djm      1513:                    identity_file, ssh_err(r));
1.240     djm      1514:                explicit_bzero(passphrase, strlen(passphrase));
1.227     djm      1515:                free(passphrase);
1.252     djm      1516:                sshkey_free(private);
1.227     djm      1517:                free(comment);
1.12      markus   1518:                exit(1);
                   1519:        }
1.240     djm      1520:        explicit_bzero(passphrase, strlen(passphrase));
1.227     djm      1521:        free(passphrase);
1.252     djm      1522:        if ((r = sshkey_from_private(private, &public)) != 0)
1.304     markus   1523:                fatal("sshkey_from_private failed: %s", ssh_err(r));
1.252     djm      1524:        sshkey_free(private);
1.12      markus   1525:
                   1526:        strlcat(identity_file, ".pub", sizeof(identity_file));
1.46      deraadt  1527:        fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1.269     djm      1528:        if (fd == -1)
                   1529:                fatal("Could not save your public key in %s", identity_file);
1.46      deraadt  1530:        f = fdopen(fd, "w");
1.269     djm      1531:        if (f == NULL)
                   1532:                fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1.252     djm      1533:        if ((r = sshkey_write(public, f)) != 0)
1.269     djm      1534:                fatal("write key failed: %s", ssh_err(r));
1.252     djm      1535:        sshkey_free(public);
1.19      markus   1536:        fprintf(f, " %s\n", new_comment);
1.12      markus   1537:        fclose(f);
1.1       deraadt  1538:
1.227     djm      1539:        free(comment);
1.1       deraadt  1540:
1.12      markus   1541:        printf("The comment in your key file has been changed.\n");
                   1542:        exit(0);
1.1       deraadt  1543: }
                   1544:
1.179     djm      1545: static void
1.252     djm      1546: add_flag_option(struct sshbuf *c, const char *name)
1.179     djm      1547: {
1.252     djm      1548:        int r;
                   1549:
1.179     djm      1550:        debug3("%s: %s", __func__, name);
1.252     djm      1551:        if ((r = sshbuf_put_cstring(c, name)) != 0 ||
                   1552:            (r = sshbuf_put_string(c, NULL, 0)) != 0)
                   1553:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.179     djm      1554: }
                   1555:
                   1556: static void
1.252     djm      1557: add_string_option(struct sshbuf *c, const char *name, const char *value)
1.179     djm      1558: {
1.252     djm      1559:        struct sshbuf *b;
                   1560:        int r;
1.179     djm      1561:
                   1562:        debug3("%s: %s=%s", __func__, name, value);
1.252     djm      1563:        if ((b = sshbuf_new()) == NULL)
                   1564:                fatal("%s: sshbuf_new failed", __func__);
                   1565:        if ((r = sshbuf_put_cstring(b, value)) != 0 ||
                   1566:            (r = sshbuf_put_cstring(c, name)) != 0 ||
                   1567:            (r = sshbuf_put_stringb(c, b)) != 0)
                   1568:                fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.179     djm      1569:
1.252     djm      1570:        sshbuf_free(b);
1.179     djm      1571: }
                   1572:
1.190     djm      1573: #define OPTIONS_CRITICAL       1
                   1574: #define OPTIONS_EXTENSIONS     2
1.179     djm      1575: static void
1.252     djm      1576: prepare_options_buf(struct sshbuf *c, int which)
1.179     djm      1577: {
1.300     djm      1578:        size_t i;
                   1579:
1.252     djm      1580:        sshbuf_reset(c);
1.196     djm      1581:        if ((which & OPTIONS_CRITICAL) != 0 &&
                   1582:            certflags_command != NULL)
                   1583:                add_string_option(c, "force-command", certflags_command);
1.190     djm      1584:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
1.210     djm      1585:            (certflags_flags & CERTOPT_X_FWD) != 0)
                   1586:                add_flag_option(c, "permit-X11-forwarding");
                   1587:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
1.190     djm      1588:            (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1.186     djm      1589:                add_flag_option(c, "permit-agent-forwarding");
1.190     djm      1590:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
                   1591:            (certflags_flags & CERTOPT_PORT_FWD) != 0)
1.186     djm      1592:                add_flag_option(c, "permit-port-forwarding");
1.190     djm      1593:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
                   1594:            (certflags_flags & CERTOPT_PTY) != 0)
1.186     djm      1595:                add_flag_option(c, "permit-pty");
1.190     djm      1596:        if ((which & OPTIONS_EXTENSIONS) != 0 &&
                   1597:            (certflags_flags & CERTOPT_USER_RC) != 0)
1.186     djm      1598:                add_flag_option(c, "permit-user-rc");
1.190     djm      1599:        if ((which & OPTIONS_CRITICAL) != 0 &&
                   1600:            certflags_src_addr != NULL)
                   1601:                add_string_option(c, "source-address", certflags_src_addr);
1.300     djm      1602:        for (i = 0; i < ncert_userext; i++) {
                   1603:                if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
                   1604:                    (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
                   1605:                        continue;
                   1606:                if (cert_userext[i].val == NULL)
                   1607:                        add_flag_option(c, cert_userext[i].key);
                   1608:                else {
                   1609:                        add_string_option(c, cert_userext[i].key,
                   1610:                            cert_userext[i].val);
                   1611:                }
                   1612:        }
1.179     djm      1613: }
                   1614:
1.252     djm      1615: static struct sshkey *
1.197     djm      1616: load_pkcs11_key(char *path)
                   1617: {
                   1618: #ifdef ENABLE_PKCS11
1.252     djm      1619:        struct sshkey **keys = NULL, *public, *private = NULL;
                   1620:        int r, i, nkeys;
1.197     djm      1621:
1.252     djm      1622:        if ((r = sshkey_load_public(path, &public, NULL)) != 0)
                   1623:                fatal("Couldn't load CA public key \"%s\": %s",
                   1624:                    path, ssh_err(r));
1.197     djm      1625:
                   1626:        nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
                   1627:        debug3("%s: %d keys", __func__, nkeys);
                   1628:        if (nkeys <= 0)
                   1629:                fatal("cannot read public key from pkcs11");
                   1630:        for (i = 0; i < nkeys; i++) {
1.252     djm      1631:                if (sshkey_equal_public(public, keys[i])) {
1.197     djm      1632:                        private = keys[i];
                   1633:                        continue;
                   1634:                }
1.252     djm      1635:                sshkey_free(keys[i]);
1.197     djm      1636:        }
1.227     djm      1637:        free(keys);
1.252     djm      1638:        sshkey_free(public);
1.197     djm      1639:        return private;
                   1640: #else
                   1641:        fatal("no pkcs11 support");
                   1642: #endif /* ENABLE_PKCS11 */
                   1643: }
                   1644:
1.305     djm      1645: /* Signer for sshkey_certify_custom that uses the agent */
                   1646: static int
                   1647: agent_signer(const struct sshkey *key, u_char **sigp, size_t *lenp,
                   1648:     const u_char *data, size_t datalen,
                   1649:     const char *alg, u_int compat, void *ctx)
                   1650: {
                   1651:        int *agent_fdp = (int *)ctx;
                   1652:
                   1653:        return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
                   1654:            data, datalen, alg, compat);
                   1655: }
                   1656:
1.179     djm      1657: static void
                   1658: do_ca_sign(struct passwd *pw, int argc, char **argv)
                   1659: {
1.305     djm      1660:        int r, i, fd, found, agent_fd = -1;
1.179     djm      1661:        u_int n;
1.252     djm      1662:        struct sshkey *ca, *public;
1.281     djm      1663:        char valid[64], *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1.179     djm      1664:        FILE *f;
1.305     djm      1665:        struct ssh_identitylist *agent_ids;
                   1666:        size_t j;
1.186     djm      1667:
1.246     markus   1668: #ifdef ENABLE_PKCS11
1.197     djm      1669:        pkcs11_init(1);
1.246     markus   1670: #endif
1.197     djm      1671:        tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
                   1672:        if (pkcs11provider != NULL) {
1.305     djm      1673:                /* If a PKCS#11 token was specified then try to use it */
1.197     djm      1674:                if ((ca = load_pkcs11_key(tmp)) == NULL)
                   1675:                        fatal("No PKCS#11 key matching %s found", ca_key_path);
1.305     djm      1676:        } else if (prefer_agent) {
                   1677:                /*
                   1678:                 * Agent signature requested. Try to use agent after making
                   1679:                 * sure the public key specified is actually present in the
                   1680:                 * agent.
                   1681:                 */
                   1682:                if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
                   1683:                        fatal("Cannot load CA public key %s: %s",
                   1684:                            tmp, ssh_err(r));
                   1685:                if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
                   1686:                        fatal("Cannot use public key for CA signature: %s",
                   1687:                            ssh_err(r));
                   1688:                if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
                   1689:                        fatal("Retrieve agent key list: %s", ssh_err(r));
                   1690:                found = 0;
                   1691:                for (j = 0; j < agent_ids->nkeys; j++) {
                   1692:                        if (sshkey_equal(ca, agent_ids->keys[j])) {
                   1693:                                found = 1;
                   1694:                                break;
                   1695:                        }
                   1696:                }
                   1697:                if (!found)
                   1698:                        fatal("CA key %s not found in agent", tmp);
                   1699:                ssh_free_identitylist(agent_ids);
                   1700:                ca->flags |= SSHKEY_FLAG_EXT;
                   1701:        } else {
                   1702:                /* CA key is assumed to be a private key on the filesystem */
1.252     djm      1703:                ca = load_identity(tmp);
1.305     djm      1704:        }
1.227     djm      1705:        free(tmp);
1.197     djm      1706:
1.290     djm      1707:        if (key_type_name != NULL &&
                   1708:            sshkey_type_from_name(key_type_name) != ca->type)  {
                   1709:                fatal("CA key type %s doesn't match specified %s",
                   1710:                    sshkey_ssh_name(ca), key_type_name);
                   1711:        }
                   1712:
1.179     djm      1713:        for (i = 0; i < argc; i++) {
                   1714:                /* Split list of principals */
                   1715:                n = 0;
                   1716:                if (cert_principals != NULL) {
                   1717:                        otmp = tmp = xstrdup(cert_principals);
                   1718:                        plist = NULL;
                   1719:                        for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1.270     deraadt  1720:                                plist = xreallocarray(plist, n + 1, sizeof(*plist));
1.179     djm      1721:                                if (*(plist[n] = xstrdup(cp)) == '\0')
                   1722:                                        fatal("Empty principal name");
                   1723:                        }
1.227     djm      1724:                        free(otmp);
1.179     djm      1725:                }
1.312     djm      1726:                if (n > SSHKEY_CERT_MAX_PRINCIPALS)
                   1727:                        fatal("Too many certificate principals specified");
1.179     djm      1728:
                   1729:                tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1.252     djm      1730:                if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
                   1731:                        fatal("%s: unable to open \"%s\": %s",
                   1732:                            __func__, tmp, ssh_err(r));
1.200     djm      1733:                if (public->type != KEY_RSA && public->type != KEY_DSA &&
1.313     markus   1734:                    public->type != KEY_ECDSA && public->type != KEY_ED25519 &&
                   1735:                    public->type != KEY_XMSS)
1.179     djm      1736:                        fatal("%s: key \"%s\" type %s cannot be certified",
1.252     djm      1737:                            __func__, tmp, sshkey_type(public));
1.179     djm      1738:
                   1739:                /* Prepare certificate to sign */
1.275     djm      1740:                if ((r = sshkey_to_certified(public)) != 0)
1.252     djm      1741:                        fatal("Could not upgrade key %s to certificate: %s",
                   1742:                            tmp, ssh_err(r));
1.179     djm      1743:                public->cert->type = cert_key_type;
1.186     djm      1744:                public->cert->serial = (u_int64_t)cert_serial;
1.179     djm      1745:                public->cert->key_id = xstrdup(cert_key_id);
                   1746:                public->cert->nprincipals = n;
                   1747:                public->cert->principals = plist;
                   1748:                public->cert->valid_after = cert_valid_from;
                   1749:                public->cert->valid_before = cert_valid_to;
1.275     djm      1750:                prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
                   1751:                prepare_options_buf(public->cert->extensions,
                   1752:                    OPTIONS_EXTENSIONS);
1.252     djm      1753:                if ((r = sshkey_from_private(ca,
                   1754:                    &public->cert->signature_key)) != 0)
1.304     markus   1755:                        fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1.179     djm      1756:
1.305     djm      1757:                if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
                   1758:                        if ((r = sshkey_certify_custom(public, ca,
                   1759:                            key_type_name, agent_signer, &agent_fd)) != 0)
                   1760:                                fatal("Couldn't certify key %s via agent: %s",
                   1761:                                    tmp, ssh_err(r));
                   1762:                } else {
                   1763:                        if ((sshkey_certify(public, ca, key_type_name)) != 0)
                   1764:                                fatal("Couldn't certify key %s: %s",
                   1765:                                    tmp, ssh_err(r));
                   1766:                }
1.179     djm      1767:
                   1768:                if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
                   1769:                        *cp = '\0';
                   1770:                xasprintf(&out, "%s-cert.pub", tmp);
1.227     djm      1771:                free(tmp);
1.179     djm      1772:
                   1773:                if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
                   1774:                        fatal("Could not open \"%s\" for writing: %s", out,
                   1775:                            strerror(errno));
                   1776:                if ((f = fdopen(fd, "w")) == NULL)
                   1777:                        fatal("%s: fdopen: %s", __func__, strerror(errno));
1.252     djm      1778:                if ((r = sshkey_write(public, f)) != 0)
                   1779:                        fatal("Could not write certified key to %s: %s",
                   1780:                            out, ssh_err(r));
1.179     djm      1781:                fprintf(f, " %s\n", comment);
                   1782:                fclose(f);
                   1783:
1.186     djm      1784:                if (!quiet) {
1.282     djm      1785:                        sshkey_format_cert_validity(public->cert,
1.281     djm      1786:                            valid, sizeof(valid));
1.186     djm      1787:                        logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1.282     djm      1788:                            "valid %s", sshkey_cert_type(public),
1.205     djm      1789:                            out, public->cert->key_id,
                   1790:                            (unsigned long long)public->cert->serial,
1.179     djm      1791:                            cert_principals != NULL ? " for " : "",
                   1792:                            cert_principals != NULL ? cert_principals : "",
1.281     djm      1793:                            valid);
1.186     djm      1794:                }
1.179     djm      1795:
1.252     djm      1796:                sshkey_free(public);
1.227     djm      1797:                free(out);
1.179     djm      1798:        }
1.246     markus   1799: #ifdef ENABLE_PKCS11
1.197     djm      1800:        pkcs11_terminate();
1.246     markus   1801: #endif
1.179     djm      1802:        exit(0);
                   1803: }
                   1804:
                   1805: static u_int64_t
                   1806: parse_relative_time(const char *s, time_t now)
                   1807: {
                   1808:        int64_t mul, secs;
                   1809:
                   1810:        mul = *s == '-' ? -1 : 1;
                   1811:
                   1812:        if ((secs = convtime(s + 1)) == -1)
                   1813:                fatal("Invalid relative certificate time %s", s);
                   1814:        if (mul == -1 && secs > now)
                   1815:                fatal("Certificate time %s cannot be represented", s);
                   1816:        return now + (u_int64_t)(secs * mul);
                   1817: }
                   1818:
                   1819: static void
                   1820: parse_cert_times(char *timespec)
                   1821: {
                   1822:        char *from, *to;
                   1823:        time_t now = time(NULL);
                   1824:        int64_t secs;
                   1825:
                   1826:        /* +timespec relative to now */
                   1827:        if (*timespec == '+' && strchr(timespec, ':') == NULL) {
                   1828:                if ((secs = convtime(timespec + 1)) == -1)
                   1829:                        fatal("Invalid relative certificate life %s", timespec);
                   1830:                cert_valid_to = now + secs;
                   1831:                /*
                   1832:                 * Backdate certificate one minute to avoid problems on hosts
                   1833:                 * with poorly-synchronised clocks.
                   1834:                 */
                   1835:                cert_valid_from = ((now - 59)/ 60) * 60;
                   1836:                return;
                   1837:        }
                   1838:
                   1839:        /*
                   1840:         * from:to, where
1.308     djm      1841:         * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
                   1842:         *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1.179     djm      1843:         */
                   1844:        from = xstrdup(timespec);
                   1845:        to = strchr(from, ':');
                   1846:        if (to == NULL || from == to || *(to + 1) == '\0')
1.181     djm      1847:                fatal("Invalid certificate life specification %s", timespec);
1.179     djm      1848:        *to++ = '\0';
                   1849:
                   1850:        if (*from == '-' || *from == '+')
                   1851:                cert_valid_from = parse_relative_time(from, now);
1.308     djm      1852:        else if (strcmp(from, "always") == 0)
                   1853:                cert_valid_from = 0;
1.314     djm      1854:        else if (parse_absolute_time(from, &cert_valid_from) != 0)
                   1855:                fatal("Invalid from time \"%s\"", from);
1.179     djm      1856:
                   1857:        if (*to == '-' || *to == '+')
1.235     djm      1858:                cert_valid_to = parse_relative_time(to, now);
1.308     djm      1859:        else if (strcmp(to, "forever") == 0)
                   1860:                cert_valid_to = ~(u_int64_t)0;
1.314     djm      1861:        else if (parse_absolute_time(to, &cert_valid_to) != 0)
                   1862:                fatal("Invalid to time \"%s\"", to);
1.179     djm      1863:
                   1864:        if (cert_valid_to <= cert_valid_from)
                   1865:                fatal("Empty certificate validity interval");
1.227     djm      1866:        free(from);
1.179     djm      1867: }
                   1868:
                   1869: static void
1.186     djm      1870: add_cert_option(char *opt)
1.179     djm      1871: {
1.300     djm      1872:        char *val, *cp;
                   1873:        int iscrit = 0;
1.179     djm      1874:
1.208     stevesk  1875:        if (strcasecmp(opt, "clear") == 0)
1.190     djm      1876:                certflags_flags = 0;
1.179     djm      1877:        else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1.190     djm      1878:                certflags_flags &= ~CERTOPT_X_FWD;
1.179     djm      1879:        else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1.190     djm      1880:                certflags_flags |= CERTOPT_X_FWD;
1.179     djm      1881:        else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1.190     djm      1882:                certflags_flags &= ~CERTOPT_AGENT_FWD;
1.179     djm      1883:        else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1.190     djm      1884:                certflags_flags |= CERTOPT_AGENT_FWD;
1.179     djm      1885:        else if (strcasecmp(opt, "no-port-forwarding") == 0)
1.190     djm      1886:                certflags_flags &= ~CERTOPT_PORT_FWD;
1.179     djm      1887:        else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1.190     djm      1888:                certflags_flags |= CERTOPT_PORT_FWD;
1.179     djm      1889:        else if (strcasecmp(opt, "no-pty") == 0)
1.190     djm      1890:                certflags_flags &= ~CERTOPT_PTY;
1.179     djm      1891:        else if (strcasecmp(opt, "permit-pty") == 0)
1.190     djm      1892:                certflags_flags |= CERTOPT_PTY;
1.179     djm      1893:        else if (strcasecmp(opt, "no-user-rc") == 0)
1.190     djm      1894:                certflags_flags &= ~CERTOPT_USER_RC;
1.179     djm      1895:        else if (strcasecmp(opt, "permit-user-rc") == 0)
1.190     djm      1896:                certflags_flags |= CERTOPT_USER_RC;
1.179     djm      1897:        else if (strncasecmp(opt, "force-command=", 14) == 0) {
                   1898:                val = opt + 14;
                   1899:                if (*val == '\0')
1.186     djm      1900:                        fatal("Empty force-command option");
1.190     djm      1901:                if (certflags_command != NULL)
1.179     djm      1902:                        fatal("force-command already specified");
1.190     djm      1903:                certflags_command = xstrdup(val);
1.179     djm      1904:        } else if (strncasecmp(opt, "source-address=", 15) == 0) {
                   1905:                val = opt + 15;
                   1906:                if (*val == '\0')
1.186     djm      1907:                        fatal("Empty source-address option");
1.190     djm      1908:                if (certflags_src_addr != NULL)
1.179     djm      1909:                        fatal("source-address already specified");
                   1910:                if (addr_match_cidr_list(NULL, val) != 0)
                   1911:                        fatal("Invalid source-address list");
1.190     djm      1912:                certflags_src_addr = xstrdup(val);
1.300     djm      1913:        } else if (strncasecmp(opt, "extension:", 10) == 0 ||
                   1914:                   (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
                   1915:                val = xstrdup(strchr(opt, ':') + 1);
                   1916:                if ((cp = strchr(val, '=')) != NULL)
                   1917:                        *cp++ = '\0';
                   1918:                cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
                   1919:                    sizeof(*cert_userext));
                   1920:                cert_userext[ncert_userext].key = val;
                   1921:                cert_userext[ncert_userext].val = cp == NULL ?
                   1922:                    NULL : xstrdup(cp);
                   1923:                cert_userext[ncert_userext].crit = iscrit;
                   1924:                ncert_userext++;
1.179     djm      1925:        } else
1.186     djm      1926:                fatal("Unsupported certificate option \"%s\"", opt);
1.179     djm      1927: }
                   1928:
1.63      itojun   1929: static void
1.275     djm      1930: show_options(struct sshbuf *optbuf, int in_critical)
1.192     djm      1931: {
1.245     djm      1932:        char *name, *arg;
1.252     djm      1933:        struct sshbuf *options, *option = NULL;
                   1934:        int r;
                   1935:
                   1936:        if ((options = sshbuf_fromb(optbuf)) == NULL)
                   1937:                fatal("%s: sshbuf_fromb failed", __func__);
                   1938:        while (sshbuf_len(options) != 0) {
                   1939:                sshbuf_free(option);
                   1940:                option = NULL;
                   1941:                if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
                   1942:                    (r = sshbuf_froms(options, &option)) != 0)
                   1943:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.192     djm      1944:                printf("                %s", name);
1.275     djm      1945:                if (!in_critical &&
1.192     djm      1946:                    (strcmp(name, "permit-X11-forwarding") == 0 ||
                   1947:                    strcmp(name, "permit-agent-forwarding") == 0 ||
                   1948:                    strcmp(name, "permit-port-forwarding") == 0 ||
                   1949:                    strcmp(name, "permit-pty") == 0 ||
                   1950:                    strcmp(name, "permit-user-rc") == 0))
                   1951:                        printf("\n");
1.275     djm      1952:                else if (in_critical &&
1.192     djm      1953:                    (strcmp(name, "force-command") == 0 ||
                   1954:                    strcmp(name, "source-address") == 0)) {
1.252     djm      1955:                        if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
                   1956:                                fatal("%s: buffer error: %s",
                   1957:                                    __func__, ssh_err(r));
1.245     djm      1958:                        printf(" %s\n", arg);
                   1959:                        free(arg);
1.192     djm      1960:                } else {
1.252     djm      1961:                        printf(" UNKNOWN OPTION (len %zu)\n",
                   1962:                            sshbuf_len(option));
                   1963:                        sshbuf_reset(option);
1.192     djm      1964:                }
1.227     djm      1965:                free(name);
1.252     djm      1966:                if (sshbuf_len(option) != 0)
1.192     djm      1967:                        fatal("Option corrupt: extra data at end");
                   1968:        }
1.252     djm      1969:        sshbuf_free(option);
                   1970:        sshbuf_free(options);
1.192     djm      1971: }
                   1972:
                   1973: static void
1.278     djm      1974: print_cert(struct sshkey *key)
1.182     djm      1975: {
1.281     djm      1976:        char valid[64], *key_fp, *ca_fp;
1.275     djm      1977:        u_int i;
1.186     djm      1978:
1.252     djm      1979:        key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
                   1980:        ca_fp = sshkey_fingerprint(key->cert->signature_key,
1.251     djm      1981:            fingerprint_hash, SSH_FP_DEFAULT);
1.259     djm      1982:        if (key_fp == NULL || ca_fp == NULL)
                   1983:                fatal("%s: sshkey_fingerprint fail", __func__);
1.281     djm      1984:        sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
1.182     djm      1985:
1.252     djm      1986:        printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
                   1987:            sshkey_cert_type(key));
                   1988:        printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
1.186     djm      1989:        printf("        Signing CA: %s %s\n",
1.252     djm      1990:            sshkey_type(key->cert->signature_key), ca_fp);
1.186     djm      1991:        printf("        Key ID: \"%s\"\n", key->cert->key_id);
1.275     djm      1992:        printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
1.281     djm      1993:        printf("        Valid: %s\n", valid);
1.182     djm      1994:        printf("        Principals: ");
                   1995:        if (key->cert->nprincipals == 0)
                   1996:                printf("(none)\n");
                   1997:        else {
                   1998:                for (i = 0; i < key->cert->nprincipals; i++)
                   1999:                        printf("\n                %s",
                   2000:                            key->cert->principals[i]);
                   2001:                printf("\n");
                   2002:        }
1.186     djm      2003:        printf("        Critical Options: ");
1.252     djm      2004:        if (sshbuf_len(key->cert->critical) == 0)
1.182     djm      2005:                printf("(none)\n");
                   2006:        else {
                   2007:                printf("\n");
1.275     djm      2008:                show_options(key->cert->critical, 1);
1.186     djm      2009:        }
1.275     djm      2010:        printf("        Extensions: ");
                   2011:        if (sshbuf_len(key->cert->extensions) == 0)
                   2012:                printf("(none)\n");
                   2013:        else {
                   2014:                printf("\n");
                   2015:                show_options(key->cert->extensions, 0);
1.182     djm      2016:        }
1.278     djm      2017: }
                   2018:
                   2019: static void
                   2020: do_show_cert(struct passwd *pw)
                   2021: {
                   2022:        struct sshkey *key = NULL;
                   2023:        struct stat st;
                   2024:        int r, is_stdin = 0, ok = 0;
                   2025:        FILE *f;
1.317     markus   2026:        char *cp, *line = NULL;
1.278     djm      2027:        const char *path;
1.317     markus   2028:        size_t linesize = 0;
1.289     djm      2029:        u_long lnum = 0;
1.278     djm      2030:
                   2031:        if (!have_identity)
                   2032:                ask_filename(pw, "Enter file in which the key is");
                   2033:        if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) < 0)
                   2034:                fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
                   2035:
                   2036:        path = identity_file;
                   2037:        if (strcmp(path, "-") == 0) {
                   2038:                f = stdin;
                   2039:                path = "(stdin)";
                   2040:                is_stdin = 1;
                   2041:        } else if ((f = fopen(identity_file, "r")) == NULL)
                   2042:                fatal("fopen %s: %s", identity_file, strerror(errno));
                   2043:
1.317     markus   2044:        while (getline(&line, &linesize, f) != -1) {
                   2045:                lnum++;
1.278     djm      2046:                sshkey_free(key);
                   2047:                key = NULL;
                   2048:                /* Trim leading space and comments */
                   2049:                cp = line + strspn(line, " \t");
                   2050:                if (*cp == '#' || *cp == '\0')
                   2051:                        continue;
                   2052:                if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
1.304     markus   2053:                        fatal("sshkey_new");
1.278     djm      2054:                if ((r = sshkey_read(key, &cp)) != 0) {
                   2055:                        error("%s:%lu: invalid key: %s", path,
                   2056:                            lnum, ssh_err(r));
                   2057:                        continue;
                   2058:                }
                   2059:                if (!sshkey_is_cert(key)) {
                   2060:                        error("%s:%lu is not a certificate", path, lnum);
                   2061:                        continue;
                   2062:                }
                   2063:                ok = 1;
                   2064:                if (!is_stdin && lnum == 1)
                   2065:                        printf("%s:\n", path);
                   2066:                else
                   2067:                        printf("%s:%lu:\n", path, lnum);
                   2068:                print_cert(key);
                   2069:        }
1.317     markus   2070:        free(line);
1.278     djm      2071:        sshkey_free(key);
                   2072:        fclose(f);
                   2073:        exit(ok ? 0 : 1);
1.182     djm      2074: }
                   2075:
1.246     markus   2076: #ifdef WITH_OPENSSL
1.182     djm      2077: static void
1.223     djm      2078: load_krl(const char *path, struct ssh_krl **krlp)
                   2079: {
1.252     djm      2080:        struct sshbuf *krlbuf;
                   2081:        int r, fd;
1.223     djm      2082:
1.252     djm      2083:        if ((krlbuf = sshbuf_new()) == NULL)
                   2084:                fatal("sshbuf_new failed");
1.223     djm      2085:        if ((fd = open(path, O_RDONLY)) == -1)
                   2086:                fatal("open %s: %s", path, strerror(errno));
1.252     djm      2087:        if ((r = sshkey_load_file(fd, krlbuf)) != 0)
                   2088:                fatal("Unable to load KRL: %s", ssh_err(r));
1.223     djm      2089:        close(fd);
                   2090:        /* XXX check sigs */
1.252     djm      2091:        if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
1.223     djm      2092:            *krlp == NULL)
1.252     djm      2093:                fatal("Invalid KRL file: %s", ssh_err(r));
                   2094:        sshbuf_free(krlbuf);
1.223     djm      2095: }
                   2096:
                   2097: static void
1.320     djm      2098: hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
                   2099:     const char *file, u_long lnum)
                   2100: {
                   2101:        char *tmp;
                   2102:        size_t tlen;
                   2103:        struct sshbuf *b;
                   2104:        int r;
                   2105:
                   2106:        if (strncmp(cp, "SHA256:", 7) != 0)
                   2107:                fatal("%s:%lu: unsupported hash algorithm", file, lnum);
                   2108:        cp += 7;
                   2109:
                   2110:        /*
                   2111:         * OpenSSH base64 hashes omit trailing '='
                   2112:         * characters; put them back for decode.
                   2113:         */
                   2114:        tlen = strlen(cp);
                   2115:        tmp = xmalloc(tlen + 4 + 1);
                   2116:        strlcpy(tmp, cp, tlen + 1);
                   2117:        while ((tlen % 4) != 0) {
                   2118:                tmp[tlen++] = '=';
                   2119:                tmp[tlen] = '\0';
                   2120:        }
                   2121:        if ((b = sshbuf_new()) == NULL)
                   2122:                fatal("%s: sshbuf_new failed", __func__);
                   2123:        if ((r = sshbuf_b64tod(b, tmp)) != 0)
                   2124:                fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
                   2125:        free(tmp);
                   2126:        *lenp = sshbuf_len(b);
                   2127:        *blobp = xmalloc(*lenp);
                   2128:        memcpy(*blobp, sshbuf_ptr(b), *lenp);
                   2129:        sshbuf_free(b);
                   2130: }
                   2131:
                   2132: static void
1.261     djm      2133: update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
1.252     djm      2134:     const struct sshkey *ca, struct ssh_krl *krl)
1.223     djm      2135: {
1.252     djm      2136:        struct sshkey *key = NULL;
1.223     djm      2137:        u_long lnum = 0;
1.317     markus   2138:        char *path, *cp, *ep, *line = NULL;
1.320     djm      2139:        u_char *blob = NULL;
                   2140:        size_t blen = 0, linesize = 0;
1.223     djm      2141:        unsigned long long serial, serial2;
1.320     djm      2142:        int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
1.223     djm      2143:        FILE *krl_spec;
                   2144:
                   2145:        path = tilde_expand_filename(file, pw->pw_uid);
                   2146:        if (strcmp(path, "-") == 0) {
                   2147:                krl_spec = stdin;
                   2148:                free(path);
                   2149:                path = xstrdup("(standard input)");
                   2150:        } else if ((krl_spec = fopen(path, "r")) == NULL)
                   2151:                fatal("fopen %s: %s", path, strerror(errno));
                   2152:
                   2153:        if (!quiet)
                   2154:                printf("Revoking from %s\n", path);
1.317     markus   2155:        while (getline(&line, &linesize, krl_spec) != -1) {
                   2156:                lnum++;
1.320     djm      2157:                was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
1.223     djm      2158:                cp = line + strspn(line, " \t");
                   2159:                /* Trim trailing space, comments and strip \n */
                   2160:                for (i = 0, r = -1; cp[i] != '\0'; i++) {
                   2161:                        if (cp[i] == '#' || cp[i] == '\n') {
                   2162:                                cp[i] = '\0';
                   2163:                                break;
                   2164:                        }
                   2165:                        if (cp[i] == ' ' || cp[i] == '\t') {
                   2166:                                /* Remember the start of a span of whitespace */
                   2167:                                if (r == -1)
                   2168:                                        r = i;
                   2169:                        } else
                   2170:                                r = -1;
                   2171:                }
                   2172:                if (r != -1)
                   2173:                        cp[r] = '\0';
                   2174:                if (*cp == '\0')
                   2175:                        continue;
                   2176:                if (strncasecmp(cp, "serial:", 7) == 0) {
1.261     djm      2177:                        if (ca == NULL && !wild_ca) {
1.231     djm      2178:                                fatal("revoking certificates by serial number "
1.223     djm      2179:                                    "requires specification of a CA key");
                   2180:                        }
                   2181:                        cp += 7;
                   2182:                        cp = cp + strspn(cp, " \t");
                   2183:                        errno = 0;
                   2184:                        serial = strtoull(cp, &ep, 0);
                   2185:                        if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
                   2186:                                fatal("%s:%lu: invalid serial \"%s\"",
                   2187:                                    path, lnum, cp);
                   2188:                        if (errno == ERANGE && serial == ULLONG_MAX)
                   2189:                                fatal("%s:%lu: serial out of range",
                   2190:                                    path, lnum);
                   2191:                        serial2 = serial;
                   2192:                        if (*ep == '-') {
                   2193:                                cp = ep + 1;
                   2194:                                errno = 0;
                   2195:                                serial2 = strtoull(cp, &ep, 0);
                   2196:                                if (*cp == '\0' || *ep != '\0')
                   2197:                                        fatal("%s:%lu: invalid serial \"%s\"",
                   2198:                                            path, lnum, cp);
                   2199:                                if (errno == ERANGE && serial2 == ULLONG_MAX)
                   2200:                                        fatal("%s:%lu: serial out of range",
                   2201:                                            path, lnum);
                   2202:                                if (serial2 <= serial)
                   2203:                                        fatal("%s:%lu: invalid serial range "
                   2204:                                            "%llu:%llu", path, lnum,
                   2205:                                            (unsigned long long)serial,
                   2206:                                            (unsigned long long)serial2);
                   2207:                        }
                   2208:                        if (ssh_krl_revoke_cert_by_serial_range(krl,
                   2209:                            ca, serial, serial2) != 0) {
                   2210:                                fatal("%s: revoke serial failed",
                   2211:                                    __func__);
                   2212:                        }
                   2213:                } else if (strncasecmp(cp, "id:", 3) == 0) {
1.261     djm      2214:                        if (ca == NULL && !wild_ca) {
1.232     djm      2215:                                fatal("revoking certificates by key ID "
1.223     djm      2216:                                    "requires specification of a CA key");
                   2217:                        }
                   2218:                        cp += 3;
                   2219:                        cp = cp + strspn(cp, " \t");
                   2220:                        if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
                   2221:                                fatal("%s: revoke key ID failed", __func__);
1.320     djm      2222:                } else if (strncasecmp(cp, "hash:", 5) == 0) {
                   2223:                        cp += 5;
                   2224:                        cp = cp + strspn(cp, " \t");
                   2225:                        hash_to_blob(cp, &blob, &blen, file, lnum);
                   2226:                        r = ssh_krl_revoke_key_sha256(krl, blob, blen);
1.223     djm      2227:                } else {
                   2228:                        if (strncasecmp(cp, "key:", 4) == 0) {
                   2229:                                cp += 4;
                   2230:                                cp = cp + strspn(cp, " \t");
                   2231:                                was_explicit_key = 1;
                   2232:                        } else if (strncasecmp(cp, "sha1:", 5) == 0) {
                   2233:                                cp += 5;
                   2234:                                cp = cp + strspn(cp, " \t");
                   2235:                                was_sha1 = 1;
1.320     djm      2236:                        } else if (strncasecmp(cp, "sha256:", 7) == 0) {
                   2237:                                cp += 7;
                   2238:                                cp = cp + strspn(cp, " \t");
                   2239:                                was_sha256 = 1;
1.223     djm      2240:                                /*
                   2241:                                 * Just try to process the line as a key.
                   2242:                                 * Parsing will fail if it isn't.
                   2243:                                 */
                   2244:                        }
1.252     djm      2245:                        if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
1.304     markus   2246:                                fatal("sshkey_new");
1.252     djm      2247:                        if ((r = sshkey_read(key, &cp)) != 0)
                   2248:                                fatal("%s:%lu: invalid key: %s",
                   2249:                                    path, lnum, ssh_err(r));
1.223     djm      2250:                        if (was_explicit_key)
                   2251:                                r = ssh_krl_revoke_key_explicit(krl, key);
1.320     djm      2252:                        else if (was_sha1) {
                   2253:                                if (sshkey_fingerprint_raw(key,
                   2254:                                    SSH_DIGEST_SHA1, &blob, &blen) != 0) {
                   2255:                                        fatal("%s:%lu: fingerprint failed",
                   2256:                                            file, lnum);
                   2257:                                }
                   2258:                                r = ssh_krl_revoke_key_sha1(krl, blob, blen);
                   2259:                        } else if (was_sha256) {
                   2260:                                if (sshkey_fingerprint_raw(key,
                   2261:                                    SSH_DIGEST_SHA256, &blob, &blen) != 0) {
                   2262:                                        fatal("%s:%lu: fingerprint failed",
                   2263:                                            file, lnum);
                   2264:                                }
                   2265:                                r = ssh_krl_revoke_key_sha256(krl, blob, blen);
                   2266:                        } else
1.223     djm      2267:                                r = ssh_krl_revoke_key(krl, key);
                   2268:                        if (r != 0)
1.252     djm      2269:                                fatal("%s: revoke key failed: %s",
                   2270:                                    __func__, ssh_err(r));
1.320     djm      2271:                        freezero(blob, blen);
                   2272:                        blob = NULL;
                   2273:                        blen = 0;
1.252     djm      2274:                        sshkey_free(key);
1.223     djm      2275:                }
                   2276:        }
                   2277:        if (strcmp(path, "-") != 0)
                   2278:                fclose(krl_spec);
1.317     markus   2279:        free(line);
1.226     djm      2280:        free(path);
1.223     djm      2281: }
                   2282:
                   2283: static void
                   2284: do_gen_krl(struct passwd *pw, int updating, int argc, char **argv)
                   2285: {
                   2286:        struct ssh_krl *krl;
                   2287:        struct stat sb;
1.252     djm      2288:        struct sshkey *ca = NULL;
1.261     djm      2289:        int fd, i, r, wild_ca = 0;
1.223     djm      2290:        char *tmp;
1.252     djm      2291:        struct sshbuf *kbuf;
1.223     djm      2292:
                   2293:        if (*identity_file == '\0')
                   2294:                fatal("KRL generation requires an output file");
                   2295:        if (stat(identity_file, &sb) == -1) {
                   2296:                if (errno != ENOENT)
                   2297:                        fatal("Cannot access KRL \"%s\": %s",
                   2298:                            identity_file, strerror(errno));
                   2299:                if (updating)
                   2300:                        fatal("KRL \"%s\" does not exist", identity_file);
                   2301:        }
                   2302:        if (ca_key_path != NULL) {
1.261     djm      2303:                if (strcasecmp(ca_key_path, "none") == 0)
                   2304:                        wild_ca = 1;
                   2305:                else {
                   2306:                        tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
                   2307:                        if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
                   2308:                                fatal("Cannot load CA public key %s: %s",
                   2309:                                    tmp, ssh_err(r));
                   2310:                        free(tmp);
                   2311:                }
1.223     djm      2312:        }
                   2313:
                   2314:        if (updating)
                   2315:                load_krl(identity_file, &krl);
                   2316:        else if ((krl = ssh_krl_init()) == NULL)
                   2317:                fatal("couldn't create KRL");
                   2318:
                   2319:        if (cert_serial != 0)
                   2320:                ssh_krl_set_version(krl, cert_serial);
                   2321:        if (identity_comment != NULL)
                   2322:                ssh_krl_set_comment(krl, identity_comment);
                   2323:
                   2324:        for (i = 0; i < argc; i++)
1.261     djm      2325:                update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
1.223     djm      2326:
1.252     djm      2327:        if ((kbuf = sshbuf_new()) == NULL)
                   2328:                fatal("sshbuf_new failed");
                   2329:        if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
1.223     djm      2330:                fatal("Couldn't generate KRL");
                   2331:        if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
                   2332:                fatal("open %s: %s", identity_file, strerror(errno));
1.318     markus   2333:        if (atomicio(vwrite, fd, sshbuf_mutable_ptr(kbuf), sshbuf_len(kbuf)) !=
1.252     djm      2334:            sshbuf_len(kbuf))
1.223     djm      2335:                fatal("write %s: %s", identity_file, strerror(errno));
                   2336:        close(fd);
1.252     djm      2337:        sshbuf_free(kbuf);
1.223     djm      2338:        ssh_krl_free(krl);
1.286     mmcc     2339:        sshkey_free(ca);
1.223     djm      2340: }
                   2341:
                   2342: static void
                   2343: do_check_krl(struct passwd *pw, int argc, char **argv)
                   2344: {
                   2345:        int i, r, ret = 0;
                   2346:        char *comment;
                   2347:        struct ssh_krl *krl;
1.252     djm      2348:        struct sshkey *k;
1.223     djm      2349:
                   2350:        if (*identity_file == '\0')
                   2351:                fatal("KRL checking requires an input file");
                   2352:        load_krl(identity_file, &krl);
                   2353:        for (i = 0; i < argc; i++) {
1.252     djm      2354:                if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
                   2355:                        fatal("Cannot load public key %s: %s",
                   2356:                            argv[i], ssh_err(r));
1.223     djm      2357:                r = ssh_krl_check_key(krl, k);
                   2358:                printf("%s%s%s%s: %s\n", argv[i],
                   2359:                    *comment ? " (" : "", comment, *comment ? ")" : "",
                   2360:                    r == 0 ? "ok" : "REVOKED");
                   2361:                if (r != 0)
                   2362:                        ret = 1;
1.252     djm      2363:                sshkey_free(k);
1.223     djm      2364:                free(comment);
                   2365:        }
                   2366:        ssh_krl_free(krl);
                   2367:        exit(ret);
                   2368: }
1.246     markus   2369: #endif
1.223     djm      2370:
                   2371: static void
1.10      markus   2372: usage(void)
                   2373: {
1.243     deraadt  2374:        fprintf(stderr,
1.302     djm      2375:            "usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa]\n"
1.243     deraadt  2376:            "                  [-N new_passphrase] [-C comment] [-f output_keyfile]\n"
                   2377:            "       ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]\n"
                   2378:            "       ssh-keygen -i [-m key_format] [-f input_keyfile]\n"
                   2379:            "       ssh-keygen -e [-m key_format] [-f input_keyfile]\n"
                   2380:            "       ssh-keygen -y [-f input_keyfile]\n"
                   2381:            "       ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]\n"
1.265     naddy    2382:            "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
1.302     djm      2383:            "       ssh-keygen -B [-f input_keyfile]\n");
1.177     markus   2384: #ifdef ENABLE_PKCS11
1.243     deraadt  2385:        fprintf(stderr,
                   2386:            "       ssh-keygen -D pkcs11\n");
1.177     markus   2387: #endif
1.243     deraadt  2388:        fprintf(stderr,
                   2389:            "       ssh-keygen -F hostname [-f known_hosts_file] [-l]\n"
                   2390:            "       ssh-keygen -H [-f known_hosts_file]\n"
                   2391:            "       ssh-keygen -R hostname [-f known_hosts_file]\n"
                   2392:            "       ssh-keygen -r hostname [-f input_keyfile] [-g]\n"
1.274     djm      2393: #ifdef WITH_OPENSSL
1.243     deraadt  2394:            "       ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]\n"
                   2395:            "       ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]\n"
                   2396:            "                  [-j start_line] [-K checkpt] [-W generator]\n"
1.274     djm      2397: #endif
1.305     djm      2398:            "       ssh-keygen -s ca_key -I certificate_identity [-h] [-U]\n"
                   2399:            "                  [-D pkcs11_provider] [-n principals] [-O option]\n"
                   2400:            "                  [-V validity_interval] [-z serial_number] file ...\n"
1.243     deraadt  2401:            "       ssh-keygen -L [-f input_keyfile]\n"
                   2402:            "       ssh-keygen -A\n"
                   2403:            "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
                   2404:            "                  file ...\n"
                   2405:            "       ssh-keygen -Q -f krl_file file ...\n");
1.12      markus   2406:        exit(1);
1.10      markus   2407: }
                   2408:
1.13      deraadt  2409: /*
                   2410:  * Main program for key management.
                   2411:  */
1.2       provos   2412: int
1.156     deraadt  2413: main(int argc, char **argv)
1.1       deraadt  2414: {
1.253     deraadt  2415:        char dotsshdir[PATH_MAX], comment[1024], *passphrase1, *passphrase2;
1.274     djm      2416:        char *rr_hostname = NULL, *ep, *fp, *ra;
1.252     djm      2417:        struct sshkey *private, *public;
1.12      markus   2418:        struct passwd *pw;
                   2419:        struct stat st;
1.252     djm      2420:        int r, opt, type, fd;
1.274     djm      2421:        int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
                   2422:        FILE *f;
                   2423:        const char *errstr;
                   2424: #ifdef WITH_OPENSSL
                   2425:        /* Moduli generation/screening */
                   2426:        char out_file[PATH_MAX], *checkpoint = NULL;
1.237     markus   2427:        u_int32_t memory = 0, generator_wanted = 0;
1.107     djm      2428:        int do_gen_candidates = 0, do_screen_candidates = 0;
1.215     dtucker  2429:        unsigned long start_lineno = 0, lines_to_process = 0;
1.107     djm      2430:        BIGNUM *start = NULL;
1.274     djm      2431: #endif
1.33      markus   2432:
1.12      markus   2433:        extern int optind;
                   2434:        extern char *optarg;
1.129     djm      2435:
1.288     dtucker  2436:        ssh_malloc_init();      /* must be called before any mallocs */
1.129     djm      2437:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                   2438:        sanitise_stdfd();
1.12      markus   2439:
1.201     djm      2440:        OpenSSL_add_all_algorithms();
1.156     deraadt  2441:        log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1.294     djm      2442:
                   2443:        setlocale(LC_CTYPE, "");
1.19      markus   2444:
1.14      markus   2445:        /* we need this for the home * directory.  */
1.12      markus   2446:        pw = getpwuid(getuid());
1.269     djm      2447:        if (!pw)
                   2448:                fatal("No user exists for uid %lu", (u_long)getuid());
                   2449:        if (gethostname(hostname, sizeof(hostname)) < 0)
                   2450:                fatal("gethostname: %s", strerror(errno));
1.14      markus   2451:
1.305     djm      2452:        /* Remaining characters: Ydw */
                   2453:        while ((opt = getopt(argc, argv, "ABHLQUXceghiklopquvxy"
1.251     djm      2454:            "C:D:E:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:"
                   2455:            "a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
1.12      markus   2456:                switch (opt) {
1.206     stevesk  2457:                case 'A':
                   2458:                        gen_all_hostkeys = 1;
                   2459:                        break;
1.12      markus   2460:                case 'b':
1.313     markus   2461:                        bits = (u_int32_t)strtonum(optarg, 10, 32768, &errstr);
1.125     avsm     2462:                        if (errstr)
                   2463:                                fatal("Bits has bad value %s (%s)",
                   2464:                                        optarg, errstr);
1.12      markus   2465:                        break;
1.251     djm      2466:                case 'E':
                   2467:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                   2468:                        if (fingerprint_hash == -1)
                   2469:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                   2470:                        break;
1.119     djm      2471:                case 'F':
                   2472:                        find_host = 1;
                   2473:                        rr_hostname = optarg;
                   2474:                        break;
                   2475:                case 'H':
                   2476:                        hash_hosts = 1;
                   2477:                        break;
1.179     djm      2478:                case 'I':
                   2479:                        cert_key_id = optarg;
                   2480:                        break;
1.119     djm      2481:                case 'R':
                   2482:                        delete_host = 1;
                   2483:                        rr_hostname = optarg;
                   2484:                        break;
1.182     djm      2485:                case 'L':
                   2486:                        show_cert = 1;
                   2487:                        break;
1.12      markus   2488:                case 'l':
                   2489:                        print_fingerprint = 1;
                   2490:                        break;
1.49      markus   2491:                case 'B':
                   2492:                        print_bubblebabble = 1;
                   2493:                        break;
1.193     djm      2494:                case 'm':
                   2495:                        if (strcasecmp(optarg, "RFC4716") == 0 ||
                   2496:                            strcasecmp(optarg, "ssh2") == 0) {
                   2497:                                convert_format = FMT_RFC4716;
                   2498:                                break;
                   2499:                        }
                   2500:                        if (strcasecmp(optarg, "PKCS8") == 0) {
                   2501:                                convert_format = FMT_PKCS8;
                   2502:                                break;
                   2503:                        }
                   2504:                        if (strcasecmp(optarg, "PEM") == 0) {
                   2505:                                convert_format = FMT_PEM;
1.319     djm      2506:                                use_new_format = 0;
1.193     djm      2507:                                break;
                   2508:                        }
                   2509:                        fatal("Unsupported conversion format \"%s\"", optarg);
1.179     djm      2510:                case 'n':
                   2511:                        cert_principals = optarg;
                   2512:                        break;
1.237     markus   2513:                case 'o':
1.319     djm      2514:                        /* no-op; new format is already the default */
1.237     markus   2515:                        break;
1.12      markus   2516:                case 'p':
                   2517:                        change_passphrase = 1;
                   2518:                        break;
                   2519:                case 'c':
                   2520:                        change_comment = 1;
                   2521:                        break;
                   2522:                case 'f':
1.274     djm      2523:                        if (strlcpy(identity_file, optarg,
                   2524:                            sizeof(identity_file)) >= sizeof(identity_file))
1.124     avsm     2525:                                fatal("Identity filename too long");
1.12      markus   2526:                        have_identity = 1;
                   2527:                        break;
1.105     jakob    2528:                case 'g':
                   2529:                        print_generic = 1;
                   2530:                        break;
1.12      markus   2531:                case 'P':
                   2532:                        identity_passphrase = optarg;
                   2533:                        break;
                   2534:                case 'N':
                   2535:                        identity_new_passphrase = optarg;
                   2536:                        break;
1.223     djm      2537:                case 'Q':
                   2538:                        check_krl = 1;
                   2539:                        break;
1.179     djm      2540:                case 'O':
1.186     djm      2541:                        add_cert_option(optarg);
1.179     djm      2542:                        break;
1.237     markus   2543:                case 'Z':
                   2544:                        new_format_cipher = optarg;
                   2545:                        break;
1.12      markus   2546:                case 'C':
                   2547:                        identity_comment = optarg;
                   2548:                        break;
                   2549:                case 'q':
                   2550:                        quiet = 1;
1.20      deraadt  2551:                        break;
1.57      markus   2552:                case 'e':
1.19      markus   2553:                case 'x':
1.57      markus   2554:                        /* export key */
1.193     djm      2555:                        convert_to = 1;
1.19      markus   2556:                        break;
1.179     djm      2557:                case 'h':
                   2558:                        cert_key_type = SSH2_CERT_TYPE_HOST;
1.190     djm      2559:                        certflags_flags = 0;
1.179     djm      2560:                        break;
1.223     djm      2561:                case 'k':
                   2562:                        gen_krl = 1;
                   2563:                        break;
1.57      markus   2564:                case 'i':
1.19      markus   2565:                case 'X':
1.57      markus   2566:                        /* import key */
1.193     djm      2567:                        convert_from = 1;
1.19      markus   2568:                        break;
                   2569:                case 'y':
                   2570:                        print_public = 1;
                   2571:                        break;
1.179     djm      2572:                case 's':
                   2573:                        ca_key_path = optarg;
                   2574:                        break;
1.33      markus   2575:                case 't':
                   2576:                        key_type_name = optarg;
                   2577:                        break;
1.75      markus   2578:                case 'D':
1.177     markus   2579:                        pkcs11provider = optarg;
1.305     djm      2580:                        break;
                   2581:                case 'U':
                   2582:                        prefer_agent = 1;
1.66      markus   2583:                        break;
1.223     djm      2584:                case 'u':
                   2585:                        update_krl = 1;
                   2586:                        break;
1.113     djm      2587:                case 'v':
                   2588:                        if (log_level == SYSLOG_LEVEL_INFO)
                   2589:                                log_level = SYSLOG_LEVEL_DEBUG1;
                   2590:                        else {
1.117     deraadt  2591:                                if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1.113     djm      2592:                                    log_level < SYSLOG_LEVEL_DEBUG3)
                   2593:                                        log_level++;
                   2594:                        }
                   2595:                        break;
1.105     jakob    2596:                case 'r':
1.119     djm      2597:                        rr_hostname = optarg;
1.105     jakob    2598:                        break;
1.107     djm      2599:                case 'a':
1.237     markus   2600:                        rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
1.124     avsm     2601:                        if (errstr)
1.237     markus   2602:                                fatal("Invalid number: %s (%s)",
1.124     avsm     2603:                                        optarg, errstr);
1.107     djm      2604:                        break;
1.274     djm      2605:                case 'V':
                   2606:                        parse_cert_times(optarg);
                   2607:                        break;
                   2608:                case 'z':
                   2609:                        errno = 0;
                   2610:                        cert_serial = strtoull(optarg, &ep, 10);
                   2611:                        if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
                   2612:                            (errno == ERANGE && cert_serial == ULLONG_MAX))
                   2613:                                fatal("Invalid serial number \"%s\"", optarg);
1.107     djm      2614:                        break;
1.274     djm      2615: #ifdef WITH_OPENSSL
                   2616:                /* Moduli generation/screening */
1.107     djm      2617:                case 'G':
                   2618:                        do_gen_candidates = 1;
1.124     avsm     2619:                        if (strlcpy(out_file, optarg, sizeof(out_file)) >=
                   2620:                            sizeof(out_file))
                   2621:                                fatal("Output filename too long");
1.107     djm      2622:                        break;
1.274     djm      2623:                case 'J':
                   2624:                        lines_to_process = strtoul(optarg, NULL, 10);
1.292     dtucker  2625:                        break;
1.274     djm      2626:                case 'j':
                   2627:                        start_lineno = strtoul(optarg, NULL, 10);
1.292     dtucker  2628:                        break;
1.211     dtucker  2629:                case 'K':
1.253     deraadt  2630:                        if (strlen(optarg) >= PATH_MAX)
1.211     dtucker  2631:                                fatal("Checkpoint filename too long");
                   2632:                        checkpoint = xstrdup(optarg);
                   2633:                        break;
1.274     djm      2634:                case 'M':
                   2635:                        memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX,
                   2636:                            &errstr);
                   2637:                        if (errstr)
                   2638:                                fatal("Memory limit is %s: %s", errstr, optarg);
                   2639:                        break;
1.107     djm      2640:                case 'S':
                   2641:                        /* XXX - also compare length against bits */
                   2642:                        if (BN_hex2bn(&start, optarg) == 0)
                   2643:                                fatal("Invalid start point.");
                   2644:                        break;
1.274     djm      2645:                case 'T':
                   2646:                        do_screen_candidates = 1;
                   2647:                        if (strlcpy(out_file, optarg, sizeof(out_file)) >=
                   2648:                            sizeof(out_file))
                   2649:                                fatal("Output filename too long");
1.186     djm      2650:                        break;
1.274     djm      2651:                case 'W':
                   2652:                        generator_wanted = (u_int32_t)strtonum(optarg, 1,
                   2653:                            UINT_MAX, &errstr);
                   2654:                        if (errstr != NULL)
                   2655:                                fatal("Desired generator invalid: %s (%s)",
                   2656:                                    optarg, errstr);
1.179     djm      2657:                        break;
1.274     djm      2658: #endif /* WITH_OPENSSL */
1.12      markus   2659:                case '?':
                   2660:                default:
                   2661:                        usage();
                   2662:                }
                   2663:        }
1.113     djm      2664:
                   2665:        /* reinit */
1.156     deraadt  2666:        log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1.113     djm      2667:
1.179     djm      2668:        argv += optind;
                   2669:        argc -= optind;
                   2670:
                   2671:        if (ca_key_path != NULL) {
1.223     djm      2672:                if (argc < 1 && !gen_krl) {
1.269     djm      2673:                        error("Too few arguments.");
1.179     djm      2674:                        usage();
                   2675:                }
1.223     djm      2676:        } else if (argc > 0 && !gen_krl && !check_krl) {
1.269     djm      2677:                error("Too many arguments.");
1.87      djm      2678:                usage();
                   2679:        }
1.12      markus   2680:        if (change_passphrase && change_comment) {
1.269     djm      2681:                error("Can only have one of -p and -c.");
1.166     djm      2682:                usage();
                   2683:        }
                   2684:        if (print_fingerprint && (delete_host || hash_hosts)) {
1.269     djm      2685:                error("Cannot use -l with -H or -R.");
1.12      markus   2686:                usage();
1.223     djm      2687:        }
1.246     markus   2688: #ifdef WITH_OPENSSL
1.223     djm      2689:        if (gen_krl) {
                   2690:                do_gen_krl(pw, update_krl, argc, argv);
                   2691:                return (0);
                   2692:        }
                   2693:        if (check_krl) {
                   2694:                do_check_krl(pw, argc, argv);
                   2695:                return (0);
1.179     djm      2696:        }
1.246     markus   2697: #endif
1.179     djm      2698:        if (ca_key_path != NULL) {
                   2699:                if (cert_key_id == NULL)
                   2700:                        fatal("Must specify key id (-I) when certifying");
                   2701:                do_ca_sign(pw, argc, argv);
1.12      markus   2702:        }
1.182     djm      2703:        if (show_cert)
                   2704:                do_show_cert(pw);
1.119     djm      2705:        if (delete_host || hash_hosts || find_host)
                   2706:                do_known_hosts(pw, rr_hostname);
1.221     djm      2707:        if (pkcs11provider != NULL)
                   2708:                do_download(pw);
1.49      markus   2709:        if (print_fingerprint || print_bubblebabble)
1.12      markus   2710:                do_fingerprint(pw);
                   2711:        if (change_passphrase)
                   2712:                do_change_passphrase(pw);
                   2713:        if (change_comment)
                   2714:                do_change_comment(pw);
1.246     markus   2715: #ifdef WITH_OPENSSL
1.193     djm      2716:        if (convert_to)
                   2717:                do_convert_to(pw);
                   2718:        if (convert_from)
                   2719:                do_convert_from(pw);
1.246     markus   2720: #endif
1.19      markus   2721:        if (print_public)
                   2722:                do_print_public(pw);
1.119     djm      2723:        if (rr_hostname != NULL) {
1.138     jakob    2724:                unsigned int n = 0;
                   2725:
                   2726:                if (have_identity) {
                   2727:                        n = do_print_resource_record(pw,
                   2728:                            identity_file, rr_hostname);
1.269     djm      2729:                        if (n == 0)
                   2730:                                fatal("%s: %s", identity_file, strerror(errno));
1.138     jakob    2731:                        exit(0);
                   2732:                } else {
                   2733:
                   2734:                        n += do_print_resource_record(pw,
                   2735:                            _PATH_HOST_RSA_KEY_FILE, rr_hostname);
                   2736:                        n += do_print_resource_record(pw,
                   2737:                            _PATH_HOST_DSA_KEY_FILE, rr_hostname);
1.214     djm      2738:                        n += do_print_resource_record(pw,
                   2739:                            _PATH_HOST_ECDSA_KEY_FILE, rr_hostname);
1.244     logan    2740:                        n += do_print_resource_record(pw,
                   2741:                            _PATH_HOST_ED25519_KEY_FILE, rr_hostname);
1.313     markus   2742:                        n += do_print_resource_record(pw,
                   2743:                            _PATH_HOST_XMSS_KEY_FILE, rr_hostname);
1.138     jakob    2744:                        if (n == 0)
                   2745:                                fatal("no keys found.");
                   2746:                        exit(0);
                   2747:                }
1.105     jakob    2748:        }
1.107     djm      2749:
1.274     djm      2750: #ifdef WITH_OPENSSL
1.107     djm      2751:        if (do_gen_candidates) {
                   2752:                FILE *out = fopen(out_file, "w");
1.111     djm      2753:
1.107     djm      2754:                if (out == NULL) {
                   2755:                        error("Couldn't open modulus candidate file \"%s\": %s",
                   2756:                            out_file, strerror(errno));
                   2757:                        return (1);
                   2758:                }
1.130     markus   2759:                if (bits == 0)
                   2760:                        bits = DEFAULT_BITS;
1.107     djm      2761:                if (gen_candidates(out, memory, bits, start) != 0)
1.131     stevesk  2762:                        fatal("modulus candidate generation failed");
1.107     djm      2763:
                   2764:                return (0);
                   2765:        }
                   2766:
                   2767:        if (do_screen_candidates) {
                   2768:                FILE *in;
1.225     djm      2769:                FILE *out = fopen(out_file, "a");
1.107     djm      2770:
                   2771:                if (have_identity && strcmp(identity_file, "-") != 0) {
                   2772:                        if ((in = fopen(identity_file, "r")) == NULL) {
                   2773:                                fatal("Couldn't open modulus candidate "
1.111     djm      2774:                                    "file \"%s\": %s", identity_file,
1.107     djm      2775:                                    strerror(errno));
                   2776:                        }
                   2777:                } else
                   2778:                        in = stdin;
                   2779:
                   2780:                if (out == NULL) {
                   2781:                        fatal("Couldn't open moduli file \"%s\": %s",
                   2782:                            out_file, strerror(errno));
                   2783:                }
1.237     markus   2784:                if (prime_test(in, out, rounds == 0 ? 100 : rounds,
                   2785:                    generator_wanted, checkpoint,
1.215     dtucker  2786:                    start_lineno, lines_to_process) != 0)
1.131     stevesk  2787:                        fatal("modulus screening failed");
1.108     markus   2788:                return (0);
1.75      markus   2789:        }
1.274     djm      2790: #endif
1.12      markus   2791:
1.206     stevesk  2792:        if (gen_all_hostkeys) {
                   2793:                do_gen_all_hostkeys(pw);
                   2794:                return (0);
                   2795:        }
                   2796:
1.133     djm      2797:        if (key_type_name == NULL)
1.273     djm      2798:                key_type_name = DEFAULT_KEY_TYPE_NAME;
1.133     djm      2799:
1.252     djm      2800:        type = sshkey_type_from_name(key_type_name);
1.255     djm      2801:        type_bits_valid(type, key_type_name, &bits);
1.206     stevesk  2802:
1.33      markus   2803:        if (!quiet)
1.252     djm      2804:                printf("Generating public/private %s key pair.\n",
                   2805:                    key_type_name);
1.269     djm      2806:        if ((r = sshkey_generate(type, bits, &private)) != 0)
1.304     markus   2807:                fatal("sshkey_generate failed");
1.269     djm      2808:        if ((r = sshkey_from_private(private, &public)) != 0)
1.304     markus   2809:                fatal("sshkey_from_private failed: %s\n", ssh_err(r));
1.12      markus   2810:
                   2811:        if (!have_identity)
                   2812:                ask_filename(pw, "Enter file in which to save the key");
                   2813:
1.132     djm      2814:        /* Create ~/.ssh directory if it doesn't already exist. */
1.188     djm      2815:        snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
                   2816:            pw->pw_dir, _PATH_SSH_USER_DIR);
                   2817:        if (strstr(identity_file, dotsshdir) != NULL) {
                   2818:                if (stat(dotsshdir, &st) < 0) {
                   2819:                        if (errno != ENOENT) {
                   2820:                                error("Could not stat %s: %s", dotsshdir,
                   2821:                                    strerror(errno));
                   2822:                        } else if (mkdir(dotsshdir, 0700) < 0) {
                   2823:                                error("Could not create directory '%s': %s",
                   2824:                                    dotsshdir, strerror(errno));
                   2825:                        } else if (!quiet)
                   2826:                                printf("Created directory '%s'.\n", dotsshdir);
                   2827:                }
1.12      markus   2828:        }
                   2829:        /* If the file already exists, ask the user to confirm. */
                   2830:        if (stat(identity_file, &st) >= 0) {
                   2831:                char yesno[3];
                   2832:                printf("%s already exists.\n", identity_file);
                   2833:                printf("Overwrite (y/n)? ");
                   2834:                fflush(stdout);
                   2835:                if (fgets(yesno, sizeof(yesno), stdin) == NULL)
                   2836:                        exit(1);
                   2837:                if (yesno[0] != 'y' && yesno[0] != 'Y')
                   2838:                        exit(1);
                   2839:        }
                   2840:        /* Ask for a passphrase (twice). */
                   2841:        if (identity_passphrase)
                   2842:                passphrase1 = xstrdup(identity_passphrase);
                   2843:        else if (identity_new_passphrase)
                   2844:                passphrase1 = xstrdup(identity_new_passphrase);
                   2845:        else {
                   2846: passphrase_again:
                   2847:                passphrase1 =
1.65      markus   2848:                        read_passphrase("Enter passphrase (empty for no "
                   2849:                            "passphrase): ", RP_ALLOW_STDIN);
                   2850:                passphrase2 = read_passphrase("Enter same passphrase again: ",
                   2851:                    RP_ALLOW_STDIN);
1.12      markus   2852:                if (strcmp(passphrase1, passphrase2) != 0) {
1.65      markus   2853:                        /*
                   2854:                         * The passphrases do not match.  Clear them and
                   2855:                         * retry.
                   2856:                         */
1.240     djm      2857:                        explicit_bzero(passphrase1, strlen(passphrase1));
                   2858:                        explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      2859:                        free(passphrase1);
                   2860:                        free(passphrase2);
1.12      markus   2861:                        printf("Passphrases do not match.  Try again.\n");
                   2862:                        goto passphrase_again;
                   2863:                }
                   2864:                /* Clear the other copy of the passphrase. */
1.240     djm      2865:                explicit_bzero(passphrase2, strlen(passphrase2));
1.227     djm      2866:                free(passphrase2);
1.12      markus   2867:        }
                   2868:
                   2869:        if (identity_comment) {
                   2870:                strlcpy(comment, identity_comment, sizeof(comment));
                   2871:        } else {
1.172     stevesk  2872:                /* Create default comment field for the passphrase. */
1.12      markus   2873:                snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
                   2874:        }
                   2875:
                   2876:        /* Save the key with the given passphrase and comment. */
1.252     djm      2877:        if ((r = sshkey_save_private(private, identity_file, passphrase1,
                   2878:            comment, use_new_format, new_format_cipher, rounds)) != 0) {
1.269     djm      2879:                error("Saving key \"%s\" failed: %s",
1.252     djm      2880:                    identity_file, ssh_err(r));
1.240     djm      2881:                explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      2882:                free(passphrase1);
1.12      markus   2883:                exit(1);
                   2884:        }
                   2885:        /* Clear the passphrase. */
1.240     djm      2886:        explicit_bzero(passphrase1, strlen(passphrase1));
1.227     djm      2887:        free(passphrase1);
1.12      markus   2888:
                   2889:        /* Clear the private key and the random number generator. */
1.252     djm      2890:        sshkey_free(private);
1.12      markus   2891:
                   2892:        if (!quiet)
                   2893:                printf("Your identification has been saved in %s.\n", identity_file);
                   2894:
                   2895:        strlcat(identity_file, ".pub", sizeof(identity_file));
1.269     djm      2896:        if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
                   2897:                fatal("Unable to save public key to %s: %s",
                   2898:                    identity_file, strerror(errno));
                   2899:        if ((f = fdopen(fd, "w")) == NULL)
                   2900:                fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1.252     djm      2901:        if ((r = sshkey_write(public, f)) != 0)
1.269     djm      2902:                error("write key failed: %s", ssh_err(r));
1.19      markus   2903:        fprintf(f, " %s\n", comment);
1.311     djm      2904:        if (ferror(f) || fclose(f) != 0)
                   2905:                fatal("write public failed: %s", strerror(errno));
1.12      markus   2906:
                   2907:        if (!quiet) {
1.259     djm      2908:                fp = sshkey_fingerprint(public, fingerprint_hash,
1.251     djm      2909:                    SSH_FP_DEFAULT);
1.259     djm      2910:                ra = sshkey_fingerprint(public, fingerprint_hash,
1.167     grunk    2911:                    SSH_FP_RANDOMART);
1.259     djm      2912:                if (fp == NULL || ra == NULL)
                   2913:                        fatal("sshkey_fingerprint failed");
1.19      markus   2914:                printf("Your public key has been saved in %s.\n",
                   2915:                    identity_file);
1.12      markus   2916:                printf("The key fingerprint is:\n");
1.50      markus   2917:                printf("%s %s\n", fp, comment);
1.167     grunk    2918:                printf("The key's randomart image is:\n");
                   2919:                printf("%s\n", ra);
1.227     djm      2920:                free(ra);
                   2921:                free(fp);
1.12      markus   2922:        }
1.19      markus   2923:
1.252     djm      2924:        sshkey_free(public);
1.12      markus   2925:        exit(0);
1.1       deraadt  2926: }