[BACK]Return to ssh-add.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/ssh-add.c, Revision 1.166

1.166   ! dtucker     1: /* $OpenBSD: ssh-add.c,v 1.165 2022/02/04 02:49:17 dtucker Exp $ */
1.1       deraadt     2: /*
1.13      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Adds an identity to the authentication server, or removes an identity.
1.19      markus      7:  *
1.22      deraadt     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".
                     13:  *
1.19      markus     14:  * SSH2 implementation,
1.41      markus     15:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.22      deraadt    16:  *
                     17:  * Redistribution and use in source and binary forms, with or without
                     18:  * modification, are permitted provided that the following conditions
                     19:  * are met:
                     20:  * 1. Redistributions of source code must retain the above copyright
                     21:  *    notice, this list of conditions and the following disclaimer.
                     22:  * 2. Redistributions in binary form must reproduce the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer in the
                     24:  *    documentation and/or other materials provided with the distribution.
                     25:  *
                     26:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     27:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     28:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     29:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     30:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     31:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     32:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     33:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     34:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     35:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.13      deraadt    36:  */
1.1       deraadt    37:
1.75      stevesk    38: #include <sys/types.h>
                     39: #include <sys/stat.h>
1.16      markus     40:
1.141     djm        41: #ifdef WITH_OPENSSL
1.19      markus     42: #include <openssl/evp.h>
1.141     djm        43: #endif
1.81      stevesk    44:
1.116     djm        45: #include <errno.h>
1.82      stevesk    46: #include <fcntl.h>
1.81      stevesk    47: #include <pwd.h>
1.88      stevesk    48: #include <stdio.h>
1.87      stevesk    49: #include <stdlib.h>
1.85      stevesk    50: #include <string.h>
1.146     naddy      51: #include <stdarg.h>
1.84      stevesk    52: #include <unistd.h>
1.117     deraadt    53: #include <limits.h>
1.1       deraadt    54:
1.89      deraadt    55: #include "xmalloc.h"
1.27      markus     56: #include "ssh.h"
                     57: #include "log.h"
1.116     djm        58: #include "sshkey.h"
                     59: #include "sshbuf.h"
1.18      markus     60: #include "authfd.h"
1.16      markus     61: #include "authfile.h"
1.25      markus     62: #include "pathnames.h"
1.57      stevesk    63: #include "misc.h"
1.110     djm        64: #include "ssherr.h"
1.115     djm        65: #include "digest.h"
1.148     djm        66: #include "ssh-sk.h"
1.157     djm        67: #include "sk-api.h"
1.162     djm        68: #include "hostfile.h"
1.1       deraadt    69:
1.45      jakob      70: /* argv0 */
                     71: extern char *__progname;
                     72:
1.48      djm        73: /* Default files to add */
                     74: static char *default_files[] = {
                     75:        _PATH_SSH_CLIENT_ID_RSA,
1.99      djm        76:        _PATH_SSH_CLIENT_ID_ECDSA,
1.143     djm        77:        _PATH_SSH_CLIENT_ID_ECDSA_SK,
1.107     pascal     78:        _PATH_SSH_CLIENT_ID_ED25519,
1.144     markus     79:        _PATH_SSH_CLIENT_ID_ED25519_SK,
1.135     markus     80:        _PATH_SSH_CLIENT_ID_XMSS,
1.165     dtucker    81:        _PATH_SSH_CLIENT_ID_DSA,
1.48      djm        82:        NULL
                     83: };
                     84:
1.115     djm        85: static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
                     86:
1.56      markus     87: /* Default lifetime (0 == forever) */
1.159     dtucker    88: static int lifetime = 0;
1.48      djm        89:
1.65      markus     90: /* User has to confirm key use */
                     91: static int confirm = 0;
                     92:
1.135     markus     93: /* Maximum number of signatures (XMSS) */
                     94: static u_int maxsign = 0;
                     95: static u_int minleft = 0;
                     96:
1.124     tim        97: /* we keep a cache of one passphrase */
1.33      markus     98: static char *pass = NULL;
1.39      itojun     99: static void
1.33      markus    100: clear_pass(void)
                    101: {
                    102:        if (pass) {
1.154     jsg       103:                freezero(pass, strlen(pass));
1.33      markus    104:                pass = NULL;
                    105:        }
                    106: }
                    107:
1.46      djm       108: static int
1.156     djm       109: delete_one(int agent_fd, const struct sshkey *key, const char *comment,
                    110:     const char *path, int qflag)
                    111: {
                    112:        int r;
                    113:
                    114:        if ((r = ssh_remove_identity(agent_fd, key)) != 0) {
                    115:                fprintf(stderr, "Could not remove identity \"%s\": %s\n",
                    116:                    path, ssh_err(r));
                    117:                return r;
                    118:        }
                    119:        if (!qflag) {
                    120:                fprintf(stderr, "Identity removed: %s %s (%s)\n", path,
1.166   ! dtucker   121:                    sshkey_type(key), comment ? comment : "no comment");
1.156     djm       122:        }
                    123:        return 0;
                    124: }
                    125:
                    126: static int
                    127: delete_stdin(int agent_fd, int qflag)
                    128: {
                    129:        char *line = NULL, *cp;
                    130:        size_t linesize = 0;
                    131:        struct sshkey *key = NULL;
                    132:        int lnum = 0, r, ret = -1;
                    133:
                    134:        while (getline(&line, &linesize, stdin) != -1) {
                    135:                lnum++;
                    136:                sshkey_free(key);
                    137:                key = NULL;
                    138:                line[strcspn(line, "\n")] = '\0';
                    139:                cp = line + strspn(line, " \t");
                    140:                if (*cp == '#' || *cp == '\0')
                    141:                        continue;
                    142:                if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
1.158     djm       143:                        fatal_f("sshkey_new");
1.156     djm       144:                if ((r = sshkey_read(key, &cp)) != 0) {
1.158     djm       145:                        error_r(r, "(stdin):%d: invalid key", lnum);
1.156     djm       146:                        continue;
                    147:                }
                    148:                if (delete_one(agent_fd, key, cp, "(stdin)", qflag) == 0)
                    149:                        ret = 0;
                    150:        }
                    151:        sshkey_free(key);
                    152:        free(line);
                    153:        return ret;
                    154: }
                    155:
                    156: static int
