[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.325

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