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