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

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