1.134     dlg       157: delete_file(int agent_fd, const char *filename, int key_only, int qflag)
1.1       deraadt   158: {
1.116     djm       159:        struct sshkey *public, *cert = NULL;
1.104     djm       160:        char *certpath = NULL, *comment = NULL;
1.116     djm       161:        int r, ret = -1;
1.1       deraadt   162:
1.156     djm       163:        if (strcmp(filename, "-") == 0)
                    164:                return delete_stdin(agent_fd, qflag);
                    165:
1.116     djm       166:        if ((r = sshkey_load_public(filename, &public,  &comment)) != 0) {
                    167:                printf("Bad key file %s: %s\n", filename, ssh_err(r));
1.46      djm       168:                return -1;
1.12      markus    169:        }
1.156     djm       170:        if (delete_one(agent_fd, public, comment, filename, qflag) == 0)
1.46      djm       171:                ret = 0;
                    172:
1.104     djm       173:        if (key_only)
                    174:                goto out;
                    175:
                    176:        /* Now try to delete the corresponding certificate too */
                    177:        free(comment);
1.105     markus    178:        comment = NULL;
1.104     djm       179:        xasprintf(&certpath, "%s-cert.pub", filename);
1.120     halex     180:        if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
                    181:                if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
1.158     djm       182:                        error_r(r, "Failed to load certificate \"%s\"", certpath);
1.104     djm       183:                goto out;
1.120     halex     184:        }
                    185:
1.116     djm       186:        if (!sshkey_equal_public(cert, public))
1.104     djm       187:                fatal("Certificate %s does not match private key %s",
                    188:                    certpath, filename);
                    189:
1.156     djm       190:        if (delete_one(agent_fd, cert, comment, certpath, qflag) == 0)
1.104     djm       191:                ret = 0;
                    192:
                    193:  out:
1.127     mmcc      194:        sshkey_free(cert);
                    195:        sshkey_free(public);
1.104     djm       196:        free(certpath);
                    197:        free(comment);
1.47      deraadt   198:
1.46      djm       199:        return ret;
1.1       deraadt   200: }
                    201:
1.19      markus    202: /* Send a request to remove all identities. */
1.46      djm       203: static int
1.136     djm       204: delete_all(int agent_fd, int qflag)
1.1       deraadt   205: {
1.46      djm       206:        int ret = -1;
1.19      markus    207:
1.130     djm       208:        /*
                    209:         * Since the agent might be forwarded, old or non-OpenSSH, when asked
                    210:         * to remove all keys, attempt to remove both protocol v.1 and v.2
                    211:         * keys.
                    212:         */
1.121     markus    213:        if (ssh_remove_all_identities(agent_fd, 2) == 0)
1.46      djm       214:                ret = 0;
1.121     markus    215:        /* ignore error-code for ssh1 */
                    216:        ssh_remove_all_identities(agent_fd, 1);
1.19      markus    217:
1.136     djm       218:        if (ret != 0)
                    219:                fprintf(stderr, "Failed to remove all identities.\n");
                    220:        else if (!qflag)
1.12      markus    221:                fprintf(stderr, "All identities removed.\n");
1.46      djm       222:
                    223:        return ret;
1.1       deraadt   224: }
                    225:
1.46      djm       226: static int
1.143     djm       227: add_file(int agent_fd, const char *filename, int key_only, int qflag,
1.162     djm       228:     const char *skprovider, struct dest_constraint **dest_constraints,
                    229:     size_t ndest_constraints)
1.1       deraadt   230: {
1.116     djm       231:        struct sshkey *private, *cert;
1.36      markus    232:        char *comment = NULL;
1.102     djm       233:        char msg[1024], *certpath = NULL;
1.116     djm       234:        int r, fd, ret = -1;
1.135     markus    235:        size_t i;
                    236:        u_int32_t left;
1.116     djm       237:        struct sshbuf *keyblob;
1.135     markus    238:        struct ssh_identitylist *idlist;
1.12      markus    239:
1.101     djm       240:        if (strcmp(filename, "-") == 0) {
                    241:                fd = STDIN_FILENO;
                    242:                filename = "(stdin)";
1.140     deraadt   243:        } else if ((fd = open(filename, O_RDONLY)) == -1) {
1.19      markus    244:                perror(filename);
1.46      djm       245:                return -1;
1.19      markus    246:        }
1.76      dtucker   247:
                    248:        /*
                    249:         * Since we'll try to load a keyfile multiple times, permission errors
                    250:         * will occur multiple times, so check perms first and bail if wrong.
                    251:         */
1.101     djm       252:        if (fd != STDIN_FILENO) {
1.116     djm       253:                if (sshkey_perm_ok(fd, filename) != 0) {
1.101     djm       254:                        close(fd);
                    255:                        return -1;
                    256:                }
                    257:        }
1.151     djm       258:        if ((r = sshbuf_load_fd(fd, &keyblob)) != 0) {
1.116     djm       259:                fprintf(stderr, "Error loading key \"%s\": %s\n",
                    260:                    filename, ssh_err(r));
                    261:                sshbuf_free(keyblob);
1.101     djm       262:                close(fd);
                    263:                return -1;
                    264:        }
1.76      dtucker   265:        close(fd);
                    266:
1.12      markus    267:        /* At first, try empty passphrase */
1.125     tim       268:        if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
                    269:            &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
1.116     djm       270:                fprintf(stderr, "Error loading key \"%s\": %s\n",
                    271:                    filename, ssh_err(r));
                    272:                goto fail_load;
                    273:        }
