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

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