- jmc@cvs.openbsd.org 2006/07/18 07:50:40
[openssh-git.git] / authfile.c
blob53397ea53f45ca9bd405782cb4d77387e55477e4
1 /* $OpenBSD: authfile.c,v 1.70 2006/07/17 01:31:09 stevesk Exp $ */
2 /*
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 * This file contains functions for reading and writing identity files, and
7 * for reading the passphrase from the user.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 2000 Markus Friedl. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
20 * are met:
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #include "includes.h"
41 #include <sys/types.h>
42 #include <sys/stat.h>
44 #include <openssl/err.h>
45 #include <openssl/evp.h>
46 #include <openssl/pem.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <unistd.h>
52 #include "cipher.h"
53 #include "xmalloc.h"
54 #include "buffer.h"
55 #include "bufaux.h"
56 #include "key.h"
57 #include "ssh.h"
58 #include "log.h"
59 #include "authfile.h"
60 #include "rsa.h"
61 #include "misc.h"
62 #include "atomicio.h"
64 /* Version identification string for SSH v1 identity files. */
65 static const char authfile_id_string[] =
66 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
69 * Saves the authentication (private) key in a file, encrypting it with
70 * passphrase. The identification of the file (lowest 64 bits of n) will
71 * precede the key to provide identification of the key without needing a
72 * passphrase.
75 static int
76 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
77 const char *comment)
79 Buffer buffer, encrypted;
80 u_char buf[100], *cp;
81 int fd, i, cipher_num;
82 CipherContext ciphercontext;
83 Cipher *cipher;
84 u_int32_t rnd;
87 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
88 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
90 cipher_num = (strcmp(passphrase, "") == 0) ?
91 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
92 if ((cipher = cipher_by_number(cipher_num)) == NULL)
93 fatal("save_private_key_rsa: bad cipher");
95 /* This buffer is used to built the secret part of the private key. */
96 buffer_init(&buffer);
98 /* Put checkbytes for checking passphrase validity. */
99 rnd = arc4random();
100 buf[0] = rnd & 0xff;
101 buf[1] = (rnd >> 8) & 0xff;
102 buf[2] = buf[0];
103 buf[3] = buf[1];
104 buffer_append(&buffer, buf, 4);
107 * Store the private key (n and e will not be stored because they
108 * will be stored in plain text, and storing them also in encrypted
109 * format would just give known plaintext).
111 buffer_put_bignum(&buffer, key->rsa->d);
112 buffer_put_bignum(&buffer, key->rsa->iqmp);
113 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
114 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
116 /* Pad the part to be encrypted until its size is a multiple of 8. */
117 while (buffer_len(&buffer) % 8 != 0)
118 buffer_put_char(&buffer, 0);
120 /* This buffer will be used to contain the data in the file. */
121 buffer_init(&encrypted);
123 /* First store keyfile id string. */
124 for (i = 0; authfile_id_string[i]; i++)
125 buffer_put_char(&encrypted, authfile_id_string[i]);
126 buffer_put_char(&encrypted, 0);
128 /* Store cipher type. */
129 buffer_put_char(&encrypted, cipher_num);
130 buffer_put_int(&encrypted, 0); /* For future extension */
132 /* Store public key. This will be in plain text. */
133 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
134 buffer_put_bignum(&encrypted, key->rsa->n);
135 buffer_put_bignum(&encrypted, key->rsa->e);
136 buffer_put_cstring(&encrypted, comment);
138 /* Allocate space for the private part of the key in the buffer. */
139 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
141 cipher_set_key_string(&ciphercontext, cipher, passphrase,
142 CIPHER_ENCRYPT);
143 cipher_crypt(&ciphercontext, cp,
144 buffer_ptr(&buffer), buffer_len(&buffer));
145 cipher_cleanup(&ciphercontext);
146 memset(&ciphercontext, 0, sizeof(ciphercontext));
148 /* Destroy temporary data. */
149 memset(buf, 0, sizeof(buf));
150 buffer_free(&buffer);
152 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
153 if (fd < 0) {
154 error("open %s failed: %s.", filename, strerror(errno));
155 buffer_free(&encrypted);
156 return 0;
158 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
159 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
160 error("write to key file %s failed: %s", filename,
161 strerror(errno));
162 buffer_free(&encrypted);
163 close(fd);
164 unlink(filename);
165 return 0;
167 close(fd);
168 buffer_free(&encrypted);
169 return 1;
172 /* save SSH v2 key in OpenSSL PEM format */
173 static int
174 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
175 const char *comment)
177 FILE *fp;
178 int fd;
179 int success = 0;
180 int len = strlen(_passphrase);
181 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
182 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
184 if (len > 0 && len <= 4) {
185 error("passphrase too short: have %d bytes, need > 4", len);
186 return 0;
188 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
189 if (fd < 0) {
190 error("open %s failed: %s.", filename, strerror(errno));
191 return 0;
193 fp = fdopen(fd, "w");
194 if (fp == NULL ) {
195 error("fdopen %s failed: %s.", filename, strerror(errno));
196 close(fd);
197 return 0;
199 switch (key->type) {
200 case KEY_DSA:
201 success = PEM_write_DSAPrivateKey(fp, key->dsa,
202 cipher, passphrase, len, NULL, NULL);
203 break;
204 case KEY_RSA:
205 success = PEM_write_RSAPrivateKey(fp, key->rsa,
206 cipher, passphrase, len, NULL, NULL);
207 break;
209 fclose(fp);
210 return success;
214 key_save_private(Key *key, const char *filename, const char *passphrase,
215 const char *comment)
217 switch (key->type) {
218 case KEY_RSA1:
219 return key_save_private_rsa1(key, filename, passphrase,
220 comment);
221 case KEY_DSA:
222 case KEY_RSA:
223 return key_save_private_pem(key, filename, passphrase,
224 comment);
225 default:
226 break;
228 error("key_save_private: cannot save key type %d", key->type);
229 return 0;
233 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
234 * encountered (the file does not exist or is not readable), and the key
235 * otherwise.
238 static Key *
239 key_load_public_rsa1(int fd, const char *filename, char **commentp)
241 Buffer buffer;
242 Key *pub;
243 struct stat st;
244 char *cp;
245 u_int i;
246 size_t len;
248 if (fstat(fd, &st) < 0) {
249 error("fstat for key file %.200s failed: %.100s",
250 filename, strerror(errno));
251 return NULL;
253 if (st.st_size > 1*1024*1024) {
254 error("key file %.200s too large", filename);
255 return NULL;
257 len = (size_t)st.st_size; /* truncated */
259 buffer_init(&buffer);
260 cp = buffer_append_space(&buffer, len);
262 if (atomicio(read, fd, cp, len) != len) {
263 debug("Read from key file %.200s failed: %.100s", filename,
264 strerror(errno));
265 buffer_free(&buffer);
266 return NULL;
269 /* Check that it is at least big enough to contain the ID string. */
270 if (len < sizeof(authfile_id_string)) {
271 debug3("Not a RSA1 key file %.200s.", filename);
272 buffer_free(&buffer);
273 return NULL;
276 * Make sure it begins with the id string. Consume the id string
277 * from the buffer.
279 for (i = 0; i < sizeof(authfile_id_string); i++)
280 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
281 debug3("Not a RSA1 key file %.200s.", filename);
282 buffer_free(&buffer);
283 return NULL;
285 /* Skip cipher type and reserved data. */
286 (void) buffer_get_char(&buffer); /* cipher type */
287 (void) buffer_get_int(&buffer); /* reserved */
289 /* Read the public key from the buffer. */
290 (void) buffer_get_int(&buffer);
291 pub = key_new(KEY_RSA1);
292 buffer_get_bignum(&buffer, pub->rsa->n);
293 buffer_get_bignum(&buffer, pub->rsa->e);
294 if (commentp)
295 *commentp = buffer_get_string(&buffer, NULL);
296 /* The encrypted private part is not parsed by this function. */
298 buffer_free(&buffer);
299 return pub;
302 /* load public key from private-key file, works only for SSH v1 */
303 Key *
304 key_load_public_type(int type, const char *filename, char **commentp)
306 Key *pub;
307 int fd;
309 if (type == KEY_RSA1) {
310 fd = open(filename, O_RDONLY);
311 if (fd < 0)
312 return NULL;
313 pub = key_load_public_rsa1(fd, filename, commentp);
314 close(fd);
315 return pub;
317 return NULL;
321 * Loads the private key from the file. Returns 0 if an error is encountered
322 * (file does not exist or is not readable, or passphrase is bad). This
323 * initializes the private key.
324 * Assumes we are called under uid of the owner of the file.
327 static Key *
328 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
329 char **commentp)
331 u_int i;
332 int check1, check2, cipher_type;
333 size_t len;
334 Buffer buffer, decrypted;
335 u_char *cp;
336 CipherContext ciphercontext;
337 Cipher *cipher;
338 Key *prv = NULL;
339 struct stat st;
341 if (fstat(fd, &st) < 0) {
342 error("fstat for key file %.200s failed: %.100s",
343 filename, strerror(errno));
344 close(fd);
345 return NULL;
347 if (st.st_size > 1*1024*1024) {
348 error("key file %.200s too large", filename);
349 close(fd);
350 return (NULL);
352 len = (size_t)st.st_size; /* truncated */
354 buffer_init(&buffer);
355 cp = buffer_append_space(&buffer, len);
357 if (atomicio(read, fd, cp, len) != len) {
358 debug("Read from key file %.200s failed: %.100s", filename,
359 strerror(errno));
360 buffer_free(&buffer);
361 close(fd);
362 return NULL;
365 /* Check that it is at least big enough to contain the ID string. */
366 if (len < sizeof(authfile_id_string)) {
367 debug3("Not a RSA1 key file %.200s.", filename);
368 buffer_free(&buffer);
369 close(fd);
370 return NULL;
373 * Make sure it begins with the id string. Consume the id string
374 * from the buffer.
376 for (i = 0; i < sizeof(authfile_id_string); i++)
377 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
378 debug3("Not a RSA1 key file %.200s.", filename);
379 buffer_free(&buffer);
380 close(fd);
381 return NULL;
384 /* Read cipher type. */
385 cipher_type = buffer_get_char(&buffer);
386 (void) buffer_get_int(&buffer); /* Reserved data. */
388 /* Read the public key from the buffer. */
389 (void) buffer_get_int(&buffer);
390 prv = key_new_private(KEY_RSA1);
392 buffer_get_bignum(&buffer, prv->rsa->n);
393 buffer_get_bignum(&buffer, prv->rsa->e);
394 if (commentp)
395 *commentp = buffer_get_string(&buffer, NULL);
396 else
397 xfree(buffer_get_string(&buffer, NULL));
399 /* Check that it is a supported cipher. */
400 cipher = cipher_by_number(cipher_type);
401 if (cipher == NULL) {
402 debug("Unsupported cipher %d used in key file %.200s.",
403 cipher_type, filename);
404 buffer_free(&buffer);
405 goto fail;
407 /* Initialize space for decrypted data. */
408 buffer_init(&decrypted);
409 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
411 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
412 cipher_set_key_string(&ciphercontext, cipher, passphrase,
413 CIPHER_DECRYPT);
414 cipher_crypt(&ciphercontext, cp,
415 buffer_ptr(&buffer), buffer_len(&buffer));
416 cipher_cleanup(&ciphercontext);
417 memset(&ciphercontext, 0, sizeof(ciphercontext));
418 buffer_free(&buffer);
420 check1 = buffer_get_char(&decrypted);
421 check2 = buffer_get_char(&decrypted);
422 if (check1 != buffer_get_char(&decrypted) ||
423 check2 != buffer_get_char(&decrypted)) {
424 if (strcmp(passphrase, "") != 0)
425 debug("Bad passphrase supplied for key file %.200s.",
426 filename);
427 /* Bad passphrase. */
428 buffer_free(&decrypted);
429 goto fail;
431 /* Read the rest of the private key. */
432 buffer_get_bignum(&decrypted, prv->rsa->d);
433 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
434 /* in SSL and SSH v1 p and q are exchanged */
435 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
436 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
438 /* calculate p-1 and q-1 */
439 rsa_generate_additional_parameters(prv->rsa);
441 buffer_free(&decrypted);
443 /* enable blinding */
444 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
445 error("key_load_private_rsa1: RSA_blinding_on failed");
446 goto fail;
448 close(fd);
449 return prv;
451 fail:
452 if (commentp)
453 xfree(*commentp);
454 close(fd);
455 key_free(prv);
456 return NULL;
459 Key *
460 key_load_private_pem(int fd, int type, const char *passphrase,
461 char **commentp)
463 FILE *fp;
464 EVP_PKEY *pk = NULL;
465 Key *prv = NULL;
466 char *name = "<no key>";
468 fp = fdopen(fd, "r");
469 if (fp == NULL) {
470 error("fdopen failed: %s", strerror(errno));
471 close(fd);
472 return NULL;
474 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
475 if (pk == NULL) {
476 debug("PEM_read_PrivateKey failed");
477 (void)ERR_get_error();
478 } else if (pk->type == EVP_PKEY_RSA &&
479 (type == KEY_UNSPEC||type==KEY_RSA)) {
480 prv = key_new(KEY_UNSPEC);
481 prv->rsa = EVP_PKEY_get1_RSA(pk);
482 prv->type = KEY_RSA;
483 name = "rsa w/o comment";
484 #ifdef DEBUG_PK
485 RSA_print_fp(stderr, prv->rsa, 8);
486 #endif
487 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
488 error("key_load_private_pem: RSA_blinding_on failed");
489 key_free(prv);
490 prv = NULL;
492 } else if (pk->type == EVP_PKEY_DSA &&
493 (type == KEY_UNSPEC||type==KEY_DSA)) {
494 prv = key_new(KEY_UNSPEC);
495 prv->dsa = EVP_PKEY_get1_DSA(pk);
496 prv->type = KEY_DSA;
497 name = "dsa w/o comment";
498 #ifdef DEBUG_PK
499 DSA_print_fp(stderr, prv->dsa, 8);
500 #endif
501 } else {
502 error("PEM_read_PrivateKey: mismatch or "
503 "unknown EVP_PKEY save_type %d", pk->save_type);
505 fclose(fp);
506 if (pk != NULL)
507 EVP_PKEY_free(pk);
508 if (prv != NULL && commentp)
509 *commentp = xstrdup(name);
510 debug("read PEM private key done: type %s",
511 prv ? key_type(prv) : "<unknown>");
512 return prv;
516 key_perm_ok(int fd, const char *filename)
518 struct stat st;
520 if (fstat(fd, &st) < 0)
521 return 0;
523 * if a key owned by the user is accessed, then we check the
524 * permissions of the file. if the key owned by a different user,
525 * then we don't care.
527 #ifdef HAVE_CYGWIN
528 if (check_ntsec(filename))
529 #endif
530 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
531 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
532 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
533 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
534 error("Permissions 0%3.3o for '%s' are too open.",
535 (u_int)st.st_mode & 0777, filename);
536 error("It is recommended that your private key files are NOT accessible by others.");
537 error("This private key will be ignored.");
538 return 0;
540 return 1;
543 Key *
544 key_load_private_type(int type, const char *filename, const char *passphrase,
545 char **commentp, int *perm_ok)
547 int fd;
549 fd = open(filename, O_RDONLY);
550 if (fd < 0)
551 return NULL;
552 if (!key_perm_ok(fd, filename)) {
553 if (perm_ok != NULL)
554 *perm_ok = 0;
555 error("bad permissions: ignore key: %s", filename);
556 close(fd);
557 return NULL;
559 if (perm_ok != NULL)
560 *perm_ok = 1;
561 switch (type) {
562 case KEY_RSA1:
563 return key_load_private_rsa1(fd, filename, passphrase,
564 commentp);
565 /* closes fd */
566 case KEY_DSA:
567 case KEY_RSA:
568 case KEY_UNSPEC:
569 return key_load_private_pem(fd, type, passphrase, commentp);
570 /* closes fd */
571 default:
572 close(fd);
573 break;
575 return NULL;
578 Key *
579 key_load_private(const char *filename, const char *passphrase,
580 char **commentp)
582 Key *pub, *prv;
583 int fd;
585 fd = open(filename, O_RDONLY);
586 if (fd < 0)
587 return NULL;
588 if (!key_perm_ok(fd, filename)) {
589 error("bad permissions: ignore key: %s", filename);
590 close(fd);
591 return NULL;
593 pub = key_load_public_rsa1(fd, filename, commentp);
594 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
595 if (pub == NULL) {
596 /* closes fd */
597 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
598 /* use the filename as a comment for PEM */
599 if (commentp && prv)
600 *commentp = xstrdup(filename);
601 } else {
602 /* it's a SSH v1 key if the public key part is readable */
603 key_free(pub);
604 /* closes fd */
605 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
607 return prv;
610 static int
611 key_try_load_public(Key *k, const char *filename, char **commentp)
613 FILE *f;
614 char line[SSH_MAX_PUBKEY_BYTES];
615 char *cp;
616 u_long linenum = 0;
618 f = fopen(filename, "r");
619 if (f != NULL) {
620 while (read_keyfile_line(f, filename, line, sizeof(line),
621 &linenum) != -1) {
622 cp = line;
623 switch (*cp) {
624 case '#':
625 case '\n':
626 case '\0':
627 continue;
629 /* Skip leading whitespace. */
630 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
632 if (*cp) {
633 if (key_read(k, &cp) == 1) {
634 if (commentp)
635 *commentp=xstrdup(filename);
636 fclose(f);
637 return 1;
641 fclose(f);
643 return 0;
646 /* load public key from ssh v1 private or any pubkey file */
647 Key *
648 key_load_public(const char *filename, char **commentp)
650 Key *pub;
651 char file[MAXPATHLEN];
653 /* try rsa1 private key */
654 pub = key_load_public_type(KEY_RSA1, filename, commentp);
655 if (pub != NULL)
656 return pub;
658 /* try rsa1 public key */
659 pub = key_new(KEY_RSA1);
660 if (key_try_load_public(pub, filename, commentp) == 1)
661 return pub;
662 key_free(pub);
664 /* try ssh2 public key */
665 pub = key_new(KEY_UNSPEC);
666 if (key_try_load_public(pub, filename, commentp) == 1)
667 return pub;
668 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
669 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
670 (key_try_load_public(pub, file, commentp) == 1))
671 return pub;
672 key_free(pub);
673 return NULL;