1.33      markus    274:        /* try last */
1.110     djm       275:        if (private == NULL && pass != NULL) {
1.125     tim       276:                if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
                    277:                    &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
1.116     djm       278:                        fprintf(stderr, "Error loading key \"%s\": %s\n",
                    279:                            filename, ssh_err(r));
                    280:                        goto fail_load;
                    281:                }
1.110     djm       282:        }
1.31      markus    283:        if (private == NULL) {
1.33      markus    284:                /* clear passphrase since it did not work */
                    285:                clear_pass();
1.124     tim       286:                snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
                    287:                    filename, confirm ? " (will confirm each use)" : "");
1.12      markus    288:                for (;;) {
1.40      markus    289:                        pass = read_passphrase(msg, RP_ALLOW_STDIN);
1.116     djm       290:                        if (strcmp(pass, "") == 0)
                    291:                                goto fail_load;
                    292:                        if ((r = sshkey_parse_private_fileblob(keyblob, pass,
1.125     tim       293:                            &private, &comment)) == 0)
1.116     djm       294:                                break;
                    295:                        else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
                    296:                                fprintf(stderr,
                    297:                                    "Error loading key \"%s\": %s\n",
                    298:                                    filename, ssh_err(r));
                    299:  fail_load:
1.35      markus    300:                                clear_pass();
1.116     djm       301:                                sshbuf_free(keyblob);
1.46      djm       302:                                return -1;
1.12      markus    303:                        }
1.33      markus    304:                        clear_pass();
1.68      markus    305:                        snprintf(msg, sizeof msg,
1.124     tim       306:                            "Bad passphrase, try again for %s%s: ", filename,
1.119     halex     307:                            confirm ? " (will confirm each use)" : "");
1.12      markus    308:                }
                    309:        }
1.124     tim       310:        if (comment == NULL || *comment == '\0')
                    311:                comment = xstrdup(filename);
1.116     djm       312:        sshbuf_free(keyblob);
1.60      markus    313:
1.135     markus    314:        /* For XMSS */
                    315:        if ((r = sshkey_set_filename(private, filename)) != 0) {
                    316:                fprintf(stderr, "Could not add filename to private key: %s (%s)\n",
                    317:                    filename, comment);
                    318:                goto out;
                    319:        }
                    320:        if (maxsign && minleft &&
                    321:            (r = ssh_fetch_identitylist(agent_fd, &idlist)) == 0) {
                    322:                for (i = 0; i < idlist->nkeys; i++) {
                    323:                        if (!sshkey_equal_public(idlist->keys[i], private))
                    324:                                continue;
                    325:                        left = sshkey_signatures_left(idlist->keys[i]);
                    326:                        if (left < minleft) {
                    327:                                fprintf(stderr,
                    328:                                    "Only %d signatures left.\n", left);
                    329:                                break;
                    330:                        }
                    331:                        fprintf(stderr, "Skipping update: ");
                    332:                        if (left == minleft) {
                    333:                                fprintf(stderr,
1.160     djm       334:                                    "required signatures left (%d).\n", left);
1.135     markus    335:                        } else {
                    336:                                fprintf(stderr,
1.160     djm       337:                                    "more signatures left (%d) than"
1.135     markus    338:                                    " required (%d).\n", left, minleft);
                    339:                        }
                    340:                        ssh_free_identitylist(idlist);
                    341:                        goto out;
                    342:                }
                    343:                ssh_free_identitylist(idlist);
                    344:        }
                    345:
1.157     djm       346:        if (sshkey_is_sk(private)) {
                    347:                if (skprovider == NULL) {
                    348:                        fprintf(stderr, "Cannot load FIDO key %s "
                    349:                            "without provider\n", filename);
                    350:                        goto out;
                    351:                }
                    352:        } else {
                    353:                /* Don't send provider constraint for other keys */
                    354:                skprovider = NULL;
1.143     djm       355:        }
                    356:
1.116     djm       357:        if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
1.162     djm       358:            lifetime, confirm, maxsign, skprovider,
                    359:            dest_constraints, ndest_constraints)) == 0) {
1.60      markus    360:                ret = 0;
1.136     djm       361:                if (!qflag) {
                    362:                        fprintf(stderr, "Identity added: %s (%s)\n",
                    363:                            filename, comment);
                    364:                        if (lifetime != 0) {
                    365:                                fprintf(stderr,
1.159     dtucker   366:                                    "Lifetime set to %d seconds\n", lifetime);
1.136     djm       367:                        }
                    368:                        if (confirm != 0) {
                    369:                                fprintf(stderr, "The user must confirm "
                    370:                                    "each use of the key\n");
                    371:                        }
                    372:                }
1.60      markus    373:        } else {
1.116     djm       374:                fprintf(stderr, "Could not add identity \"%s\": %s\n",
                    375:                    filename, ssh_err(r));
1.56      markus    376:        }
                    377:
1.102     djm       378:        /* Skip trying to load the cert if requested */
                    379:        if (key_only)
                    380:                goto out;
1.93      djm       381:
                    382:        /* Now try to add the certificate flavour too */
                    383:        xasprintf(&certpath, "%s-cert.pub", filename);
1.116     djm       384:        if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
                    385:                if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
