xref: /netbsd-src/crypto/external/bsd/openssh/dist/authfile.c (revision cc7d2833ecf67da5a5ddc470841931eb9f6723e4)
1 /*	$NetBSD: authfile.c,v 1.22 2019/10/12 18:32:22 christos Exp $	*/
2 /* $OpenBSD: authfile.c,v 1.135 2019/09/03 08:30:47 djm Exp $ */
3 /*
4  * Copyright (c) 2000, 2013 Markus Friedl.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 __RCSID("$NetBSD: authfile.c,v 1.22 2019/10/12 18:32:22 christos Exp $");
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/uio.h>
32 
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <limits.h>
40 
41 #include "cipher.h"
42 #include "ssh.h"
43 #include "log.h"
44 #include "authfile.h"
45 #include "misc.h"
46 #include "atomicio.h"
47 #include "sshkey.h"
48 #include "sshbuf.h"
49 #include "ssherr.h"
50 #include "krl.h"
51 
52 #define MAX_KEY_FILE_SIZE	(1024 * 1024)
53 
54 /* Save a key blob to a file */
55 static int
56 sshkey_save_private_blob(struct sshbuf *keybuf, const char *filename)
57 {
58 	int fd, oerrno;
59 
60 	if ((fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0600)) == -1)
61 		return SSH_ERR_SYSTEM_ERROR;
62 	if (atomicio(vwrite, fd, sshbuf_mutable_ptr(keybuf),
63 	    sshbuf_len(keybuf)) != sshbuf_len(keybuf)) {
64 		oerrno = errno;
65 		close(fd);
66 		unlink(filename);
67 		errno = oerrno;
68 		return SSH_ERR_SYSTEM_ERROR;
69 	}
70 	close(fd);
71 	return 0;
72 }
73 
74 int
75 sshkey_save_private(struct sshkey *key, const char *filename,
76     const char *passphrase, const char *comment,
77     int format, const char *openssh_format_cipher, int openssh_format_rounds)
78 {
79 	struct sshbuf *keyblob = NULL;
80 	int r;
81 
82 	if ((keyblob = sshbuf_new()) == NULL)
83 		return SSH_ERR_ALLOC_FAIL;
84 	if ((r = sshkey_private_to_fileblob(key, keyblob, passphrase, comment,
85 	    format, openssh_format_cipher, openssh_format_rounds)) != 0)
86 		goto out;
87 	if ((r = sshkey_save_private_blob(keyblob, filename)) != 0)
88 		goto out;
89 	r = 0;
90  out:
91 	sshbuf_free(keyblob);
92 	return r;
93 }
94 
95 /* Load a key from a fd into a buffer */
96 int
97 sshkey_load_file(int fd, struct sshbuf *blob)
98 {
99 	u_char buf[1024];
100 	size_t len;
101 	struct stat st;
102 	int r;
103 
104 	if (fstat(fd, &st) == -1)
105 		return SSH_ERR_SYSTEM_ERROR;
106 	if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
107 	    st.st_size > MAX_KEY_FILE_SIZE)
108 		return SSH_ERR_INVALID_FORMAT;
109 	for (;;) {
110 		if ((len = atomicio(read, fd, buf, sizeof(buf))) == 0) {
111 			if (errno == EPIPE)
112 				break;
113 			r = SSH_ERR_SYSTEM_ERROR;
114 			goto out;
115 		}
116 		if ((r = sshbuf_put(blob, buf, len)) != 0)
117 			goto out;
118 		if (sshbuf_len(blob) > MAX_KEY_FILE_SIZE) {
119 			r = SSH_ERR_INVALID_FORMAT;
120 			goto out;
121 		}
122 	}
123 	if ((st.st_mode & (S_IFSOCK|S_IFCHR|S_IFIFO)) == 0 &&
124 	    st.st_size != (off_t)sshbuf_len(blob)) {
125 		r = SSH_ERR_FILE_CHANGED;
126 		goto out;
127 	}
128 	r = 0;
129 
130  out:
131 	explicit_bzero(buf, sizeof(buf));
132 	if (r != 0)
133 		sshbuf_reset(blob);
134 	return r;
135 }
136 
137 
138 /* XXX remove error() calls from here? */
139 int
140 sshkey_perm_ok(int fd, const char *filename)
141 {
142 	struct stat st;
143 
144 	if (fstat(fd, &st) == -1)
145 		return SSH_ERR_SYSTEM_ERROR;
146 	/*
147 	 * if a key owned by the user is accessed, then we check the
148 	 * permissions of the file. if the key owned by a different user,
149 	 * then we don't care.
150 	 */
151 	if ((st.st_uid == getuid()) && (st.st_mode & 077) != 0) {
152 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
153 		error("@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @");
154 		error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
155 		error("Permissions 0%3.3o for '%s' are too open.",
156 		    (u_int)st.st_mode & 0777, filename);
157 		error("It is required that your private key files are NOT accessible by others.");
158 		error("This private key will be ignored.");
159 		return SSH_ERR_KEY_BAD_PERMISSIONS;
160 	}
161 	return 0;
162 }
163 
164 int
165 sshkey_load_private_type(int type, const char *filename, const char *passphrase,
166     struct sshkey **keyp, char **commentp)
167 {
168 	int fd, r;
169 
170 	if (keyp != NULL)
171 		*keyp = NULL;
172 	if (commentp != NULL)
173 		*commentp = NULL;
174 
175 	if ((fd = open(filename, O_RDONLY)) == -1)
176 		return SSH_ERR_SYSTEM_ERROR;
177 
178 	r = sshkey_perm_ok(fd, filename);
179 	if (r != 0)
180 		goto out;
181 
182 	r = sshkey_load_private_type_fd(fd, type, passphrase, keyp, commentp);
183 	if (r == 0 && keyp && *keyp)
184 		r = sshkey_set_filename(*keyp, filename);
185  out:
186 	close(fd);
187 	return r;
188 }
189 
190 int
191 sshkey_load_private_type_fd(int fd, int type, const char *passphrase,
192     struct sshkey **keyp, char **commentp)
193 {
194 	struct sshbuf *buffer = NULL;
195 	int r;
196 
197 	if (keyp != NULL)
198 		*keyp = NULL;
199 	if ((buffer = sshbuf_new()) == NULL) {
200 		r = SSH_ERR_ALLOC_FAIL;
201 		goto out;
202 	}
203 	if ((r = sshkey_load_file(fd, buffer)) != 0 ||
204 	    (r = sshkey_parse_private_fileblob_type(buffer, type,
205 	    passphrase, keyp, commentp)) != 0)
206 		goto out;
207 
208 	/* success */
209 	r = 0;
210  out:
211 	sshbuf_free(buffer);
212 	return r;
213 }
214 
215 /* XXX this is almost identical to sshkey_load_private_type() */
216 int
217 sshkey_load_private(const char *filename, const char *passphrase,
218     struct sshkey **keyp, char **commentp)
219 {
220 	struct sshbuf *buffer = NULL;
221 	int r, fd;
222 
223 	if (keyp != NULL)
224 		*keyp = NULL;
225 	if (commentp != NULL)
226 		*commentp = NULL;
227 
228 	if ((fd = open(filename, O_RDONLY)) == -1)
229 		return SSH_ERR_SYSTEM_ERROR;
230 	if (sshkey_perm_ok(fd, filename) != 0) {
231 		r = SSH_ERR_KEY_BAD_PERMISSIONS;
232 		goto out;
233 	}
234 
235 	if ((buffer = sshbuf_new()) == NULL) {
236 		r = SSH_ERR_ALLOC_FAIL;
237 		goto out;
238 	}
239 	if ((r = sshkey_load_file(fd, buffer)) != 0 ||
240 	    (r = sshkey_parse_private_fileblob(buffer, passphrase, keyp,
241 	    commentp)) != 0)
242 		goto out;
243 	if (keyp && *keyp &&
244 	    (r = sshkey_set_filename(*keyp, filename)) != 0)
245 		goto out;
246 	r = 0;
247  out:
248 	close(fd);
249 	sshbuf_free(buffer);
250 	return r;
251 }
252 
253 static int
254 sshkey_try_load_public(struct sshkey *k, const char *filename, char **commentp)
255 {
256 	FILE *f;
257 	char *line = NULL, *cp;
258 	size_t linesize = 0;
259 	int r;
260 
261 	if (commentp != NULL)
262 		*commentp = NULL;
263 	if ((f = fopen(filename, "r")) == NULL)
264 		return SSH_ERR_SYSTEM_ERROR;
265 	while (getline(&line, &linesize, f) != -1) {
266 		cp = line;
267 		switch (*cp) {
268 		case '#':
269 		case '\n':
270 		case '\0':
271 			continue;
272 		}
273 		/* Abort loading if this looks like a private key */
274 		if (strncmp(cp, "-----BEGIN", 10) == 0 ||
275 		    strcmp(cp, "SSH PRIVATE KEY FILE") == 0)
276 			break;
277 		/* Skip leading whitespace. */
278 		for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
279 			;
280 		if (*cp) {
281 			if ((r = sshkey_read(k, &cp)) == 0) {
282 				cp[strcspn(cp, "\r\n")] = '\0';
283 				if (commentp) {
284 					*commentp = strdup(*cp ?
285 					    cp : filename);
286 					if (*commentp == NULL)
287 						r = SSH_ERR_ALLOC_FAIL;
288 				}
289 				free(line);
290 				fclose(f);
291 				return r;
292 			}
293 		}
294 	}
295 	free(line);
296 	fclose(f);
297 	return SSH_ERR_INVALID_FORMAT;
298 }
299 
300 /* load public key from any pubkey file */
301 int
302 sshkey_load_public(const char *filename, struct sshkey **keyp, char **commentp)
303 {
304 	struct sshkey *pub = NULL;
305 	char *file = NULL;
306 	int r;
307 
308 	if (keyp != NULL)
309 		*keyp = NULL;
310 	if (commentp != NULL)
311 		*commentp = NULL;
312 
313 	if ((pub = sshkey_new(KEY_UNSPEC)) == NULL)
314 		return SSH_ERR_ALLOC_FAIL;
315 	if ((r = sshkey_try_load_public(pub, filename, commentp)) == 0) {
316 		if (keyp != NULL) {
317 			*keyp = pub;
318 			pub = NULL;
319 		}
320 		r = 0;
321 		goto out;
322 	}
323 	sshkey_free(pub);
324 
325 	/* try .pub suffix */
326 	if (asprintf(&file, "%s.pub", filename) == -1)
327 		return SSH_ERR_ALLOC_FAIL;
328 	if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
329 		r = SSH_ERR_ALLOC_FAIL;
330 		goto out;
331 	}
332 	if ((r = sshkey_try_load_public(pub, file, commentp)) == 0) {
333 		if (keyp != NULL) {
334 			*keyp = pub;
335 			pub = NULL;
336 		}
337 		r = 0;
338 	}
339  out:
340 	free(file);
341 	sshkey_free(pub);
342 	return r;
343 }
344 
345 /* Load the certificate associated with the named private key */
346 int
347 sshkey_load_cert(const char *filename, struct sshkey **keyp)
348 {
349 	struct sshkey *pub = NULL;
350 	char *file = NULL;
351 	int r = SSH_ERR_INTERNAL_ERROR;
352 
353 	if (keyp != NULL)
354 		*keyp = NULL;
355 
356 	if (asprintf(&file, "%s-cert.pub", filename) == -1)
357 		return SSH_ERR_ALLOC_FAIL;
358 
359 	if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
360 		goto out;
361 	}
362 	if ((r = sshkey_try_load_public(pub, file, NULL)) != 0)
363 		goto out;
364 	/* success */
365 	if (keyp != NULL) {
366 		*keyp = pub;
367 		pub = NULL;
368 	}
369 	r = 0;
370  out:
371 	free(file);
372 	sshkey_free(pub);
373 	return r;
374 }
375 
376 /* Load private key and certificate */
377 int
378 sshkey_load_private_cert(int type, const char *filename, const char *passphrase,
379     struct sshkey **keyp)
380 {
381 	struct sshkey *key = NULL, *cert = NULL;
382 	int r;
383 
384 	if (keyp != NULL)
385 		*keyp = NULL;
386 
387 	switch (type) {
388 #ifdef WITH_OPENSSL
389 	case KEY_RSA:
390 	case KEY_DSA:
391 	case KEY_ECDSA:
392 #endif /* WITH_OPENSSL */
393 	case KEY_ED25519:
394 	case KEY_XMSS:
395 	case KEY_UNSPEC:
396 		break;
397 	default:
398 		return SSH_ERR_KEY_TYPE_UNKNOWN;
399 	}
400 
401 	if ((r = sshkey_load_private_type(type, filename,
402 	    passphrase, &key, NULL)) != 0 ||
403 	    (r = sshkey_load_cert(filename, &cert)) != 0)
404 		goto out;
405 
406 	/* Make sure the private key matches the certificate */
407 	if (sshkey_equal_public(key, cert) == 0) {
408 		r = SSH_ERR_KEY_CERT_MISMATCH;
409 		goto out;
410 	}
411 
412 	if ((r = sshkey_to_certified(key)) != 0 ||
413 	    (r = sshkey_cert_copy(cert, key)) != 0)
414 		goto out;
415 	r = 0;
416 	if (keyp != NULL) {
417 		*keyp = key;
418 		key = NULL;
419 	}
420  out:
421 	sshkey_free(key);
422 	sshkey_free(cert);
423 	return r;
424 }
425 
426 /*
427  * Returns success if the specified "key" is listed in the file "filename",
428  * SSH_ERR_KEY_NOT_FOUND: if the key is not listed or another error.
429  * If "strict_type" is set then the key type must match exactly,
430  * otherwise a comparison that ignores certficiate data is performed.
431  * If "check_ca" is set and "key" is a certificate, then its CA key is
432  * also checked and sshkey_in_file() will return success if either is found.
433  */
434 int
435 sshkey_in_file(struct sshkey *key, const char *filename, int strict_type,
436     int check_ca)
437 {
438 	FILE *f;
439 	char *line = NULL, *cp;
440 	size_t linesize = 0;
441 	int r = 0;
442 	struct sshkey *pub = NULL;
443 
444 	int (*sshkey_compare)(const struct sshkey *, const struct sshkey *) =
445 	    strict_type ?  sshkey_equal : sshkey_equal_public;
446 
447 	if ((f = fopen(filename, "r")) == NULL)
448 		return SSH_ERR_SYSTEM_ERROR;
449 
450 	while (getline(&line, &linesize, f) != -1) {
451 		sshkey_free(pub);
452 		pub = NULL;
453 		cp = line;
454 
455 		/* Skip leading whitespace. */
456 		for (; *cp && (*cp == ' ' || *cp == '\t'); cp++)
457 			;
458 
459 		/* Skip comments and empty lines */
460 		switch (*cp) {
461 		case '#':
462 		case '\n':
463 		case '\0':
464 			continue;
465 		}
466 
467 		if ((pub = sshkey_new(KEY_UNSPEC)) == NULL) {
468 			r = SSH_ERR_ALLOC_FAIL;
469 			goto out;
470 		}
471 		switch (r = sshkey_read(pub, &cp)) {
472 		case 0:
473 			break;
474 		case SSH_ERR_KEY_LENGTH:
475 			continue;
476 		default:
477 			goto out;
478 		}
479 		if (sshkey_compare(key, pub) ||
480 		    (check_ca && sshkey_is_cert(key) &&
481 		    sshkey_compare(key->cert->signature_key, pub))) {
482 			r = 0;
483 			goto out;
484 		}
485 	}
486 	r = SSH_ERR_KEY_NOT_FOUND;
487  out:
488 	free(line);
489 	sshkey_free(pub);
490 	fclose(f);
491 	return r;
492 }
493 
494 /*
495  * Checks whether the specified key is revoked, returning 0 if not,
496  * SSH_ERR_KEY_REVOKED if it is or another error code if something
497  * unexpected happened.
498  * This will check both the key and, if it is a certificate, its CA key too.
499  * "revoked_keys_file" may be a KRL or a one-per-line list of public keys.
500  */
501 int
502 sshkey_check_revoked(struct sshkey *key, const char *revoked_keys_file)
503 {
504 	int r;
505 
506 	r = ssh_krl_file_contains_key(revoked_keys_file, key);
507 	/* If this was not a KRL to begin with then continue below */
508 	if (r != SSH_ERR_KRL_BAD_MAGIC)
509 		return r;
510 
511 	/*
512 	 * If the file is not a KRL or we can't handle KRLs then attempt to
513 	 * parse the file as a flat list of keys.
514 	 */
515 	switch ((r = sshkey_in_file(key, revoked_keys_file, 0, 1))) {
516 	case 0:
517 		/* Key found => revoked */
518 		return SSH_ERR_KEY_REVOKED;
519 	case SSH_ERR_KEY_NOT_FOUND:
520 		/* Key not found => not revoked */
521 		return 0;
522 	default:
523 		/* Some other error occurred */
524 		return r;
525 	}
526 }
527 
528 /*
529  * Advanced *cpp past the end of key options, defined as the first unquoted
530  * whitespace character. Returns 0 on success or -1 on failure (e.g.
531  * unterminated quotes).
532  */
533 int
534 sshkey_advance_past_options(char **cpp)
535 {
536 	char *cp = *cpp;
537 	int quoted = 0;
538 
539 	for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) {
540 		if (*cp == '\\' && cp[1] == '"')
541 			cp++;	/* Skip both */
542 		else if (*cp == '"')
543 			quoted = !quoted;
544 	}
545 	*cpp = cp;
546 	/* return failure for unterminated quotes */
547 	return (*cp == '\0' && quoted) ? -1 : 0;
548 }
549 
550