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