1.158     djm       386:                        error_r(r, "Failed to load certificate \"%s\"", certpath);
1.96      djm       387:                goto out;
1.116     djm       388:        }
1.96      djm       389:
1.116     djm       390:        if (!sshkey_equal_public(cert, private)) {
1.96      djm       391:                error("Certificate %s does not match private key %s",
                    392:                    certpath, filename);
1.116     djm       393:                sshkey_free(cert);
1.96      djm       394:                goto out;
1.166   ! dtucker   395:        }
1.93      djm       396:
1.96      djm       397:        /* Graft with private bits */
1.123     djm       398:        if ((r = sshkey_to_certified(private)) != 0) {
1.158     djm       399:                error_fr(r, "sshkey_to_certified");
1.116     djm       400:                sshkey_free(cert);
                    401:                goto out;
                    402:        }
                    403:        if ((r = sshkey_cert_copy(cert, private)) != 0) {
1.158     djm       404:                error_fr(r, "sshkey_cert_copy");
1.116     djm       405:                sshkey_free(cert);
1.96      djm       406:                goto out;
1.94      otto      407:        }
1.116     djm       408:        sshkey_free(cert);
1.93      djm       409:
1.116     djm       410:        if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
1.162     djm       411:            lifetime, confirm, maxsign, skprovider,
                    412:            dest_constraints, ndest_constraints)) != 0) {
1.158     djm       413:                error_r(r, "Certificate %s (%s) add failed", certpath,
                    414:                    private->cert->key_id);
1.116     djm       415:                goto out;
1.96      djm       416:        }
1.136     djm       417:        /* success */
                    418:        if (!qflag) {
                    419:                fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
                    420:                    private->cert->key_id);
                    421:                if (lifetime != 0) {
1.159     dtucker   422:                        fprintf(stderr, "Lifetime set to %d seconds\n",
1.136     djm       423:                            lifetime);
                    424:                }
                    425:                if (confirm != 0) {
                    426:                        fprintf(stderr, "The user must confirm each use "
                    427:                            "of the key\n");
                    428:                }
                    429:        }
                    430:
1.96      djm       431:  out:
1.116     djm       432:        free(certpath);
1.106     djm       433:        free(comment);
1.116     djm       434:        sshkey_free(private);
1.47      deraadt   435:
1.46      djm       436:        return ret;
1.1       deraadt   437: }
                    438:
1.46      djm       439: static int
1.162     djm       440: update_card(int agent_fd, int add, const char *id, int qflag,
                    441:     struct dest_constraint **dest_constraints, size_t ndest_constraints)
1.42      markus    442: {
1.108     djm       443:        char *pin = NULL;
1.116     djm       444:        int r, ret = -1;
1.53      rees      445:
1.108     djm       446:        if (add) {
                    447:                if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
                    448:                    RP_ALLOW_STDIN)) == NULL)
                    449:                        return -1;
                    450:        }
1.53      rees      451:
1.116     djm       452:        if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
1.162     djm       453:            lifetime, confirm, dest_constraints, ndest_constraints)) == 0) {
1.66      markus    454:                ret = 0;
1.136     djm       455:                if (!qflag) {
                    456:                        fprintf(stderr, "Card %s: %s\n",
                    457:                            add ? "added" : "removed", id);
                    458:                }
1.46      djm       459:        } else {
1.116     djm       460:                fprintf(stderr, "Could not %s card \"%s\": %s\n",
                    461:                    add ? "add" : "remove", id, ssh_err(r));
1.66      markus    462:                ret = -1;
1.46      djm       463:        }
1.106     djm       464:        free(pin);
1.66      markus    465:        return ret;
1.42      markus    466: }
                    467:
1.50      markus    468: static int
1.137     djm       469: test_key(int agent_fd, const char *filename)
                    470: {
                    471:        struct sshkey *key = NULL;
                    472:        u_char *sig = NULL;
                    473:        size_t slen = 0;
                    474:        int r, ret = -1;
                    475:        char data[1024];
                    476:
                    477:        if ((r = sshkey_load_public(filename, &key, NULL)) != 0) {
1.158     djm       478:                error_r(r, "Couldn't read public key %s", filename);
1.137     djm       479:                return -1;
                    480:        }
                    481:        arc4random_buf(data, sizeof(data));
                    482:        if ((r = ssh_agent_sign(agent_fd, key, &sig, &slen, data, sizeof(data),
                    483:            NULL, 0)) != 0) {
1.158     djm       484:                error_r(r, "Agent signature failed for %s", filename);
1.137     djm       485:                goto done;
                    486:        }
                    487:        if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
1.147     djm       488:            NULL, 0, NULL)) != 0) {
1.158     djm       489:                error_r(r, "Signature verification failed for %s", filename);
1.137     djm       490:                goto done;
                    491:        }
                    492:        /* success */
                    493:        ret = 0;
                    494:  done:
                    495:        free(sig);
                    496:        sshkey_free(key);
                    497:        return ret;
                    498: }
                    499:
                    500: static int
