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

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