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

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