1.116     djm       501: list_identities(int agent_fd, int do_fp)
1.1       deraadt   502: {
1.116     djm       503:        char *fp;
1.131     naddy     504:        int r;
1.116     djm       505:        struct ssh_identitylist *idlist;
1.135     markus    506:        u_int32_t left;
1.116     djm       507:        size_t i;
1.12      markus    508:
1.131     naddy     509:        if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
                    510:                if (r != SSH_ERR_AGENT_NO_IDENTITIES)
                    511:                        fprintf(stderr, "error fetching identities: %s\n",
                    512:                            ssh_err(r));
                    513:                else
                    514:                        printf("The agent has no identities.\n");
                    515:                return -1;
                    516:        }
                    517:        for (i = 0; i < idlist->nkeys; i++) {
                    518:                if (do_fp) {
                    519:                        fp = sshkey_fingerprint(idlist->keys[i],
                    520:                            fingerprint_hash, SSH_FP_DEFAULT);
                    521:                        printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
                    522:                            fp == NULL ? "(null)" : fp, idlist->comments[i],
                    523:                            sshkey_type(idlist->keys[i]));
                    524:                        free(fp);
                    525:                } else {
                    526:                        if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
                    527:                                fprintf(stderr, "sshkey_write: %s\n",
                    528:                                    ssh_err(r));
                    529:                                continue;
1.12      markus    530:                        }
1.135     markus    531:                        fprintf(stdout, " %s", idlist->comments[i]);
                    532:                        left = sshkey_signatures_left(idlist->keys[i]);
                    533:                        if (left > 0)
                    534:                                fprintf(stdout,
                    535:                                    " [signatures left %d]", left);
                    536:                        fprintf(stdout, "\n");
1.12      markus    537:                }
1.50      markus    538:        }
1.131     naddy     539:        ssh_free_identitylist(idlist);
1.50      markus    540:        return 0;
1.1       deraadt   541: }
                    542:
1.48      djm       543: static int
1.116     djm       544: lock_agent(int agent_fd, int lock)
1.54      markus    545: {
                    546:        char prompt[100], *p1, *p2;
1.116     djm       547:        int r, passok = 1, ret = -1;
1.61      deraadt   548:
1.54      markus    549:        strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
                    550:        p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
                    551:        if (lock) {
                    552:                strlcpy(prompt, "Again: ", sizeof prompt);
                    553:                p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
                    554:                if (strcmp(p1, p2) != 0) {
                    555:                        fprintf(stderr, "Passwords do not match.\n");
                    556:                        passok = 0;
                    557:                }
1.154     jsg       558:                freezero(p2, strlen(p2));
1.54      markus    559:        }
1.116     djm       560:        if (passok) {
                    561:                if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
                    562:                        fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
                    563:                        ret = 0;
                    564:                } else {
                    565:                        fprintf(stderr, "Failed to %slock agent: %s\n",
                    566:                            lock ? "" : "un", ssh_err(r));
                    567:                }
                    568:        }
1.154     jsg       569:        freezero(p1, strlen(p1));
1.62      markus    570:        return (ret);
1.54      markus    571: }
                    572:
                    573: static int
1.162     djm       574: load_resident_keys(int agent_fd, const char *skprovider, int qflag,
                    575:     struct dest_constraint **dest_constraints, size_t ndest_constraints)
