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

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