- djm@cvs.openbsd.org 2008/12/07 22:17:48
[openssh-git.git] / authfile.c
blob735c6478096495fa392c74d1a1cdb8f73a405f90
1 /* $OpenBSD: authfile.c,v 1.76 2006/08/03 03:34:41 deraadt 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>
43 #include <sys/param.h>
44 #include <sys/uio.h>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/pem.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <stdarg.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
58 #include "xmalloc.h"
59 #include "cipher.h"
60 #include "buffer.h"
61 #include "key.h"
62 #include "ssh.h"
63 #include "log.h"
64 #include "authfile.h"
65 #include "rsa.h"
66 #include "misc.h"
67 #include "atomicio.h"
69 /* Version identification string for SSH v1 identity files. */
70 static const char authfile_id_string[] =
71 "SSH PRIVATE KEY FILE FORMAT 1.1\n";
74 * Saves the authentication (private) key in a file, encrypting it with
75 * passphrase. The identification of the file (lowest 64 bits of n) will
76 * precede the key to provide identification of the key without needing a
77 * passphrase.
80 static int
81 key_save_private_rsa1(Key *key, const char *filename, const char *passphrase,
82 const char *comment)
84 Buffer buffer, encrypted;
85 u_char buf[100], *cp;
86 int fd, i, cipher_num;
87 CipherContext ciphercontext;
88 Cipher *cipher;
89 u_int32_t rnd;
92 * If the passphrase is empty, use SSH_CIPHER_NONE to ease converting
93 * to another cipher; otherwise use SSH_AUTHFILE_CIPHER.
95 cipher_num = (strcmp(passphrase, "") == 0) ?
96 SSH_CIPHER_NONE : SSH_AUTHFILE_CIPHER;
97 if ((cipher = cipher_by_number(cipher_num)) == NULL)
98 fatal("save_private_key_rsa: bad cipher");
100 /* This buffer is used to built the secret part of the private key. */
101 buffer_init(&buffer);
103 /* Put checkbytes for checking passphrase validity. */
104 rnd = arc4random();
105 buf[0] = rnd & 0xff;
106 buf[1] = (rnd >> 8) & 0xff;
107 buf[2] = buf[0];
108 buf[3] = buf[1];
109 buffer_append(&buffer, buf, 4);
112 * Store the private key (n and e will not be stored because they
113 * will be stored in plain text, and storing them also in encrypted
114 * format would just give known plaintext).
116 buffer_put_bignum(&buffer, key->rsa->d);
117 buffer_put_bignum(&buffer, key->rsa->iqmp);
118 buffer_put_bignum(&buffer, key->rsa->q); /* reverse from SSL p */
119 buffer_put_bignum(&buffer, key->rsa->p); /* reverse from SSL q */
121 /* Pad the part to be encrypted until its size is a multiple of 8. */
122 while (buffer_len(&buffer) % 8 != 0)
123 buffer_put_char(&buffer, 0);
125 /* This buffer will be used to contain the data in the file. */
126 buffer_init(&encrypted);
128 /* First store keyfile id string. */
129 for (i = 0; authfile_id_string[i]; i++)
130 buffer_put_char(&encrypted, authfile_id_string[i]);
131 buffer_put_char(&encrypted, 0);
133 /* Store cipher type. */
134 buffer_put_char(&encrypted, cipher_num);
135 buffer_put_int(&encrypted, 0); /* For future extension */
137 /* Store public key. This will be in plain text. */
138 buffer_put_int(&encrypted, BN_num_bits(key->rsa->n));
139 buffer_put_bignum(&encrypted, key->rsa->n);
140 buffer_put_bignum(&encrypted, key->rsa->e);
141 buffer_put_cstring(&encrypted, comment);
143 /* Allocate space for the private part of the key in the buffer. */
144 cp = buffer_append_space(&encrypted, buffer_len(&buffer));
146 cipher_set_key_string(&ciphercontext, cipher, passphrase,
147 CIPHER_ENCRYPT);
148 cipher_crypt(&ciphercontext, cp,
149 buffer_ptr(&buffer), buffer_len(&buffer));
150 cipher_cleanup(&ciphercontext);
151 memset(&ciphercontext, 0, sizeof(ciphercontext));
153 /* Destroy temporary data. */
154 memset(buf, 0, sizeof(buf));
155 buffer_free(&buffer);
157 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
158 if (fd < 0) {
159 error("open %s failed: %s.", filename, strerror(errno));
160 buffer_free(&encrypted);
161 return 0;
163 if (atomicio(vwrite, fd, buffer_ptr(&encrypted),
164 buffer_len(&encrypted)) != buffer_len(&encrypted)) {
165 error("write to key file %s failed: %s", filename,
166 strerror(errno));
167 buffer_free(&encrypted);
168 close(fd);
169 unlink(filename);
170 return 0;
172 close(fd);
173 buffer_free(&encrypted);
174 return 1;
177 /* save SSH v2 key in OpenSSL PEM format */
178 static int
179 key_save_private_pem(Key *key, const char *filename, const char *_passphrase,
180 const char *comment)
182 FILE *fp;
183 int fd;
184 int success = 0;
185 int len = strlen(_passphrase);
186 u_char *passphrase = (len > 0) ? (u_char *)_passphrase : NULL;
187 const EVP_CIPHER *cipher = (len > 0) ? EVP_des_ede3_cbc() : NULL;
189 if (len > 0 && len <= 4) {
190 error("passphrase too short: have %d bytes, need > 4", len);
191 return 0;
193 fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600);
194 if (fd < 0) {
195 error("open %s failed: %s.", filename, strerror(errno));
196 return 0;
198 fp = fdopen(fd, "w");
199 if (fp == NULL) {
200 error("fdopen %s failed: %s.", filename, strerror(errno));
201 close(fd);
202 return 0;
204 switch (key->type) {
205 case KEY_DSA:
206 success = PEM_write_DSAPrivateKey(fp, key->dsa,
207 cipher, passphrase, len, NULL, NULL);
208 break;
209 case KEY_RSA:
210 success = PEM_write_RSAPrivateKey(fp, key->rsa,
211 cipher, passphrase, len, NULL, NULL);
212 break;
214 fclose(fp);
215 return success;
219 key_save_private(Key *key, const char *filename, const char *passphrase,
220 const char *comment)
222 switch (key->type) {
223 case KEY_RSA1:
224 return key_save_private_rsa1(key, filename, passphrase,
225 comment);
226 case KEY_DSA:
227 case KEY_RSA:
228 return key_save_private_pem(key, filename, passphrase,
229 comment);
230 default:
231 break;
233 error("key_save_private: cannot save key type %d", key->type);
234 return 0;
238 * Loads the public part of the ssh v1 key file. Returns NULL if an error was
239 * encountered (the file does not exist or is not readable), and the key
240 * otherwise.
243 static Key *
244 key_load_public_rsa1(int fd, const char *filename, char **commentp)
246 Buffer buffer;
247 Key *pub;
248 struct stat st;
249 char *cp;
250 u_int i;
251 size_t len;
253 if (fstat(fd, &st) < 0) {
254 error("fstat for key file %.200s failed: %.100s",
255 filename, strerror(errno));
256 return NULL;
258 if (st.st_size > 1*1024*1024) {
259 error("key file %.200s too large", filename);
260 return NULL;
262 len = (size_t)st.st_size; /* truncated */
264 buffer_init(&buffer);
265 cp = buffer_append_space(&buffer, len);
267 if (atomicio(read, fd, cp, len) != len) {
268 debug("Read from key file %.200s failed: %.100s", filename,
269 strerror(errno));
270 buffer_free(&buffer);
271 return NULL;
274 /* Check that it is at least big enough to contain the ID string. */
275 if (len < sizeof(authfile_id_string)) {
276 debug3("Not a RSA1 key file %.200s.", filename);
277 buffer_free(&buffer);
278 return NULL;
281 * Make sure it begins with the id string. Consume the id string
282 * from the buffer.
284 for (i = 0; i < sizeof(authfile_id_string); i++)
285 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
286 debug3("Not a RSA1 key file %.200s.", filename);
287 buffer_free(&buffer);
288 return NULL;
290 /* Skip cipher type and reserved data. */
291 (void) buffer_get_char(&buffer); /* cipher type */
292 (void) buffer_get_int(&buffer); /* reserved */
294 /* Read the public key from the buffer. */
295 (void) buffer_get_int(&buffer);
296 pub = key_new(KEY_RSA1);
297 buffer_get_bignum(&buffer, pub->rsa->n);
298 buffer_get_bignum(&buffer, pub->rsa->e);
299 if (commentp)
300 *commentp = buffer_get_string(&buffer, NULL);
301 /* The encrypted private part is not parsed by this function. */
303 buffer_free(&buffer);
304 return pub;
307 /* load public key from private-key file, works only for SSH v1 */
308 Key *
309 key_load_public_type(int type, const char *filename, char **commentp)
311 Key *pub;
312 int fd;
314 if (type == KEY_RSA1) {
315 fd = open(filename, O_RDONLY);
316 if (fd < 0)
317 return NULL;
318 pub = key_load_public_rsa1(fd, filename, commentp);
319 close(fd);
320 return pub;
322 return NULL;
326 * Loads the private key from the file. Returns 0 if an error is encountered
327 * (file does not exist or is not readable, or passphrase is bad). This
328 * initializes the private key.
329 * Assumes we are called under uid of the owner of the file.
332 static Key *
333 key_load_private_rsa1(int fd, const char *filename, const char *passphrase,
334 char **commentp)
336 u_int i;
337 int check1, check2, cipher_type;
338 size_t len;
339 Buffer buffer, decrypted;
340 u_char *cp;
341 CipherContext ciphercontext;
342 Cipher *cipher;
343 Key *prv = NULL;
344 struct stat st;
346 if (fstat(fd, &st) < 0) {
347 error("fstat for key file %.200s failed: %.100s",
348 filename, strerror(errno));
349 close(fd);
350 return NULL;
352 if (st.st_size > 1*1024*1024) {
353 error("key file %.200s too large", filename);
354 close(fd);
355 return (NULL);
357 len = (size_t)st.st_size; /* truncated */
359 buffer_init(&buffer);
360 cp = buffer_append_space(&buffer, len);
362 if (atomicio(read, fd, cp, len) != len) {
363 debug("Read from key file %.200s failed: %.100s", filename,
364 strerror(errno));
365 buffer_free(&buffer);
366 close(fd);
367 return NULL;
370 /* Check that it is at least big enough to contain the ID string. */
371 if (len < sizeof(authfile_id_string)) {
372 debug3("Not a RSA1 key file %.200s.", filename);
373 buffer_free(&buffer);
374 close(fd);
375 return NULL;
378 * Make sure it begins with the id string. Consume the id string
379 * from the buffer.
381 for (i = 0; i < sizeof(authfile_id_string); i++)
382 if (buffer_get_char(&buffer) != authfile_id_string[i]) {
383 debug3("Not a RSA1 key file %.200s.", filename);
384 buffer_free(&buffer);
385 close(fd);
386 return NULL;
389 /* Read cipher type. */
390 cipher_type = buffer_get_char(&buffer);
391 (void) buffer_get_int(&buffer); /* Reserved data. */
393 /* Read the public key from the buffer. */
394 (void) buffer_get_int(&buffer);
395 prv = key_new_private(KEY_RSA1);
397 buffer_get_bignum(&buffer, prv->rsa->n);
398 buffer_get_bignum(&buffer, prv->rsa->e);
399 if (commentp)
400 *commentp = buffer_get_string(&buffer, NULL);
401 else
402 xfree(buffer_get_string(&buffer, NULL));
404 /* Check that it is a supported cipher. */
405 cipher = cipher_by_number(cipher_type);
406 if (cipher == NULL) {
407 debug("Unsupported cipher %d used in key file %.200s.",
408 cipher_type, filename);
409 buffer_free(&buffer);
410 goto fail;
412 /* Initialize space for decrypted data. */
413 buffer_init(&decrypted);
414 cp = buffer_append_space(&decrypted, buffer_len(&buffer));
416 /* Rest of the buffer is encrypted. Decrypt it using the passphrase. */
417 cipher_set_key_string(&ciphercontext, cipher, passphrase,
418 CIPHER_DECRYPT);
419 cipher_crypt(&ciphercontext, cp,
420 buffer_ptr(&buffer), buffer_len(&buffer));
421 cipher_cleanup(&ciphercontext);
422 memset(&ciphercontext, 0, sizeof(ciphercontext));
423 buffer_free(&buffer);
425 check1 = buffer_get_char(&decrypted);
426 check2 = buffer_get_char(&decrypted);
427 if (check1 != buffer_get_char(&decrypted) ||
428 check2 != buffer_get_char(&decrypted)) {
429 if (strcmp(passphrase, "") != 0)
430 debug("Bad passphrase supplied for key file %.200s.",
431 filename);
432 /* Bad passphrase. */
433 buffer_free(&decrypted);
434 goto fail;
436 /* Read the rest of the private key. */
437 buffer_get_bignum(&decrypted, prv->rsa->d);
438 buffer_get_bignum(&decrypted, prv->rsa->iqmp); /* u */
439 /* in SSL and SSH v1 p and q are exchanged */
440 buffer_get_bignum(&decrypted, prv->rsa->q); /* p */
441 buffer_get_bignum(&decrypted, prv->rsa->p); /* q */
443 /* calculate p-1 and q-1 */
444 rsa_generate_additional_parameters(prv->rsa);
446 buffer_free(&decrypted);
448 /* enable blinding */
449 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
450 error("key_load_private_rsa1: RSA_blinding_on failed");
451 goto fail;
453 close(fd);
454 return prv;
456 fail:
457 if (commentp)
458 xfree(*commentp);
459 close(fd);
460 key_free(prv);
461 return NULL;
464 Key *
465 key_load_private_pem(int fd, int type, const char *passphrase,
466 char **commentp)
468 FILE *fp;
469 EVP_PKEY *pk = NULL;
470 Key *prv = NULL;
471 char *name = "<no key>";
473 fp = fdopen(fd, "r");
474 if (fp == NULL) {
475 error("fdopen failed: %s", strerror(errno));
476 close(fd);
477 return NULL;
479 pk = PEM_read_PrivateKey(fp, NULL, NULL, (char *)passphrase);
480 if (pk == NULL) {
481 debug("PEM_read_PrivateKey failed");
482 (void)ERR_get_error();
483 } else if (pk->type == EVP_PKEY_RSA &&
484 (type == KEY_UNSPEC||type==KEY_RSA)) {
485 prv = key_new(KEY_UNSPEC);
486 prv->rsa = EVP_PKEY_get1_RSA(pk);
487 prv->type = KEY_RSA;
488 name = "rsa w/o comment";
489 #ifdef DEBUG_PK
490 RSA_print_fp(stderr, prv->rsa, 8);
491 #endif
492 if (RSA_blinding_on(prv->rsa, NULL) != 1) {
493 error("key_load_private_pem: RSA_blinding_on failed");
494 key_free(prv);
495 prv = NULL;
497 } else if (pk->type == EVP_PKEY_DSA &&
498 (type == KEY_UNSPEC||type==KEY_DSA)) {
499 prv = key_new(KEY_UNSPEC);
500 prv->dsa = EVP_PKEY_get1_DSA(pk);
501 prv->type = KEY_DSA;
502 name = "dsa w/o comment";
503 #ifdef DEBUG_PK
504 DSA_print_fp(stderr, prv->dsa, 8);
505 #endif
506 } else {
507 error("PEM_read_PrivateKey: mismatch or "
508 "unknown EVP_PKEY save_type %d", pk->save_type);
510 fclose(fp);
511 if (pk != NULL)
512 EVP_PKEY_free(pk);
513 if (prv != NULL && commentp)
514 *commentp = xstrdup(name);
515 debug("read PEM private key done: type %s",
516 prv ? key_type(prv) : "<unknown>");
517 return prv;
521 key_perm_ok(int fd, const char *filename)
523 struct stat st;
525 if (fstat(fd, &st) < 0)
526 return 0;
528 * if a key owned by the user is accessed, then we check the
529 * permissions of the file. if the key owned by a different user,
530 * then we don't care.
532 #ifdef HAVE_CYGWIN
533 if (check_ntsec(filename))
534 #endif
535 if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
536 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
537 error("@ WARNING: UNPROTECTED PRIVATE KEY FILE! @");
538 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
539 error("Permissions 0%3.3o for '%s' are too open.",
540 (u_int)st.st_mode & 0777, filename);
541 error("It is recommended that your private key files are NOT accessible by others.");
542 error("This private key will be ignored.");
543 return 0;
545 return 1;
548 Key *
549 key_load_private_type(int type, const char *filename, const char *passphrase,
550 char **commentp, int *perm_ok)
552 int fd;
554 fd = open(filename, O_RDONLY);
555 if (fd < 0)
556 return NULL;
557 if (!key_perm_ok(fd, filename)) {
558 if (perm_ok != NULL)
559 *perm_ok = 0;
560 error("bad permissions: ignore key: %s", filename);
561 close(fd);
562 return NULL;
564 if (perm_ok != NULL)
565 *perm_ok = 1;
566 switch (type) {
567 case KEY_RSA1:
568 return key_load_private_rsa1(fd, filename, passphrase,
569 commentp);
570 /* closes fd */
571 case KEY_DSA:
572 case KEY_RSA:
573 case KEY_UNSPEC:
574 return key_load_private_pem(fd, type, passphrase, commentp);
575 /* closes fd */
576 default:
577 close(fd);
578 break;
580 return NULL;
583 Key *
584 key_load_private(const char *filename, const char *passphrase,
585 char **commentp)
587 Key *pub, *prv;
588 int fd;
590 fd = open(filename, O_RDONLY);
591 if (fd < 0)
592 return NULL;
593 if (!key_perm_ok(fd, filename)) {
594 error("bad permissions: ignore key: %s", filename);
595 close(fd);
596 return NULL;
598 pub = key_load_public_rsa1(fd, filename, commentp);
599 lseek(fd, (off_t) 0, SEEK_SET); /* rewind */
600 if (pub == NULL) {
601 /* closes fd */
602 prv = key_load_private_pem(fd, KEY_UNSPEC, passphrase, NULL);
603 /* use the filename as a comment for PEM */
604 if (commentp && prv)
605 *commentp = xstrdup(filename);
606 } else {
607 /* it's a SSH v1 key if the public key part is readable */
608 key_free(pub);
609 /* closes fd */
610 prv = key_load_private_rsa1(fd, filename, passphrase, NULL);
612 return prv;
615 static int
616 key_try_load_public(Key *k, const char *filename, char **commentp)
618 FILE *f;
619 char line[SSH_MAX_PUBKEY_BYTES];
620 char *cp;
621 u_long linenum = 0;
623 f = fopen(filename, "r");
624 if (f != NULL) {
625 while (read_keyfile_line(f, filename, line, sizeof(line),
626 &linenum) != -1) {
627 cp = line;
628 switch (*cp) {
629 case '#':
630 case '\n':
631 case '\0':
632 continue;
634 /* Skip leading whitespace. */
635 for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
637 if (*cp) {
638 if (key_read(k, &cp) == 1) {
639 if (commentp)
640 *commentp=xstrdup(filename);
641 fclose(f);
642 return 1;
646 fclose(f);
648 return 0;
651 /* load public key from ssh v1 private or any pubkey file */
652 Key *
653 key_load_public(const char *filename, char **commentp)
655 Key *pub;
656 char file[MAXPATHLEN];
658 /* try rsa1 private key */
659 pub = key_load_public_type(KEY_RSA1, filename, commentp);
660 if (pub != NULL)
661 return pub;
663 /* try rsa1 public key */
664 pub = key_new(KEY_RSA1);
665 if (key_try_load_public(pub, filename, commentp) == 1)
666 return pub;
667 key_free(pub);
669 /* try ssh2 public key */
670 pub = key_new(KEY_UNSPEC);
671 if (key_try_load_public(pub, filename, commentp) == 1)
672 return pub;
673 if ((strlcpy(file, filename, sizeof file) < sizeof(file)) &&
674 (strlcat(file, ".pub", sizeof file) < sizeof(file)) &&
675 (key_try_load_public(pub, file, commentp) == 1))
676 return pub;
677 key_free(pub);
678 return NULL;