1.148     djm       576: {
1.161     djm       577:        struct sshsk_resident_key **srks;
                    578:        size_t nsrks, i;
                    579:        struct sshkey *key;
1.148     djm       580:        int r, ok = 0;
                    581:        char *fp;
                    582:
1.152     naddy     583:        pass = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
1.161     djm       584:        if ((r = sshsk_load_resident(skprovider, NULL, pass, 0,
                    585:            &srks, &nsrks)) != 0) {
1.158     djm       586:                error_r(r, "Unable to load resident keys");
1.148     djm       587:                return r;
                    588:        }
1.161     djm       589:        for (i = 0; i < nsrks; i++) {
                    590:                key = srks[i]->key;
                    591:                if ((fp = sshkey_fingerprint(key,
1.148     djm       592:                    fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
1.158     djm       593:                        fatal_f("sshkey_fingerprint failed");
1.161     djm       594:                if ((r = ssh_add_identity_constrained(agent_fd, key, "",
1.162     djm       595:                    lifetime, confirm, maxsign, skprovider,
                    596:                    dest_constraints, ndest_constraints)) != 0) {
                    597:                        error("Unable to add key %s %s",
                    598:                            sshkey_type(key), fp);
1.148     djm       599:                        free(fp);
                    600:                        ok = r;
                    601:                        continue;
                    602:                }
                    603:                if (ok == 0)
                    604:                        ok = 1;
                    605:                if (!qflag) {
                    606:                        fprintf(stderr, "Resident identity added: %s %s\n",
1.161     djm       607:                            sshkey_type(key), fp);
1.148     djm       608:                        if (lifetime != 0) {
                    609:                                fprintf(stderr,
1.159     dtucker   610:                                    "Lifetime set to %d seconds\n", lifetime);
1.148     djm       611:                        }
                    612:                        if (confirm != 0) {
                    613:                                fprintf(stderr, "The user must confirm "
                    614:                                    "each use of the key\n");
                    615:                        }
                    616:                }
                    617:                free(fp);
                    618:        }
1.161     djm       619:        sshsk_free_resident_keys(srks, nsrks);
                    620:        if (nsrks == 0)
1.148     djm       621:                return SSH_ERR_KEY_NOT_FOUND;
                    622:        return ok == 1 ? 0 : ok;
                    623: }
                    624:
                    625: static int
1.143     djm       626: do_file(int agent_fd, int deleting, int key_only, char *file, int qflag,
1.162     djm       627:     const char *skprovider, struct dest_constraint **dest_constraints,
                    628:     size_t ndest_constraints)
1.48      djm       629: {
                    630:        if (deleting) {
1.134     dlg       631:                if (delete_file(agent_fd, file, key_only, qflag) == -1)
1.48      djm       632:                        return -1;
                    633:        } else {
1.162     djm       634:                if (add_file(agent_fd, file, key_only, qflag, skprovider,
                    635:                    dest_constraints, ndest_constraints) == -1)
1.48      djm       636:                        return -1;
                    637:        }
                    638:        return 0;
                    639: }
                    640:
1.162     djm       641: /* Append string 's' to a NULL-terminated array of strings */
                    642: static void
                    643: stringlist_append(char ***listp, const char *s)
                    644: {
                    645:        size_t i = 0;
                    646:
                    647:        if (*listp == NULL)
                    648:                *listp = xcalloc(2, sizeof(**listp));
                    649:        else {
                    650:                for (i = 0; (*listp)[i] != NULL; i++)
                    651:                        ; /* count */
                    652:                *listp = xrecallocarray(*listp, i + 1, i + 2, sizeof(**listp));
                    653:        }
                    654:        (*listp)[i] = xstrdup(s);
                    655: }
                    656:
                    657: static void
                    658: parse_dest_constraint_hop(const char *s, struct dest_constraint_hop *dch,
                    659:     char **hostkey_files)
                    660: {
                    661:        char *user = NULL, *host, *os, *path;
                    662:        size_t i;
                    663:        struct hostkeys *hostkeys;
                    664:        const struct hostkey_entry *hke;
                    665:        int r, want_ca;
                    666:
                    667:        memset(dch, '\0', sizeof(*dch));
                    668:        os = xstrdup(s);
                    669:        if ((host = strchr(os, '@')) == NULL)
                    670:                host = os;
                    671:        else {
                    672:                *host++ = '\0';
                    673:                user = os;
                    674:        }
                    675:        cleanhostname(host);
                    676:        /* Trivial case: username@ (all hosts) */
                    677:        if (*host == '\0') {
                    678:                if (user == NULL) {
                    679:                        fatal("Invalid key destination constraint \"%s\": "
                    680:                            "does not specify user or host", s);
                    681:                }
                    682:                dch->user = xstrdup(user);
                    683:                /* other fields left blank */
                    684:                free(os);
                    685:                return;
                    686:        }
                    687:        if (hostkey_files == NULL)
                    688:                fatal_f("no hostkey files");
                    689:        /* Otherwise we need to look up the keys for this hostname */
                    690:        hostkeys = init_hostkeys();
                    691:        for (i = 0; hostkey_files[i]; i++) {
                    692:                path = tilde_expand_filename(hostkey_files[i], getuid());
                    693:                debug2_f("looking up host keys for \"%s\" in %s", host, path);
                    694:                 load_hostkeys(hostkeys, host, path, 0);
                    695:                free(path);
                    696:        }
                    697:        dch->user = user == NULL ? NULL : xstrdup(user);
                    698:        dch->hostname = xstrdup(host);
                    699:        for (i = 0; i < hostkeys->num_entries; i++) {
                    700:                hke = hostkeys->entries + i;
                    701:                want_ca = hke->marker == MRK_CA;
                    702:                if (hke->marker != MRK_NONE && !want_ca)
                    703:                        continue;
                    704:                debug3_f("%s%s%s: adding %s %skey from %s:%lu as key %u",
                    705:                    user == NULL ? "": user, user == NULL ? "" : "@",
                    706:                    host, sshkey_type(hke->key), want_ca ? "CA " : "",
                    707:                    hke->file, hke->line, dch->nkeys);
                    708:                dch->keys = xrecallocarray(dch->keys, dch->nkeys,
                    709:                    dch->nkeys + 1, sizeof(*dch->keys));
                    710:                dch->key_is_ca = xrecallocarray(dch->key_is_ca, dch->nkeys,
                    711:                    dch->nkeys + 1, sizeof(*dch->key_is_ca));
                    712:                if ((r = sshkey_from_private(hke->key,
                    713:                    &(dch->keys[dch->nkeys]))) != 0)
                    714:                        fatal_fr(r, "sshkey_from_private");
                    715:                dch->key_is_ca[dch->nkeys] = want_ca;
                    716:                dch->nkeys++;
                    717:        }
                    718:        if (dch->nkeys == 0)
                    719:                fatal("No host keys found for destination \"%s\"", host);
                    720:        free_hostkeys(hostkeys);
                    721:        free(os);
                    722:        return;
                    723: }
                    724:
                    725: static void
                    726: parse_dest_constraint(const char *s, struct dest_constraint ***dcp,
                    727:     size_t *ndcp, char **hostkey_files)
                    728: {
                    729:        struct dest_constraint *dc;
                    730:        char *os, *cp;
                    731:
                    732:        dc = xcalloc(1, sizeof(*dc));
                    733:        os = xstrdup(s);
                    734:        if ((cp = strchr(os, '>')) == NULL) {
                    735:                /* initial hop; no 'from' hop specified */
                    736:                parse_dest_constraint_hop(os, &dc->to, hostkey_files);
                    737:        } else {
                    738:                /* two hops specified */
                    739:                *(cp++) = '\0';
                    740:                parse_dest_constraint_hop(os, &dc->from, hostkey_files);
                    741:                parse_dest_constraint_hop(cp, &dc->to, hostkey_files);
                    742:                if (dc->from.user != NULL) {
                    743:                        fatal("Invalid key constraint %s: cannot specify "
                    744:                            "user on 'from' host", os);
                    745:                }
                    746:        }
                    747:        /* XXX eliminate or error on duplicates */
                    748:        debug2_f("constraint %zu: %s%s%s (%u keys) > %s%s%s (%u keys)", *ndcp,
                    749:            dc->from.user ? dc->from.user : "", dc->from.user ? "@" : "",
                    750:            dc->from.hostname ? dc->from.hostname : "(ORIGIN)", dc->from.nkeys,
                    751:            dc->to.user ? dc->to.user : "", dc->to.user ? "@" : "",
                    752:            dc->to.hostname ? dc->to.hostname : "(ANY)", dc->to.nkeys);
                    753:        *dcp = xrecallocarray(*dcp, *ndcp, *ndcp + 1, sizeof(**dcp));
                    754:        (*dcp)[(*ndcp)++] = dc;
                    755:        free(os);
                    756: }
                    757:
                    758:
1.42      markus    759: static void
                    760: usage(void)
                    761: {
1.150     naddy     762:        fprintf(stderr,
1.163     jmc       763: "usage: ssh-add [-cDdKkLlqvXx] [-E fingerprint_hash] [-H hostkey_file]\n"
                    764: "               [-h destination_constraint] [-S provider] [-t life]\n"
1.150     naddy     765: #ifdef WITH_XMSS
                    766: "               [-M maxsign] [-m minleft]\n"
                    767: #endif
                    768: "               [file ...]\n"
                    769: "       ssh-add -s pkcs11\n"
                    770: "       ssh-add -e pkcs11\n"
                    771: "       ssh-add -T pubkey ...\n"
                    772:        );
1.42      markus    773: }
                    774:
1.2       provos    775: int
1.7       markus    776: main(int argc, char **argv)
1.1       deraadt   777: {
1.43      markus    778:        extern char *optarg;
                    779:        extern int optind;
1.116     djm       780:        int agent_fd;
1.143     djm       781:        char *pkcs11provider = NULL, *skprovider = NULL;
1.162     djm       782:        char **dest_constraint_strings = NULL, **hostkey_files = NULL;
1.148     djm       783:        int r, i, ch, deleting = 0, ret = 0, key_only = 0, do_download = 0;
1.137     djm       784:        int xflag = 0, lflag = 0, Dflag = 0, qflag = 0, Tflag = 0;
1.138     djm       785:        SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
                    786:        LogLevel log_level = SYSLOG_LEVEL_INFO;
1.162     djm       787:        struct dest_constraint **dest_constraints = NULL;
                    788:        size_t ndest_constraints = 0;
1.73      djm       789:
                    790:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    791:        sanitise_stdfd();
1.12      markus    792:
1.141     djm       793: #ifdef WITH_OPENSSL
1.100     djm       794:        OpenSSL_add_all_algorithms();
1.141     djm       795: #endif
1.138     djm       796:        log_init(__progname, log_level, log_facility, 1);
                    797:
1.114     millert   798:        setvbuf(stdout, NULL, _IOLBF, 0);
1.19      markus    799:
1.116     djm       800:        /* First, get a connection to the authentication agent. */
                    801:        switch (r = ssh_get_authentication_socket(&agent_fd)) {
                    802:        case 0:
                    803:                break;
                    804:        case SSH_ERR_AGENT_NOT_PRESENT:
                    805:                fprintf(stderr, "Could not open a connection to your "
                    806:                    "authentication agent.\n");
                    807:                exit(2);
                    808:        default:
                    809:                fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
1.50      markus    810:                exit(2);
1.12      markus    811:        }
1.116     djm       812:
1.143     djm       813:        skprovider = getenv("SSH_SK_PROVIDER");
                    814:
1.162     djm       815:        while ((ch = getopt(argc, argv, "vkKlLcdDTxXE:e:h:H:M:m:qs:S:t:")) != -1) {
1.43      markus    816:                switch (ch) {
1.138     djm       817:                case 'v':
                    818:                        if (log_level == SYSLOG_LEVEL_INFO)
                    819:                                log_level = SYSLOG_LEVEL_DEBUG1;
                    820:                        else if (log_level < SYSLOG_LEVEL_DEBUG3)
                    821:                                log_level++;
                    822:                        break;
1.115     djm       823:                case 'E':
                    824:                        fingerprint_hash = ssh_digest_alg_by_name(optarg);
                    825:                        if (fingerprint_hash == -1)
                    826:                                fatal("Invalid hash algorithm \"%s\"", optarg);
                    827:                        break;
1.162     djm       828:                case 'H':
                    829:                        stringlist_append(&hostkey_files, optarg);
                    830:                        break;
                    831:                case 'h':
                    832:                        stringlist_append(&dest_constraint_strings, optarg);
                    833:                        break;
1.102     djm       834:                case 'k':
                    835:                        key_only = 1;
                    836:                        break;
1.150     naddy     837:                case 'K':
                    838:                        do_download = 1;
                    839:                        break;
1.43      markus    840:                case 'l':
                    841:                case 'L':
1.115     djm       842:                        if (lflag != 0)
                    843:                                fatal("-%c flag already specified", lflag);
                    844:                        lflag = ch;
1.148     djm       845:                        break;
1.54      markus    846:                case 'x':
                    847:                case 'X':
1.115     djm       848:                        if (xflag != 0)
                    849:                                fatal("-%c flag already specified", xflag);
                    850:                        xflag = ch;
                    851:                        break;
1.65      markus    852:                case 'c':
                    853:                        confirm = 1;
1.135     markus    854:                        break;
                    855:                case 'm':
                    856:                        minleft = (int)strtonum(optarg, 1, UINT_MAX, NULL);
                    857:                        if (minleft == 0) {
                    858:                                usage();
                    859:                                ret = 1;
                    860:                                goto done;
                    861:                        }
                    862:                        break;
                    863:                case 'M':
                    864:                        maxsign = (int)strtonum(optarg, 1, UINT_MAX, NULL);
                    865:                        if (maxsign == 0) {
                    866:                                usage();
                    867:                                ret = 1;
                    868:                                goto done;
                    869:                        }
1.43      markus    870:                        break;
                    871:                case 'd':
1.12      markus    872:                        deleting = 1;
1.43      markus    873:                        break;
                    874:                case 'D':
1.115     djm       875:                        Dflag = 1;
                    876:                        break;
1.43      markus    877:                case 's':
1.92      markus    878:                        pkcs11provider = optarg;
1.43      markus    879:                        break;
1.143     djm       880:                case 'S':
                    881:                        skprovider = optarg;
                    882:                        break;
1.43      markus    883:                case 'e':
1.47      deraadt   884:                        deleting = 1;
1.92      markus    885:                        pkcs11provider = optarg;
1.56      markus    886:                        break;
                    887:                case 't':
1.153     dtucker   888:                        if ((lifetime = convtime(optarg)) == -1 ||
1.155     dtucker   889:                            lifetime < 0 || (u_long)lifetime > UINT32_MAX) {
1.57      stevesk   890:                                fprintf(stderr, "Invalid lifetime\n");
                    891:                                ret = 1;
                    892:                                goto done;
                    893:                        }
1.43      markus    894:                        break;
1.134     dlg       895:                case 'q':
                    896:                        qflag = 1;
                    897:                        break;
1.137     djm       898:                case 'T':
                    899:                        Tflag = 1;
                    900:                        break;
1.43      markus    901:                default:
                    902:                        usage();
1.46      djm       903:                        ret = 1;
                    904:                        goto done;
1.42      markus    905:                }
                    906:        }
1.138     djm       907:        log_init(__progname, log_level, log_facility, 1);
1.115     djm       908:
                    909:        if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
                    910:                fatal("Invalid combination of actions");
                    911:        else if (xflag) {
1.116     djm       912:                if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
1.115     djm       913:                        ret = 1;
                    914:                goto done;
                    915:        } else if (lflag) {
1.116     djm       916:                if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
1.115     djm       917:                        ret = 1;
                    918:                goto done;
                    919:        } else if (Dflag) {
1.136     djm       920:                if (delete_all(agent_fd, qflag) == -1)
1.115     djm       921:                        ret = 1;
                    922:                goto done;
                    923:        }
1.145     djm       924:
                    925:        if (skprovider == NULL)
                    926:                skprovider = "internal";
1.162     djm       927:        if (hostkey_files == NULL) {
                    928:                /* use defaults from readconf.c */
                    929:                stringlist_append(&hostkey_files, _PATH_SSH_USER_HOSTFILE);
                    930:                stringlist_append(&hostkey_files, _PATH_SSH_USER_HOSTFILE2);
                    931:                stringlist_append(&hostkey_files, _PATH_SSH_SYSTEM_HOSTFILE);
                    932:                stringlist_append(&hostkey_files, _PATH_SSH_SYSTEM_HOSTFILE2);
                    933:        }
                    934:        if (dest_constraint_strings != NULL) {
                    935:                for (i = 0; dest_constraint_strings[i] != NULL; i++) {
                    936:                        parse_dest_constraint(dest_constraint_strings[i],
                    937:                          &dest_constraints, &ndest_constraints, hostkey_files);
                    938:                }
                    939:        }
1.115     djm       940:
1.43      markus    941:        argc -= optind;
                    942:        argv += optind;
1.137     djm       943:        if (Tflag) {
                    944:                if (argc <= 0)
                    945:                        fatal("no keys to test");
                    946:                for (r = i = 0; i < argc; i++)
                    947:                        r |= test_key(agent_fd, argv[i]);
                    948:                ret = r == 0 ? 0 : 1;
                    949:                goto done;
                    950:        }
1.92      markus    951:        if (pkcs11provider != NULL) {
1.136     djm       952:                if (update_card(agent_fd, !deleting, pkcs11provider,
1.162     djm       953:                    qflag, dest_constraints, ndest_constraints) == -1)
1.46      djm       954:                        ret = 1;
1.43      markus    955:                goto done;
1.12      markus    956:        }
1.148     djm       957:        if (do_download) {
                    958:                if (skprovider == NULL)
                    959:                        fatal("Cannot download keys without provider");
1.162     djm       960:                if (load_resident_keys(agent_fd, skprovider, qflag,
                    961:                    dest_constraints, ndest_constraints) != 0)
1.148     djm       962:                        ret = 1;
                    963:                goto done;
                    964:        }
1.43      markus    965:        if (argc == 0) {
1.117     deraadt   966:                char buf[PATH_MAX];
1.48      djm       967:                struct passwd *pw;
1.52      markus    968:                struct stat st;
                    969:                int count = 0;
1.48      djm       970:
                    971:                if ((pw = getpwuid(getuid())) == NULL) {
1.20      deraadt   972:                        fprintf(stderr, "No user found with uid %u\n",
                    973:                            (u_int)getuid());
1.46      djm       974:                        ret = 1;
                    975:                        goto done;
1.12      markus    976:                }
1.48      djm       977:
1.71      deraadt   978:                for (i = 0; default_files[i]; i++) {
1.51      markus    979:                        snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
1.48      djm       980:                            default_files[i]);
1.140     deraadt   981:                        if (stat(buf, &st) == -1)
1.52      markus    982:                                continue;
1.134     dlg       983:                        if (do_file(agent_fd, deleting, key_only, buf,
1.162     djm       984:                            qflag, skprovider,
                    985:                            dest_constraints, ndest_constraints) == -1)
1.46      djm       986:                                ret = 1;
1.52      markus    987:                        else
                    988:                                count++;
1.46      djm       989:                }
1.52      markus    990:                if (count == 0)
                    991:                        ret = 1;
1.43      markus    992:        } else {
1.71      deraadt   993:                for (i = 0; i < argc; i++) {
1.116     djm       994:                        if (do_file(agent_fd, deleting, key_only,
1.162     djm       995:                            argv[i], qflag, skprovider,
                    996:                            dest_constraints, ndest_constraints) == -1)
1.48      djm       997:                                ret = 1;
1.43      markus    998:                }
1.12      markus    999:        }
1.148     djm      1000: done:
1.33      markus   1001:        clear_pass();
1.116     djm      1002:        ssh_close_authentication_socket(agent_fd);
1.46      djm      1003:        return ret;
1.1       deraadt  1004: }