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

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