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

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