1 /* $OpenBSD: ssh-add.c,v 1.135 2018/02/23 15:58:37 markus Exp $ */
2 /*
3 * Author: Tatu Ylonen <[email protected]>
4 * Copyright (c) 1995 Tatu Ylonen <[email protected]>, Espoo, Finland
5 * All rights reserved
6 * Adds an identity to the authentication server, or removes an identity.
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".
13 *
14 * SSH2 implementation,
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
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.
36 */
37
38 #include "includes.h"
39
40 #include <sys/types.h>
41 #include <sys/stat.h>
42
43 #include <openssl/evp.h>
44 #include "openbsd-compat/openssl-compat.h"
45
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <pwd.h>
49 #include <stdarg.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <limits.h>
55
56 #include "xmalloc.h"
57 #include "ssh.h"
58 #include "log.h"
59 #include "sshkey.h"
60 #include "sshbuf.h"
61 #include "authfd.h"
62 #include "authfile.h"
63 #include "pathnames.h"
64 #include "misc.h"
65 #include "ssherr.h"
66 #include "digest.h"
67
68 /* argv0 */
69 extern char *__progname;
70
71 /* Default files to add */
72 static char *default_files[] = {
73 #ifdef WITH_OPENSSL
74 _PATH_SSH_CLIENT_ID_RSA,
75 _PATH_SSH_CLIENT_ID_DSA,
76 #ifdef OPENSSL_HAS_ECC
77 _PATH_SSH_CLIENT_ID_ECDSA,
78 #endif
79 #endif /* WITH_OPENSSL */
80 _PATH_SSH_CLIENT_ID_ED25519,
81 _PATH_SSH_CLIENT_ID_XMSS,
82 NULL
83 };
84
85 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
86
87 /* Default lifetime (0 == forever) */
88 static int lifetime = 0;
89
90 /* User has to confirm key use */
91 static int confirm = 0;
92
93 /* Maximum number of signatures (XMSS) */
94 static u_int maxsign = 0;
95 static u_int minleft = 0;
96
97 /* we keep a cache of one passphrase */
98 static char *pass = NULL;
99 static void
clear_pass(void)100 clear_pass(void)
101 {
102 if (pass) {
103 explicit_bzero(pass, strlen(pass));
104 free(pass);
105 pass = NULL;
106 }
107 }
108
109 static int
delete_file(int agent_fd,const char * filename,int key_only,int qflag)110 delete_file(int agent_fd, const char *filename, int key_only, int qflag)
111 {
112 struct sshkey *public, *cert = NULL;
113 char *certpath = NULL, *comment = NULL;
114 int r, ret = -1;
115
116 if ((r = sshkey_load_public(filename, &public, &comment)) != 0) {
117 printf("Bad key file %s: %s\n", filename, ssh_err(r));
118 return -1;
119 }
120 if ((r = ssh_remove_identity(agent_fd, public)) == 0) {
121 if (!qflag) {
122 fprintf(stderr, "Identity removed: %s (%s)\n",
123 filename, comment);
124 }
125 ret = 0;
126 } else
127 fprintf(stderr, "Could not remove identity \"%s\": %s\n",
128 filename, ssh_err(r));
129
130 if (key_only)
131 goto out;
132
133 /* Now try to delete the corresponding certificate too */
134 free(comment);
135 comment = NULL;
136 xasprintf(&certpath, "%s-cert.pub", filename);
137 if ((r = sshkey_load_public(certpath, &cert, &comment)) != 0) {
138 if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
139 error("Failed to load certificate \"%s\": %s",
140 certpath, ssh_err(r));
141 goto out;
142 }
143
144 if (!sshkey_equal_public(cert, public))
145 fatal("Certificate %s does not match private key %s",
146 certpath, filename);
147
148 if ((r = ssh_remove_identity(agent_fd, cert)) == 0) {
149 if (!qflag) {
150 fprintf(stderr, "Identity removed: %s (%s)\n",
151 certpath, comment);
152 }
153 ret = 0;
154 } else
155 fprintf(stderr, "Could not remove identity \"%s\": %s\n",
156 certpath, ssh_err(r));
157
158 out:
159 sshkey_free(cert);
160 sshkey_free(public);
161 free(certpath);
162 free(comment);
163
164 return ret;
165 }
166
167 /* Send a request to remove all identities. */
168 static int
delete_all(int agent_fd)169 delete_all(int agent_fd)
170 {
171 int ret = -1;
172
173 /*
174 * Since the agent might be forwarded, old or non-OpenSSH, when asked
175 * to remove all keys, attempt to remove both protocol v.1 and v.2
176 * keys.
177 */
178 if (ssh_remove_all_identities(agent_fd, 2) == 0)
179 ret = 0;
180 /* ignore error-code for ssh1 */
181 ssh_remove_all_identities(agent_fd, 1);
182
183 if (ret == 0)
184 fprintf(stderr, "All identities removed.\n");
185 else
186 fprintf(stderr, "Failed to remove all identities.\n");
187
188 return ret;
189 }
190
191 static int
add_file(int agent_fd,const char * filename,int key_only,int qflag)192 add_file(int agent_fd, const char *filename, int key_only, int qflag)
193 {
194 struct sshkey *private, *cert;
195 char *comment = NULL;
196 char msg[1024], *certpath = NULL;
197 int r, fd, ret = -1;
198 size_t i;
199 u_int32_t left;
200 struct sshbuf *keyblob;
201 struct ssh_identitylist *idlist;
202
203 if (strcmp(filename, "-") == 0) {
204 fd = STDIN_FILENO;
205 filename = "(stdin)";
206 } else if ((fd = open(filename, O_RDONLY)) < 0) {
207 perror(filename);
208 return -1;
209 }
210
211 /*
212 * Since we'll try to load a keyfile multiple times, permission errors
213 * will occur multiple times, so check perms first and bail if wrong.
214 */
215 if (fd != STDIN_FILENO) {
216 if (sshkey_perm_ok(fd, filename) != 0) {
217 close(fd);
218 return -1;
219 }
220 }
221 if ((keyblob = sshbuf_new()) == NULL)
222 fatal("%s: sshbuf_new failed", __func__);
223 if ((r = sshkey_load_file(fd, keyblob)) != 0) {
224 fprintf(stderr, "Error loading key \"%s\": %s\n",
225 filename, ssh_err(r));
226 sshbuf_free(keyblob);
227 close(fd);
228 return -1;
229 }
230 close(fd);
231
232 /* At first, try empty passphrase */
233 if ((r = sshkey_parse_private_fileblob(keyblob, "", &private,
234 &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
235 fprintf(stderr, "Error loading key \"%s\": %s\n",
236 filename, ssh_err(r));
237 goto fail_load;
238 }
239 /* try last */
240 if (private == NULL && pass != NULL) {
241 if ((r = sshkey_parse_private_fileblob(keyblob, pass, &private,
242 &comment)) != 0 && r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
243 fprintf(stderr, "Error loading key \"%s\": %s\n",
244 filename, ssh_err(r));
245 goto fail_load;
246 }
247 }
248 if (private == NULL) {
249 /* clear passphrase since it did not work */
250 clear_pass();
251 snprintf(msg, sizeof msg, "Enter passphrase for %s%s: ",
252 filename, confirm ? " (will confirm each use)" : "");
253 for (;;) {
254 pass = read_passphrase(msg, RP_ALLOW_STDIN);
255 if (strcmp(pass, "") == 0)
256 goto fail_load;
257 if ((r = sshkey_parse_private_fileblob(keyblob, pass,
258 &private, &comment)) == 0)
259 break;
260 else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE) {
261 fprintf(stderr,
262 "Error loading key \"%s\": %s\n",
263 filename, ssh_err(r));
264 fail_load:
265 clear_pass();
266 sshbuf_free(keyblob);
267 return -1;
268 }
269 clear_pass();
270 snprintf(msg, sizeof msg,
271 "Bad passphrase, try again for %s%s: ", filename,
272 confirm ? " (will confirm each use)" : "");
273 }
274 }
275 if (comment == NULL || *comment == '\0')
276 comment = xstrdup(filename);
277 sshbuf_free(keyblob);
278
279 /* For XMSS */
280 if ((r = sshkey_set_filename(private, filename)) != 0) {
281 fprintf(stderr, "Could not add filename to private key: %s (%s)\n",
282 filename, comment);
283 goto out;
284 }
285 if (maxsign && minleft &&
286 (r = ssh_fetch_identitylist(agent_fd, &idlist)) == 0) {
287 for (i = 0; i < idlist->nkeys; i++) {
288 if (!sshkey_equal_public(idlist->keys[i], private))
289 continue;
290 left = sshkey_signatures_left(idlist->keys[i]);
291 if (left < minleft) {
292 fprintf(stderr,
293 "Only %d signatures left.\n", left);
294 break;
295 }
296 fprintf(stderr, "Skipping update: ");
297 if (left == minleft) {
298 fprintf(stderr,
299 "required signatures left (%d).\n", left);
300 } else {
301 fprintf(stderr,
302 "more signatures left (%d) than"
303 " required (%d).\n", left, minleft);
304 }
305 ssh_free_identitylist(idlist);
306 goto out;
307 }
308 ssh_free_identitylist(idlist);
309 }
310
311 if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
312 lifetime, confirm, maxsign)) == 0) {
313 fprintf(stderr, "Identity added: %s (%s)\n", filename, comment);
314 ret = 0;
315 if (lifetime != 0)
316 fprintf(stderr,
317 "Lifetime set to %d seconds\n", lifetime);
318 if (confirm != 0)
319 fprintf(stderr,
320 "The user must confirm each use of the key\n");
321 } else {
322 fprintf(stderr, "Could not add identity \"%s\": %s\n",
323 filename, ssh_err(r));
324 }
325
326 /* Skip trying to load the cert if requested */
327 if (key_only)
328 goto out;
329
330 /* Now try to add the certificate flavour too */
331 xasprintf(&certpath, "%s-cert.pub", filename);
332 if ((r = sshkey_load_public(certpath, &cert, NULL)) != 0) {
333 if (r != SSH_ERR_SYSTEM_ERROR || errno != ENOENT)
334 error("Failed to load certificate \"%s\": %s",
335 certpath, ssh_err(r));
336 goto out;
337 }
338
339 if (!sshkey_equal_public(cert, private)) {
340 error("Certificate %s does not match private key %s",
341 certpath, filename);
342 sshkey_free(cert);
343 goto out;
344 }
345
346 /* Graft with private bits */
347 if ((r = sshkey_to_certified(private)) != 0) {
348 error("%s: sshkey_to_certified: %s", __func__, ssh_err(r));
349 sshkey_free(cert);
350 goto out;
351 }
352 if ((r = sshkey_cert_copy(cert, private)) != 0) {
353 error("%s: sshkey_cert_copy: %s", __func__, ssh_err(r));
354 sshkey_free(cert);
355 goto out;
356 }
357 sshkey_free(cert);
358
359 if ((r = ssh_add_identity_constrained(agent_fd, private, comment,
360 lifetime, confirm, maxsign)) != 0) {
361 error("Certificate %s (%s) add failed: %s", certpath,
362 private->cert->key_id, ssh_err(r));
363 goto out;
364 }
365 fprintf(stderr, "Certificate added: %s (%s)\n", certpath,
366 private->cert->key_id);
367 if (lifetime != 0)
368 fprintf(stderr, "Lifetime set to %d seconds\n", lifetime);
369 if (confirm != 0)
370 fprintf(stderr, "The user must confirm each use of the key\n");
371 out:
372 free(certpath);
373 free(comment);
374 sshkey_free(private);
375
376 return ret;
377 }
378
379 static int
update_card(int agent_fd,int add,const char * id)380 update_card(int agent_fd, int add, const char *id)
381 {
382 char *pin = NULL;
383 int r, ret = -1;
384
385 if (add) {
386 if ((pin = read_passphrase("Enter passphrase for PKCS#11: ",
387 RP_ALLOW_STDIN)) == NULL)
388 return -1;
389 }
390
391 if ((r = ssh_update_card(agent_fd, add, id, pin == NULL ? "" : pin,
392 lifetime, confirm)) == 0) {
393 fprintf(stderr, "Card %s: %s\n",
394 add ? "added" : "removed", id);
395 ret = 0;
396 } else {
397 fprintf(stderr, "Could not %s card \"%s\": %s\n",
398 add ? "add" : "remove", id, ssh_err(r));
399 ret = -1;
400 }
401 free(pin);
402 return ret;
403 }
404
405 static int
list_identities(int agent_fd,int do_fp)406 list_identities(int agent_fd, int do_fp)
407 {
408 char *fp;
409 int r;
410 struct ssh_identitylist *idlist;
411 u_int32_t left;
412 size_t i;
413
414 if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) {
415 if (r != SSH_ERR_AGENT_NO_IDENTITIES)
416 fprintf(stderr, "error fetching identities: %s\n",
417 ssh_err(r));
418 else
419 printf("The agent has no identities.\n");
420 return -1;
421 }
422 for (i = 0; i < idlist->nkeys; i++) {
423 if (do_fp) {
424 fp = sshkey_fingerprint(idlist->keys[i],
425 fingerprint_hash, SSH_FP_DEFAULT);
426 printf("%u %s %s (%s)\n", sshkey_size(idlist->keys[i]),
427 fp == NULL ? "(null)" : fp, idlist->comments[i],
428 sshkey_type(idlist->keys[i]));
429 free(fp);
430 } else {
431 if ((r = sshkey_write(idlist->keys[i], stdout)) != 0) {
432 fprintf(stderr, "sshkey_write: %s\n",
433 ssh_err(r));
434 continue;
435 }
436 fprintf(stdout, " %s", idlist->comments[i]);
437 left = sshkey_signatures_left(idlist->keys[i]);
438 if (left > 0)
439 fprintf(stdout,
440 " [signatures left %d]", left);
441 fprintf(stdout, "\n");
442 }
443 }
444 ssh_free_identitylist(idlist);
445 return 0;
446 }
447
448 static int
lock_agent(int agent_fd,int lock)449 lock_agent(int agent_fd, int lock)
450 {
451 char prompt[100], *p1, *p2;
452 int r, passok = 1, ret = -1;
453
454 strlcpy(prompt, "Enter lock password: ", sizeof(prompt));
455 p1 = read_passphrase(prompt, RP_ALLOW_STDIN);
456 if (lock) {
457 strlcpy(prompt, "Again: ", sizeof prompt);
458 p2 = read_passphrase(prompt, RP_ALLOW_STDIN);
459 if (strcmp(p1, p2) != 0) {
460 fprintf(stderr, "Passwords do not match.\n");
461 passok = 0;
462 }
463 explicit_bzero(p2, strlen(p2));
464 free(p2);
465 }
466 if (passok) {
467 if ((r = ssh_lock_agent(agent_fd, lock, p1)) == 0) {
468 fprintf(stderr, "Agent %slocked.\n", lock ? "" : "un");
469 ret = 0;
470 } else {
471 fprintf(stderr, "Failed to %slock agent: %s\n",
472 lock ? "" : "un", ssh_err(r));
473 }
474 }
475 explicit_bzero(p1, strlen(p1));
476 free(p1);
477 return (ret);
478 }
479
480 static int
do_file(int agent_fd,int deleting,int key_only,char * file,int qflag)481 do_file(int agent_fd, int deleting, int key_only, char *file, int qflag)
482 {
483 if (deleting) {
484 if (delete_file(agent_fd, file, key_only, qflag) == -1)
485 return -1;
486 } else {
487 if (add_file(agent_fd, file, key_only, qflag) == -1)
488 return -1;
489 }
490 return 0;
491 }
492
493 static void
usage(void)494 usage(void)
495 {
496 fprintf(stderr, "usage: %s [options] [file ...]\n", __progname);
497 fprintf(stderr, "Options:\n");
498 fprintf(stderr, " -l List fingerprints of all identities.\n");
499 fprintf(stderr, " -E hash Specify hash algorithm used for fingerprints.\n");
500 fprintf(stderr, " -L List public key parameters of all identities.\n");
501 fprintf(stderr, " -k Load only keys and not certificates.\n");
502 fprintf(stderr, " -c Require confirmation to sign using identities\n");
503 fprintf(stderr, " -m minleft Maxsign is only changed if less than minleft are left (for XMSS)\n");
504 fprintf(stderr, " -M maxsign Maximum number of signatures allowed (for XMSS)\n");
505 fprintf(stderr, " -t life Set lifetime (in seconds) when adding identities.\n");
506 fprintf(stderr, " -d Delete identity.\n");
507 fprintf(stderr, " -D Delete all identities.\n");
508 fprintf(stderr, " -x Lock agent.\n");
509 fprintf(stderr, " -X Unlock agent.\n");
510 fprintf(stderr, " -s pkcs11 Add keys from PKCS#11 provider.\n");
511 fprintf(stderr, " -e pkcs11 Remove keys provided by PKCS#11 provider.\n");
512 fprintf(stderr, " -q Be quiet after a successful operation.\n");
513 }
514
515 int
main(int argc,char ** argv)516 main(int argc, char **argv)
517 {
518 extern char *optarg;
519 extern int optind;
520 int agent_fd;
521 char *pkcs11provider = NULL;
522 int r, i, ch, deleting = 0, ret = 0, key_only = 0;
523 int xflag = 0, lflag = 0, Dflag = 0, qflag = 0;
524
525 ssh_malloc_init(); /* must be called before any mallocs */
526 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
527 sanitise_stdfd();
528
529 __progname = ssh_get_progname(argv[0]);
530 seed_rng();
531
532 #ifdef WITH_OPENSSL
533 OpenSSL_add_all_algorithms();
534 #endif
535
536 setvbuf(stdout, NULL, _IOLBF, 0);
537
538 /* First, get a connection to the authentication agent. */
539 switch (r = ssh_get_authentication_socket(&agent_fd)) {
540 case 0:
541 break;
542 case SSH_ERR_AGENT_NOT_PRESENT:
543 fprintf(stderr, "Could not open a connection to your "
544 "authentication agent.\n");
545 exit(2);
546 default:
547 fprintf(stderr, "Error connecting to agent: %s\n", ssh_err(r));
548 exit(2);
549 }
550
551 while ((ch = getopt(argc, argv, "klLcdDxXE:e:M:m:qs:t:")) != -1) {
552 switch (ch) {
553 case 'E':
554 fingerprint_hash = ssh_digest_alg_by_name(optarg);
555 if (fingerprint_hash == -1)
556 fatal("Invalid hash algorithm \"%s\"", optarg);
557 break;
558 case 'k':
559 key_only = 1;
560 break;
561 case 'l':
562 case 'L':
563 if (lflag != 0)
564 fatal("-%c flag already specified", lflag);
565 lflag = ch;
566 break;
567 case 'x':
568 case 'X':
569 if (xflag != 0)
570 fatal("-%c flag already specified", xflag);
571 xflag = ch;
572 break;
573 case 'c':
574 confirm = 1;
575 break;
576 case 'm':
577 minleft = (int)strtonum(optarg, 1, UINT_MAX, NULL);
578 if (minleft == 0) {
579 usage();
580 ret = 1;
581 goto done;
582 }
583 break;
584 case 'M':
585 maxsign = (int)strtonum(optarg, 1, UINT_MAX, NULL);
586 if (maxsign == 0) {
587 usage();
588 ret = 1;
589 goto done;
590 }
591 break;
592 case 'd':
593 deleting = 1;
594 break;
595 case 'D':
596 Dflag = 1;
597 break;
598 case 's':
599 pkcs11provider = optarg;
600 break;
601 case 'e':
602 deleting = 1;
603 pkcs11provider = optarg;
604 break;
605 case 't':
606 if ((lifetime = convtime(optarg)) == -1) {
607 fprintf(stderr, "Invalid lifetime\n");
608 ret = 1;
609 goto done;
610 }
611 break;
612 case 'q':
613 qflag = 1;
614 break;
615 default:
616 usage();
617 ret = 1;
618 goto done;
619 }
620 }
621
622 if ((xflag != 0) + (lflag != 0) + (Dflag != 0) > 1)
623 fatal("Invalid combination of actions");
624 else if (xflag) {
625 if (lock_agent(agent_fd, xflag == 'x' ? 1 : 0) == -1)
626 ret = 1;
627 goto done;
628 } else if (lflag) {
629 if (list_identities(agent_fd, lflag == 'l' ? 1 : 0) == -1)
630 ret = 1;
631 goto done;
632 } else if (Dflag) {
633 if (delete_all(agent_fd) == -1)
634 ret = 1;
635 goto done;
636 }
637
638 argc -= optind;
639 argv += optind;
640 if (pkcs11provider != NULL) {
641 if (update_card(agent_fd, !deleting, pkcs11provider) == -1)
642 ret = 1;
643 goto done;
644 }
645 if (argc == 0) {
646 char buf[PATH_MAX];
647 struct passwd *pw;
648 struct stat st;
649 int count = 0;
650
651 if ((pw = getpwuid(getuid())) == NULL) {
652 fprintf(stderr, "No user found with uid %u\n",
653 (u_int)getuid());
654 ret = 1;
655 goto done;
656 }
657
658 for (i = 0; default_files[i]; i++) {
659 snprintf(buf, sizeof(buf), "%s/%s", pw->pw_dir,
660 default_files[i]);
661 if (stat(buf, &st) < 0)
662 continue;
663 if (do_file(agent_fd, deleting, key_only, buf,
664 qflag) == -1)
665 ret = 1;
666 else
667 count++;
668 }
669 if (count == 0)
670 ret = 1;
671 } else {
672 for (i = 0; i < argc; i++) {
673 if (do_file(agent_fd, deleting, key_only,
674 argv[i], qflag) == -1)
675 ret = 1;
676 }
677 }
678 clear_pass();
679
680 done:
681 ssh_close_authentication_socket(agent_fd);
682 return ret;
683 }
684