xref: /freebsd/crypto/openssh/auth-options.c (revision 389e4940069316fe667ffa263fa7d6390d0a960f)
1 /* $OpenBSD: auth-options.c,v 1.78 2018/03/14 05:35:40 djm Exp $ */
2 /*
3  * Copyright (c) 2018 Damien Miller <djm@mindrot.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include "includes.h"
19 
20 #include <sys/types.h>
21 
22 #include <netdb.h>
23 #include <pwd.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdarg.h>
27 #include <ctype.h>
28 #include <limits.h>
29 
30 #include "openbsd-compat/sys-queue.h"
31 
32 #include "xmalloc.h"
33 #include "ssherr.h"
34 #include "log.h"
35 #include "sshbuf.h"
36 #include "misc.h"
37 #include "sshkey.h"
38 #include "match.h"
39 #include "ssh2.h"
40 #include "auth-options.h"
41 
42 /*
43  * Match flag 'opt' in *optsp, and if allow_negate is set then also match
44  * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
45  * if negated option matches.
46  * If the option or negated option matches, then *optsp is updated to
47  * point to the first character after the option.
48  */
49 static int
50 opt_flag(const char *opt, int allow_negate, const char **optsp)
51 {
52 	size_t opt_len = strlen(opt);
53 	const char *opts = *optsp;
54 	int negate = 0;
55 
56 	if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
57 		opts += 3;
58 		negate = 1;
59 	}
60 	if (strncasecmp(opts, opt, opt_len) == 0) {
61 		*optsp = opts + opt_len;
62 		return negate ? 0 : 1;
63 	}
64 	return -1;
65 }
66 
67 static char *
68 opt_dequote(const char **sp, const char **errstrp)
69 {
70 	const char *s = *sp;
71 	char *ret;
72 	size_t i;
73 
74 	*errstrp = NULL;
75 	if (*s != '"') {
76 		*errstrp = "missing start quote";
77 		return NULL;
78 	}
79 	s++;
80 	if ((ret = malloc(strlen((s)) + 1)) == NULL) {
81 		*errstrp = "memory allocation failed";
82 		return NULL;
83 	}
84 	for (i = 0; *s != '\0' && *s != '"';) {
85 		if (s[0] == '\\' && s[1] == '"')
86 			s++;
87 		ret[i++] = *s++;
88 	}
89 	if (*s == '\0') {
90 		*errstrp = "missing end quote";
91 		free(ret);
92 		return NULL;
93 	}
94 	ret[i] = '\0';
95 	s++;
96 	*sp = s;
97 	return ret;
98 }
99 
100 static int
101 opt_match(const char **opts, const char *term)
102 {
103 	if (strncasecmp((*opts), term, strlen(term)) == 0 &&
104 	    (*opts)[strlen(term)] == '=') {
105 		*opts += strlen(term) + 1;
106 		return 1;
107 	}
108 	return 0;
109 }
110 
111 static int
112 dup_strings(char ***dstp, size_t *ndstp, char **src, size_t nsrc)
113 {
114 	char **dst;
115 	size_t i, j;
116 
117 	*dstp = NULL;
118 	*ndstp = 0;
119 	if (nsrc == 0)
120 		return 0;
121 
122 	if ((dst = calloc(nsrc, sizeof(*src))) == NULL)
123 		return -1;
124 	for (i = 0; i < nsrc; i++) {
125 		if ((dst[i] = strdup(src[i])) == NULL) {
126 			for (j = 0; j < i; j++)
127 				free(dst[j]);
128 			free(dst);
129 			return -1;
130 		}
131 	}
132 	/* success */
133 	*dstp = dst;
134 	*ndstp = nsrc;
135 	return 0;
136 }
137 
138 #define OPTIONS_CRITICAL	1
139 #define OPTIONS_EXTENSIONS	2
140 static int
141 cert_option_list(struct sshauthopt *opts, struct sshbuf *oblob,
142     u_int which, int crit)
143 {
144 	char *command, *allowed;
145 	char *name = NULL;
146 	struct sshbuf *c = NULL, *data = NULL;
147 	int r, ret = -1, found;
148 
149 	if ((c = sshbuf_fromb(oblob)) == NULL) {
150 		error("%s: sshbuf_fromb failed", __func__);
151 		goto out;
152 	}
153 
154 	while (sshbuf_len(c) > 0) {
155 		sshbuf_free(data);
156 		data = NULL;
157 		if ((r = sshbuf_get_cstring(c, &name, NULL)) != 0 ||
158 		    (r = sshbuf_froms(c, &data)) != 0) {
159 			error("Unable to parse certificate options: %s",
160 			    ssh_err(r));
161 			goto out;
162 		}
163 		debug3("found certificate option \"%.100s\" len %zu",
164 		    name, sshbuf_len(data));
165 		found = 0;
166 		if ((which & OPTIONS_EXTENSIONS) != 0) {
167 			if (strcmp(name, "permit-X11-forwarding") == 0) {
168 				opts->permit_x11_forwarding_flag = 1;
169 				found = 1;
170 			} else if (strcmp(name,
171 			    "permit-agent-forwarding") == 0) {
172 				opts->permit_agent_forwarding_flag = 1;
173 				found = 1;
174 			} else if (strcmp(name,
175 			    "permit-port-forwarding") == 0) {
176 				opts->permit_port_forwarding_flag = 1;
177 				found = 1;
178 			} else if (strcmp(name, "permit-pty") == 0) {
179 				opts->permit_pty_flag = 1;
180 				found = 1;
181 			} else if (strcmp(name, "permit-user-rc") == 0) {
182 				opts->permit_user_rc = 1;
183 				found = 1;
184 			}
185 		}
186 		if (!found && (which & OPTIONS_CRITICAL) != 0) {
187 			if (strcmp(name, "force-command") == 0) {
188 				if ((r = sshbuf_get_cstring(data, &command,
189 				    NULL)) != 0) {
190 					error("Unable to parse \"%s\" "
191 					    "section: %s", name, ssh_err(r));
192 					goto out;
193 				}
194 				if (opts->force_command != NULL) {
195 					error("Certificate has multiple "
196 					    "force-command options");
197 					free(command);
198 					goto out;
199 				}
200 				opts->force_command = command;
201 				found = 1;
202 			}
203 			if (strcmp(name, "source-address") == 0) {
204 				if ((r = sshbuf_get_cstring(data, &allowed,
205 				    NULL)) != 0) {
206 					error("Unable to parse \"%s\" "
207 					    "section: %s", name, ssh_err(r));
208 					goto out;
209 				}
210 				if (opts->required_from_host_cert != NULL) {
211 					error("Certificate has multiple "
212 					    "source-address options");
213 					free(allowed);
214 					goto out;
215 				}
216 				/* Check syntax */
217 				if (addr_match_cidr_list(NULL, allowed) == -1) {
218 					error("Certificate source-address "
219 					    "contents invalid");
220 					goto out;
221 				}
222 				opts->required_from_host_cert = allowed;
223 				found = 1;
224 			}
225 		}
226 
227 		if (!found) {
228 			if (crit) {
229 				error("Certificate critical option \"%s\" "
230 				    "is not supported", name);
231 				goto out;
232 			} else {
233 				logit("Certificate extension \"%s\" "
234 				    "is not supported", name);
235 			}
236 		} else if (sshbuf_len(data) != 0) {
237 			error("Certificate option \"%s\" corrupt "
238 			    "(extra data)", name);
239 			goto out;
240 		}
241 		free(name);
242 		name = NULL;
243 	}
244 	/* successfully parsed all options */
245 	ret = 0;
246 
247  out:
248 	free(name);
249 	sshbuf_free(data);
250 	sshbuf_free(c);
251 	return ret;
252 }
253 
254 struct sshauthopt *
255 sshauthopt_new(void)
256 {
257 	struct sshauthopt *ret;
258 
259 	if ((ret = calloc(1, sizeof(*ret))) == NULL)
260 		return NULL;
261 	ret->force_tun_device = -1;
262 	return ret;
263 }
264 
265 void
266 sshauthopt_free(struct sshauthopt *opts)
267 {
268 	size_t i;
269 
270 	if (opts == NULL)
271 		return;
272 
273 	free(opts->cert_principals);
274 	free(opts->force_command);
275 	free(opts->required_from_host_cert);
276 	free(opts->required_from_host_keys);
277 
278 	for (i = 0; i < opts->nenv; i++)
279 		free(opts->env[i]);
280 	free(opts->env);
281 
282 	for (i = 0; i < opts->npermitopen; i++)
283 		free(opts->permitopen[i]);
284 	free(opts->permitopen);
285 
286 	explicit_bzero(opts, sizeof(*opts));
287 	free(opts);
288 }
289 
290 struct sshauthopt *
291 sshauthopt_new_with_keys_defaults(void)
292 {
293 	struct sshauthopt *ret = NULL;
294 
295 	if ((ret = sshauthopt_new()) == NULL)
296 		return NULL;
297 
298 	/* Defaults for authorized_keys flags */
299 	ret->permit_port_forwarding_flag = 1;
300 	ret->permit_agent_forwarding_flag = 1;
301 	ret->permit_x11_forwarding_flag = 1;
302 	ret->permit_pty_flag = 1;
303 	ret->permit_user_rc = 1;
304 	return ret;
305 }
306 
307 struct sshauthopt *
308 sshauthopt_parse(const char *opts, const char **errstrp)
309 {
310 	char **oarray, *opt, *cp, *tmp, *host;
311 	int r;
312 	struct sshauthopt *ret = NULL;
313 	const char *errstr = "unknown error";
314 	uint64_t valid_before;
315 
316 	if (errstrp != NULL)
317 		*errstrp = NULL;
318 	if ((ret = sshauthopt_new_with_keys_defaults()) == NULL)
319 		goto alloc_fail;
320 
321 	if (opts == NULL)
322 		return ret;
323 
324 	while (*opts && *opts != ' ' && *opts != '\t') {
325 		/* flag options */
326 		if ((r = opt_flag("restrict", 0, &opts)) != -1) {
327 			ret->restricted = 1;
328 			ret->permit_port_forwarding_flag = 0;
329 			ret->permit_agent_forwarding_flag = 0;
330 			ret->permit_x11_forwarding_flag = 0;
331 			ret->permit_pty_flag = 0;
332 			ret->permit_user_rc = 0;
333 		} else if ((r = opt_flag("cert-authority", 0, &opts)) != -1) {
334 			ret->cert_authority = r;
335 		} else if ((r = opt_flag("port-forwarding", 1, &opts)) != -1) {
336 			ret->permit_port_forwarding_flag = r == 1;
337 		} else if ((r = opt_flag("agent-forwarding", 1, &opts)) != -1) {
338 			ret->permit_agent_forwarding_flag = r == 1;
339 		} else if ((r = opt_flag("x11-forwarding", 1, &opts)) != -1) {
340 			ret->permit_x11_forwarding_flag = r == 1;
341 		} else if ((r = opt_flag("pty", 1, &opts)) != -1) {
342 			ret->permit_pty_flag = r == 1;
343 		} else if ((r = opt_flag("user-rc", 1, &opts)) != -1) {
344 			ret->permit_user_rc = r == 1;
345 		} else if (opt_match(&opts, "command")) {
346 			if (ret->force_command != NULL) {
347 				errstr = "multiple \"command\" clauses";
348 				goto fail;
349 			}
350 			ret->force_command = opt_dequote(&opts, &errstr);
351 			if (ret->force_command == NULL)
352 				goto fail;
353 		} else if (opt_match(&opts, "principals")) {
354 			if (ret->cert_principals != NULL) {
355 				errstr = "multiple \"principals\" clauses";
356 				goto fail;
357 			}
358 			ret->cert_principals = opt_dequote(&opts, &errstr);
359 			if (ret->cert_principals == NULL)
360 				goto fail;
361 		} else if (opt_match(&opts, "from")) {
362 			if (ret->required_from_host_keys != NULL) {
363 				errstr = "multiple \"from\" clauses";
364 				goto fail;
365 			}
366 			ret->required_from_host_keys = opt_dequote(&opts,
367 			    &errstr);
368 			if (ret->required_from_host_keys == NULL)
369 				goto fail;
370 		} else if (opt_match(&opts, "expiry-time")) {
371 			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
372 				goto fail;
373 			if (parse_absolute_time(opt, &valid_before) != 0 ||
374 			    valid_before == 0) {
375 				free(opt);
376 				errstr = "invalid expires time";
377 				goto fail;
378 			}
379 			free(opt);
380 			if (ret->valid_before == 0 ||
381 			    valid_before < ret->valid_before)
382 				ret->valid_before = valid_before;
383 		} else if (opt_match(&opts, "environment")) {
384 			if (ret->nenv > INT_MAX) {
385 				errstr = "too many environment strings";
386 				goto fail;
387 			}
388 			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
389 				goto fail;
390 			/* env name must be alphanumeric and followed by '=' */
391 			if ((tmp = strchr(opt, '=')) == NULL) {
392 				free(opt);
393 				errstr = "invalid environment string";
394 				goto fail;
395 			}
396 			for (cp = opt; cp < tmp; cp++) {
397 				if (!isalnum((u_char)*cp)) {
398 					free(opt);
399 					errstr = "invalid environment string";
400 					goto fail;
401 				}
402 			}
403 			/* Append it. */
404 			oarray = ret->env;
405 			if ((ret->env = recallocarray(ret->env, ret->nenv,
406 			    ret->nenv + 1, sizeof(*ret->env))) == NULL) {
407 				free(opt);
408 				ret->env = oarray; /* put it back for cleanup */
409 				goto alloc_fail;
410 			}
411 			ret->env[ret->nenv++] = opt;
412 		} else if (opt_match(&opts, "permitopen")) {
413 			if (ret->npermitopen > INT_MAX) {
414 				errstr = "too many permitopens";
415 				goto fail;
416 			}
417 			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
418 				goto fail;
419 			if ((tmp = strdup(opt)) == NULL) {
420 				free(opt);
421 				goto alloc_fail;
422 			}
423 			cp = tmp;
424 			/* validate syntax of permitopen before recording it. */
425 			host = hpdelim(&cp);
426 			if (host == NULL || strlen(host) >= NI_MAXHOST) {
427 				free(tmp);
428 				free(opt);
429 				errstr = "invalid permitopen hostname";
430 				goto fail;
431 			}
432 			/*
433 			 * don't want to use permitopen_port to avoid
434 			 * dependency on channels.[ch] here.
435 			 */
436 			if (cp == NULL ||
437 			    (strcmp(cp, "*") != 0 && a2port(cp) <= 0)) {
438 				free(tmp);
439 				free(opt);
440 				errstr = "invalid permitopen port";
441 				goto fail;
442 			}
443 			/* XXX - add streamlocal support */
444 			free(tmp);
445 			/* Record it */
446 			oarray = ret->permitopen;
447 			if ((ret->permitopen = recallocarray(ret->permitopen,
448 			    ret->npermitopen, ret->npermitopen + 1,
449 			    sizeof(*ret->permitopen))) == NULL) {
450 				free(opt);
451 				ret->permitopen = oarray;
452 				goto alloc_fail;
453 			}
454 			ret->permitopen[ret->npermitopen++] = opt;
455 		} else if (opt_match(&opts, "tunnel")) {
456 			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
457 				goto fail;
458 			ret->force_tun_device = a2tun(opt, NULL);
459 			free(opt);
460 			if (ret->force_tun_device == SSH_TUNID_ERR) {
461 				errstr = "invalid tun device";
462 				goto fail;
463 			}
464 		}
465 		/*
466 		 * Skip the comma, and move to the next option
467 		 * (or break out if there are no more).
468 		 */
469 		if (*opts == '\0' || *opts == ' ' || *opts == '\t')
470 			break;		/* End of options. */
471 		/* Anything other than a comma is an unknown option */
472 		if (*opts != ',') {
473 			errstr = "unknown key option";
474 			goto fail;
475 		}
476 		opts++;
477 		if (*opts == '\0') {
478 			errstr = "unexpected end-of-options";
479 			goto fail;
480 		}
481 	}
482 
483 	/* success */
484 	if (errstrp != NULL)
485 		*errstrp = NULL;
486 	return ret;
487 
488 alloc_fail:
489 	errstr = "memory allocation failed";
490 fail:
491 	sshauthopt_free(ret);
492 	if (errstrp != NULL)
493 		*errstrp = errstr;
494 	return NULL;
495 }
496 
497 struct sshauthopt *
498 sshauthopt_from_cert(struct sshkey *k)
499 {
500 	struct sshauthopt *ret;
501 
502 	if (k == NULL || !sshkey_type_is_cert(k->type) || k->cert == NULL ||
503 	    k->cert->type != SSH2_CERT_TYPE_USER)
504 		return NULL;
505 
506 	if ((ret = sshauthopt_new()) == NULL)
507 		return NULL;
508 
509 	/* Handle options and critical extensions separately */
510 	if (cert_option_list(ret, k->cert->critical,
511 	    OPTIONS_CRITICAL, 1) == -1) {
512 		sshauthopt_free(ret);
513 		return NULL;
514 	}
515 	if (cert_option_list(ret, k->cert->extensions,
516 	    OPTIONS_EXTENSIONS, 0) == -1) {
517 		sshauthopt_free(ret);
518 		return NULL;
519 	}
520 	/* success */
521 	return ret;
522 }
523 
524 /*
525  * Merges "additional" options to "primary" and returns the result.
526  * NB. Some options from primary have primacy.
527  */
528 struct sshauthopt *
529 sshauthopt_merge(const struct sshauthopt *primary,
530     const struct sshauthopt *additional, const char **errstrp)
531 {
532 	struct sshauthopt *ret;
533 	const char *errstr = "internal error";
534 	const char *tmp;
535 
536 	if (errstrp != NULL)
537 		*errstrp = NULL;
538 
539 	if ((ret = sshauthopt_new()) == NULL)
540 		goto alloc_fail;
541 
542 	/* cert_authority and cert_principals are cleared in result */
543 
544 	/* Prefer access lists from primary. */
545 	/* XXX err is both set and mismatch? */
546 	tmp = primary->required_from_host_cert;
547 	if (tmp == NULL)
548 		tmp = additional->required_from_host_cert;
549 	if (tmp != NULL && (ret->required_from_host_cert = strdup(tmp)) == NULL)
550 		goto alloc_fail;
551 	tmp = primary->required_from_host_keys;
552 	if (tmp == NULL)
553 		tmp = additional->required_from_host_keys;
554 	if (tmp != NULL && (ret->required_from_host_keys = strdup(tmp)) == NULL)
555 		goto alloc_fail;
556 
557 	/* force_tun_device, permitopen and environment prefer the primary. */
558 	ret->force_tun_device = primary->force_tun_device;
559 	if (ret->force_tun_device == -1)
560 		ret->force_tun_device = additional->force_tun_device;
561 	if (primary->nenv > 0) {
562 		if (dup_strings(&ret->env, &ret->nenv,
563 		    primary->env, primary->nenv) != 0)
564 			goto alloc_fail;
565 	} else if (additional->nenv) {
566 		if (dup_strings(&ret->env, &ret->nenv,
567 		    additional->env, additional->nenv) != 0)
568 			goto alloc_fail;
569 	}
570 	if (primary->npermitopen > 0) {
571 		if (dup_strings(&ret->permitopen, &ret->npermitopen,
572 		    primary->permitopen, primary->npermitopen) != 0)
573 			goto alloc_fail;
574 	} else if (additional->npermitopen > 0) {
575 		if (dup_strings(&ret->permitopen, &ret->npermitopen,
576 		    additional->permitopen, additional->npermitopen) != 0)
577 			goto alloc_fail;
578 	}
579 
580 	/* Flags are logical-AND (i.e. must be set in both for permission) */
581 #define OPTFLAG(x) ret->x = (primary->x == 1) && (additional->x == 1)
582 	OPTFLAG(permit_port_forwarding_flag);
583 	OPTFLAG(permit_agent_forwarding_flag);
584 	OPTFLAG(permit_x11_forwarding_flag);
585 	OPTFLAG(permit_pty_flag);
586 	OPTFLAG(permit_user_rc);
587 #undef OPTFLAG
588 
589 	/* Earliest expiry time should win */
590 	if (primary->valid_before != 0)
591 		ret->valid_before = primary->valid_before;
592 	if (additional->valid_before != 0 &&
593 	    additional->valid_before < ret->valid_before)
594 		ret->valid_before = additional->valid_before;
595 
596 	/*
597 	 * When both multiple forced-command are specified, only
598 	 * proceed if they are identical, otherwise fail.
599 	 */
600 	if (primary->force_command != NULL &&
601 	    additional->force_command != NULL) {
602 		if (strcmp(primary->force_command,
603 		    additional->force_command) == 0) {
604 			/* ok */
605 			ret->force_command = strdup(primary->force_command);
606 			if (ret->force_command == NULL)
607 				goto alloc_fail;
608 		} else {
609 			errstr = "forced command options do not match";
610 			goto fail;
611 		}
612 	} else if (primary->force_command != NULL) {
613 		if ((ret->force_command = strdup(
614 		    primary->force_command)) == NULL)
615 			goto alloc_fail;
616 	} else if (additional->force_command != NULL) {
617 		if ((ret->force_command = strdup(
618 		    additional->force_command)) == NULL)
619 			goto alloc_fail;
620 	}
621 	/* success */
622 	if (errstrp != NULL)
623 		*errstrp = NULL;
624 	return ret;
625 
626  alloc_fail:
627 	errstr = "memory allocation failed";
628  fail:
629 	if (errstrp != NULL)
630 		*errstrp = errstr;
631 	sshauthopt_free(ret);
632 	return NULL;
633 }
634 
635 /*
636  * Copy options
637  */
638 struct sshauthopt *
639 sshauthopt_copy(const struct sshauthopt *orig)
640 {
641 	struct sshauthopt *ret;
642 
643 	if ((ret = sshauthopt_new()) == NULL)
644 		return NULL;
645 
646 #define OPTSCALAR(x) ret->x = orig->x
647 	OPTSCALAR(permit_port_forwarding_flag);
648 	OPTSCALAR(permit_agent_forwarding_flag);
649 	OPTSCALAR(permit_x11_forwarding_flag);
650 	OPTSCALAR(permit_pty_flag);
651 	OPTSCALAR(permit_user_rc);
652 	OPTSCALAR(restricted);
653 	OPTSCALAR(cert_authority);
654 	OPTSCALAR(force_tun_device);
655 	OPTSCALAR(valid_before);
656 #undef OPTSCALAR
657 #define OPTSTRING(x) \
658 	do { \
659 		if (orig->x != NULL && (ret->x = strdup(orig->x)) == NULL) { \
660 			sshauthopt_free(ret); \
661 			return NULL; \
662 		} \
663 	} while (0)
664 	OPTSTRING(cert_principals);
665 	OPTSTRING(force_command);
666 	OPTSTRING(required_from_host_cert);
667 	OPTSTRING(required_from_host_keys);
668 #undef OPTSTRING
669 
670 	if (dup_strings(&ret->env, &ret->nenv, orig->env, orig->nenv) != 0 ||
671 	    dup_strings(&ret->permitopen, &ret->npermitopen,
672 	    orig->permitopen, orig->npermitopen) != 0) {
673 		sshauthopt_free(ret);
674 		return NULL;
675 	}
676 	return ret;
677 }
678 
679 static int
680 serialise_array(struct sshbuf *m, char **a, size_t n)
681 {
682 	struct sshbuf *b;
683 	size_t i;
684 	int r;
685 
686 	if (n > INT_MAX)
687 		return SSH_ERR_INTERNAL_ERROR;
688 
689 	if ((b = sshbuf_new()) == NULL) {
690 		return SSH_ERR_ALLOC_FAIL;
691 	}
692 	for (i = 0; i < n; i++) {
693 		if ((r = sshbuf_put_cstring(b, a[i])) != 0) {
694 			sshbuf_free(b);
695 			return r;
696 		}
697 	}
698 	if ((r = sshbuf_put_u32(m, n)) != 0 ||
699 	    (r = sshbuf_put_stringb(m, b)) != 0) {
700 		sshbuf_free(b);
701 		return r;
702 	}
703 	/* success */
704 	return 0;
705 }
706 
707 static int
708 deserialise_array(struct sshbuf *m, char ***ap, size_t *np)
709 {
710 	char **a = NULL;
711 	size_t i, n = 0;
712 	struct sshbuf *b = NULL;
713 	u_int tmp;
714 	int r = SSH_ERR_INTERNAL_ERROR;
715 
716 	if ((r = sshbuf_get_u32(m, &tmp)) != 0 ||
717 	    (r = sshbuf_froms(m, &b)) != 0)
718 		goto out;
719 	if (tmp > INT_MAX) {
720 		r = SSH_ERR_INVALID_FORMAT;
721 		goto out;
722 	}
723 	n = tmp;
724 	if (n > 0 && (a = calloc(n, sizeof(*a))) == NULL) {
725 		r = SSH_ERR_ALLOC_FAIL;
726 		goto out;
727 	}
728 	for (i = 0; i < n; i++) {
729 		if ((r = sshbuf_get_cstring(b, &a[i], NULL)) != 0)
730 			goto out;
731 	}
732 	/* success */
733 	r = 0;
734 	*ap = a;
735 	a = NULL;
736 	*np = n;
737 	n = 0;
738  out:
739 	for (i = 0; i < n; i++)
740 		free(a[i]);
741 	free(a);
742 	sshbuf_free(b);
743 	return r;
744 }
745 
746 static int
747 serialise_nullable_string(struct sshbuf *m, const char *s)
748 {
749 	int r;
750 
751 	if ((r = sshbuf_put_u8(m, s == NULL)) != 0 ||
752 	    (r = sshbuf_put_cstring(m, s)) != 0)
753 		return r;
754 	return 0;
755 }
756 
757 static int
758 deserialise_nullable_string(struct sshbuf *m, char **sp)
759 {
760 	int r;
761 	u_char flag;
762 
763 	*sp = NULL;
764 	if ((r = sshbuf_get_u8(m, &flag)) != 0 ||
765 	    (r = sshbuf_get_cstring(m, flag ? NULL : sp, NULL)) != 0)
766 		return r;
767 	return 0;
768 }
769 
770 int
771 sshauthopt_serialise(const struct sshauthopt *opts, struct sshbuf *m,
772     int untrusted)
773 {
774 	int r = SSH_ERR_INTERNAL_ERROR;
775 
776 	/* Flag and simple integer options */
777 	if ((r = sshbuf_put_u8(m, opts->permit_port_forwarding_flag)) != 0 ||
778 	    (r = sshbuf_put_u8(m, opts->permit_agent_forwarding_flag)) != 0 ||
779 	    (r = sshbuf_put_u8(m, opts->permit_x11_forwarding_flag)) != 0 ||
780 	    (r = sshbuf_put_u8(m, opts->permit_pty_flag)) != 0 ||
781 	    (r = sshbuf_put_u8(m, opts->permit_user_rc)) != 0 ||
782 	    (r = sshbuf_put_u8(m, opts->restricted)) != 0 ||
783 	    (r = sshbuf_put_u8(m, opts->cert_authority)) != 0 ||
784 	    (r = sshbuf_put_u64(m, opts->valid_before)) != 0)
785 		return r;
786 
787 	/* tunnel number can be negative to indicate "unset" */
788 	if ((r = sshbuf_put_u8(m, opts->force_tun_device == -1)) != 0 ||
789 	    (r = sshbuf_put_u32(m, (opts->force_tun_device < 0) ?
790 	    0 : (u_int)opts->force_tun_device)) != 0)
791 		return r;
792 
793 	/* String options; these may be NULL */
794 	if ((r = serialise_nullable_string(m,
795 	    untrusted ? "yes" : opts->cert_principals)) != 0 ||
796 	    (r = serialise_nullable_string(m,
797 	    untrusted ? "true" : opts->force_command)) != 0 ||
798 	    (r = serialise_nullable_string(m,
799 	    untrusted ? NULL : opts->required_from_host_cert)) != 0 ||
800 	    (r = serialise_nullable_string(m,
801 	     untrusted ? NULL : opts->required_from_host_keys)) != 0)
802 		return r;
803 
804 	/* Array options */
805 	if ((r = serialise_array(m, opts->env,
806 	    untrusted ? 0 : opts->nenv)) != 0 ||
807 	    (r = serialise_array(m, opts->permitopen,
808 	    untrusted ? 0 : opts->npermitopen)) != 0)
809 		return r;
810 
811 	/* success */
812 	return 0;
813 }
814 
815 int
816 sshauthopt_deserialise(struct sshbuf *m, struct sshauthopt **optsp)
817 {
818 	struct sshauthopt *opts = NULL;
819 	int r = SSH_ERR_INTERNAL_ERROR;
820 	u_char f;
821 	u_int tmp;
822 
823 	if ((opts = calloc(1, sizeof(*opts))) == NULL)
824 		return SSH_ERR_ALLOC_FAIL;
825 
826 #define OPT_FLAG(x) \
827 	do { \
828 		if ((r = sshbuf_get_u8(m, &f)) != 0) \
829 			goto out; \
830 		opts->x = f; \
831 	} while (0)
832 	OPT_FLAG(permit_port_forwarding_flag);
833 	OPT_FLAG(permit_agent_forwarding_flag);
834 	OPT_FLAG(permit_x11_forwarding_flag);
835 	OPT_FLAG(permit_pty_flag);
836 	OPT_FLAG(permit_user_rc);
837 	OPT_FLAG(restricted);
838 	OPT_FLAG(cert_authority);
839 #undef OPT_FLAG
840 
841 	if ((r = sshbuf_get_u64(m, &opts->valid_before)) != 0)
842 		goto out;
843 
844 	/* tunnel number can be negative to indicate "unset" */
845 	if ((r = sshbuf_get_u8(m, &f)) != 0 ||
846 	    (r = sshbuf_get_u32(m, &tmp)) != 0)
847 		goto out;
848 	opts->force_tun_device = f ? -1 : (int)tmp;
849 
850 	/* String options may be NULL */
851 	if ((r = deserialise_nullable_string(m, &opts->cert_principals)) != 0 ||
852 	    (r = deserialise_nullable_string(m, &opts->force_command)) != 0 ||
853 	    (r = deserialise_nullable_string(m,
854 	    &opts->required_from_host_cert)) != 0 ||
855 	    (r = deserialise_nullable_string(m,
856 	    &opts->required_from_host_keys)) != 0)
857 		goto out;
858 
859 	/* Array options */
860 	if ((r = deserialise_array(m, &opts->env, &opts->nenv)) != 0 ||
861 	    (r = deserialise_array(m,
862 	    &opts->permitopen, &opts->npermitopen)) != 0)
863 		goto out;
864 
865 	/* success */
866 	r = 0;
867 	*optsp = opts;
868 	opts = NULL;
869  out:
870 	sshauthopt_free(opts);
871 	return r;
872 }
873