1/* $OpenBSD: auth-options.c,v 1.84 2018/10/03 06:38:35 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 */
49static int
50opt_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
67static char *
68opt_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
100static int
101opt_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
111static int
112dup_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
140static int
141cert_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
254struct sshauthopt *
255sshauthopt_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
265void
266sshauthopt_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	for (i = 0; i < opts->npermitlisten; i++)
287		free(opts->permitlisten[i]);
288	free(opts->permitlisten);
289
290	explicit_bzero(opts, sizeof(*opts));
291	free(opts);
292}
293
294struct sshauthopt *
295sshauthopt_new_with_keys_defaults(void)
296{
297	struct sshauthopt *ret = NULL;
298
299	if ((ret = sshauthopt_new()) == NULL)
300		return NULL;
301
302	/* Defaults for authorized_keys flags */
303	ret->permit_port_forwarding_flag = 1;
304	ret->permit_agent_forwarding_flag = 1;
305	ret->permit_x11_forwarding_flag = 1;
306	ret->permit_pty_flag = 1;
307	ret->permit_user_rc = 1;
308	return ret;
309}
310
311/*
312 * Parse and record a permitopen/permitlisten directive.
313 * Return 0 on success. Return -1 on failure and sets *errstrp to error reason.
314 */
315static int
316handle_permit(const char **optsp, int allow_bare_port,
317    char ***permitsp, size_t *npermitsp, const char **errstrp)
318{
319	char *opt, *tmp, *cp, *host, **permits = *permitsp;
320	size_t npermits = *npermitsp;
321	const char *errstr = "unknown error";
322
323	if (npermits > INT_MAX) {
324		*errstrp = "too many permission directives";
325		return -1;
326	}
327	if ((opt = opt_dequote(optsp, &errstr)) == NULL) {
328		return -1;
329	}
330	if (allow_bare_port && strchr(opt, ':') == NULL) {
331		/*
332		 * Allow a bare port number in permitlisten to indicate a
333		 * listen_host wildcard.
334		 */
335		if (asprintf(&tmp, "*:%s", opt) < 0) {
336			*errstrp = "memory allocation failed";
337			return -1;
338		}
339		free(opt);
340		opt = tmp;
341	}
342	if ((tmp = strdup(opt)) == NULL) {
343		free(opt);
344		*errstrp = "memory allocation failed";
345		return -1;
346	}
347	cp = tmp;
348	/* validate syntax before recording it. */
349	host = hpdelim(&cp);
350	if (host == NULL || strlen(host) >= NI_MAXHOST) {
351		free(tmp);
352		free(opt);
353		*errstrp = "invalid permission hostname";
354		return -1;
355	}
356	/*
357	 * don't want to use permitopen_port to avoid
358	 * dependency on channels.[ch] here.
359	 */
360	if (cp == NULL ||
361	    (strcmp(cp, "*") != 0 && a2port(cp) <= 0)) {
362		free(tmp);
363		free(opt);
364		*errstrp = "invalid permission port";
365		return -1;
366	}
367	/* XXX - add streamlocal support */
368	free(tmp);
369	/* Record it */
370	if ((permits = recallocarray(permits, npermits, npermits + 1,
371	    sizeof(*permits))) == NULL) {
372		free(opt);
373		/* NB. don't update *permitsp if alloc fails */
374		*errstrp = "memory allocation failed";
375		return -1;
376	}
377	permits[npermits++] = opt;
378	*permitsp = permits;
379	*npermitsp = npermits;
380	return 0;
381}
382
383struct sshauthopt *
384sshauthopt_parse(const char *opts, const char **errstrp)
385{
386	char **oarray, *opt, *cp, *tmp;
387	int r;
388	struct sshauthopt *ret = NULL;
389	const char *errstr = "unknown error";
390	uint64_t valid_before;
391
392	if (errstrp != NULL)
393		*errstrp = NULL;
394	if ((ret = sshauthopt_new_with_keys_defaults()) == NULL)
395		goto alloc_fail;
396
397	if (opts == NULL)
398		return ret;
399
400	while (*opts && *opts != ' ' && *opts != '\t') {
401		/* flag options */
402		if ((r = opt_flag("restrict", 0, &opts)) != -1) {
403			ret->restricted = 1;
404			ret->permit_port_forwarding_flag = 0;
405			ret->permit_agent_forwarding_flag = 0;
406			ret->permit_x11_forwarding_flag = 0;
407			ret->permit_pty_flag = 0;
408			ret->permit_user_rc = 0;
409		} else if ((r = opt_flag("cert-authority", 0, &opts)) != -1) {
410			ret->cert_authority = r;
411		} else if ((r = opt_flag("port-forwarding", 1, &opts)) != -1) {
412			ret->permit_port_forwarding_flag = r == 1;
413		} else if ((r = opt_flag("agent-forwarding", 1, &opts)) != -1) {
414			ret->permit_agent_forwarding_flag = r == 1;
415		} else if ((r = opt_flag("x11-forwarding", 1, &opts)) != -1) {
416			ret->permit_x11_forwarding_flag = r == 1;
417		} else if ((r = opt_flag("pty", 1, &opts)) != -1) {
418			ret->permit_pty_flag = r == 1;
419		} else if ((r = opt_flag("user-rc", 1, &opts)) != -1) {
420			ret->permit_user_rc = r == 1;
421		} else if (opt_match(&opts, "command")) {
422			if (ret->force_command != NULL) {
423				errstr = "multiple \"command\" clauses";
424				goto fail;
425			}
426			ret->force_command = opt_dequote(&opts, &errstr);
427			if (ret->force_command == NULL)
428				goto fail;
429		} else if (opt_match(&opts, "principals")) {
430			if (ret->cert_principals != NULL) {
431				errstr = "multiple \"principals\" clauses";
432				goto fail;
433			}
434			ret->cert_principals = opt_dequote(&opts, &errstr);
435			if (ret->cert_principals == NULL)
436				goto fail;
437		} else if (opt_match(&opts, "from")) {
438			if (ret->required_from_host_keys != NULL) {
439				errstr = "multiple \"from\" clauses";
440				goto fail;
441			}
442			ret->required_from_host_keys = opt_dequote(&opts,
443			    &errstr);
444			if (ret->required_from_host_keys == NULL)
445				goto fail;
446		} else if (opt_match(&opts, "expiry-time")) {
447			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
448				goto fail;
449			if (parse_absolute_time(opt, &valid_before) != 0 ||
450			    valid_before == 0) {
451				free(opt);
452				errstr = "invalid expires time";
453				goto fail;
454			}
455			free(opt);
456			if (ret->valid_before == 0 ||
457			    valid_before < ret->valid_before)
458				ret->valid_before = valid_before;
459		} else if (opt_match(&opts, "environment")) {
460			if (ret->nenv > INT_MAX) {
461				errstr = "too many environment strings";
462				goto fail;
463			}
464			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
465				goto fail;
466			/* env name must be alphanumeric and followed by '=' */
467			if ((tmp = strchr(opt, '=')) == NULL) {
468				free(opt);
469				errstr = "invalid environment string";
470				goto fail;
471			}
472			if ((cp = strdup(opt)) == NULL)
473				goto alloc_fail;
474			cp[tmp - opt] = '\0'; /* truncate at '=' */
475			if (!valid_env_name(cp)) {
476				free(cp);
477				free(opt);
478				errstr = "invalid environment string";
479				goto fail;
480			}
481			free(cp);
482			/* Append it. */
483			oarray = ret->env;
484			if ((ret->env = recallocarray(ret->env, ret->nenv,
485			    ret->nenv + 1, sizeof(*ret->env))) == NULL) {
486				free(opt);
487				ret->env = oarray; /* put it back for cleanup */
488				goto alloc_fail;
489			}
490			ret->env[ret->nenv++] = opt;
491		} else if (opt_match(&opts, "permitopen")) {
492			if (handle_permit(&opts, 0, &ret->permitopen,
493			    &ret->npermitopen, &errstr) != 0)
494				goto fail;
495		} else if (opt_match(&opts, "permitlisten")) {
496			if (handle_permit(&opts, 1, &ret->permitlisten,
497			    &ret->npermitlisten, &errstr) != 0)
498				goto fail;
499		} else if (opt_match(&opts, "tunnel")) {
500			if ((opt = opt_dequote(&opts, &errstr)) == NULL)
501				goto fail;
502			ret->force_tun_device = a2tun(opt, NULL);
503			free(opt);
504			if (ret->force_tun_device == SSH_TUNID_ERR) {
505				errstr = "invalid tun device";
506				goto fail;
507			}
508		}
509		/*
510		 * Skip the comma, and move to the next option
511		 * (or break out if there are no more).
512		 */
513		if (*opts == '\0' || *opts == ' ' || *opts == '\t')
514			break;		/* End of options. */
515		/* Anything other than a comma is an unknown option */
516		if (*opts != ',') {
517			errstr = "unknown key option";
518			goto fail;
519		}
520		opts++;
521		if (*opts == '\0') {
522			errstr = "unexpected end-of-options";
523			goto fail;
524		}
525	}
526
527	/* success */
528	if (errstrp != NULL)
529		*errstrp = NULL;
530	return ret;
531
532alloc_fail:
533	errstr = "memory allocation failed";
534fail:
535	sshauthopt_free(ret);
536	if (errstrp != NULL)
537		*errstrp = errstr;
538	return NULL;
539}
540
541struct sshauthopt *
542sshauthopt_from_cert(struct sshkey *k)
543{
544	struct sshauthopt *ret;
545
546	if (k == NULL || !sshkey_type_is_cert(k->type) || k->cert == NULL ||
547	    k->cert->type != SSH2_CERT_TYPE_USER)
548		return NULL;
549
550	if ((ret = sshauthopt_new()) == NULL)
551		return NULL;
552
553	/* Handle options and critical extensions separately */
554	if (cert_option_list(ret, k->cert->critical,
555	    OPTIONS_CRITICAL, 1) == -1) {
556		sshauthopt_free(ret);
557		return NULL;
558	}
559	if (cert_option_list(ret, k->cert->extensions,
560	    OPTIONS_EXTENSIONS, 0) == -1) {
561		sshauthopt_free(ret);
562		return NULL;
563	}
564	/* success */
565	return ret;
566}
567
568/*
569 * Merges "additional" options to "primary" and returns the result.
570 * NB. Some options from primary have primacy.
571 */
572struct sshauthopt *
573sshauthopt_merge(const struct sshauthopt *primary,
574    const struct sshauthopt *additional, const char **errstrp)
575{
576	struct sshauthopt *ret;
577	const char *errstr = "internal error";
578	const char *tmp;
579
580	if (errstrp != NULL)
581		*errstrp = NULL;
582
583	if ((ret = sshauthopt_new()) == NULL)
584		goto alloc_fail;
585
586	/* cert_authority and cert_principals are cleared in result */
587
588	/* Prefer access lists from primary. */
589	/* XXX err is both set and mismatch? */
590	tmp = primary->required_from_host_cert;
591	if (tmp == NULL)
592		tmp = additional->required_from_host_cert;
593	if (tmp != NULL && (ret->required_from_host_cert = strdup(tmp)) == NULL)
594		goto alloc_fail;
595	tmp = primary->required_from_host_keys;
596	if (tmp == NULL)
597		tmp = additional->required_from_host_keys;
598	if (tmp != NULL && (ret->required_from_host_keys = strdup(tmp)) == NULL)
599		goto alloc_fail;
600
601	/*
602	 * force_tun_device, permitopen/permitlisten and environment all
603	 * prefer the primary.
604	 */
605	ret->force_tun_device = primary->force_tun_device;
606	if (ret->force_tun_device == -1)
607		ret->force_tun_device = additional->force_tun_device;
608	if (primary->nenv > 0) {
609		if (dup_strings(&ret->env, &ret->nenv,
610		    primary->env, primary->nenv) != 0)
611			goto alloc_fail;
612	} else if (additional->nenv) {
613		if (dup_strings(&ret->env, &ret->nenv,
614		    additional->env, additional->nenv) != 0)
615			goto alloc_fail;
616	}
617	if (primary->npermitopen > 0) {
618		if (dup_strings(&ret->permitopen, &ret->npermitopen,
619		    primary->permitopen, primary->npermitopen) != 0)
620			goto alloc_fail;
621	} else if (additional->npermitopen > 0) {
622		if (dup_strings(&ret->permitopen, &ret->npermitopen,
623		    additional->permitopen, additional->npermitopen) != 0)
624			goto alloc_fail;
625	}
626
627	if (primary->npermitlisten > 0) {
628		if (dup_strings(&ret->permitlisten, &ret->npermitlisten,
629		    primary->permitlisten, primary->npermitlisten) != 0)
630			goto alloc_fail;
631	} else if (additional->npermitlisten > 0) {
632		if (dup_strings(&ret->permitlisten, &ret->npermitlisten,
633		    additional->permitlisten, additional->npermitlisten) != 0)
634			goto alloc_fail;
635	}
636
637	/* Flags are logical-AND (i.e. must be set in both for permission) */
638#define OPTFLAG(x) ret->x = (primary->x == 1) && (additional->x == 1)
639	OPTFLAG(permit_port_forwarding_flag);
640	OPTFLAG(permit_agent_forwarding_flag);
641	OPTFLAG(permit_x11_forwarding_flag);
642	OPTFLAG(permit_pty_flag);
643	OPTFLAG(permit_user_rc);
644#undef OPTFLAG
645
646	/* Earliest expiry time should win */
647	if (primary->valid_before != 0)
648		ret->valid_before = primary->valid_before;
649	if (additional->valid_before != 0 &&
650	    additional->valid_before < ret->valid_before)
651		ret->valid_before = additional->valid_before;
652
653	/*
654	 * When both multiple forced-command are specified, only
655	 * proceed if they are identical, otherwise fail.
656	 */
657	if (primary->force_command != NULL &&
658	    additional->force_command != NULL) {
659		if (strcmp(primary->force_command,
660		    additional->force_command) == 0) {
661			/* ok */
662			ret->force_command = strdup(primary->force_command);
663			if (ret->force_command == NULL)
664				goto alloc_fail;
665		} else {
666			errstr = "forced command options do not match";
667			goto fail;
668		}
669	} else if (primary->force_command != NULL) {
670		if ((ret->force_command = strdup(
671		    primary->force_command)) == NULL)
672			goto alloc_fail;
673	} else if (additional->force_command != NULL) {
674		if ((ret->force_command = strdup(
675		    additional->force_command)) == NULL)
676			goto alloc_fail;
677	}
678	/* success */
679	if (errstrp != NULL)
680		*errstrp = NULL;
681	return ret;
682
683 alloc_fail:
684	errstr = "memory allocation failed";
685 fail:
686	if (errstrp != NULL)
687		*errstrp = errstr;
688	sshauthopt_free(ret);
689	return NULL;
690}
691
692/*
693 * Copy options
694 */
695struct sshauthopt *
696sshauthopt_copy(const struct sshauthopt *orig)
697{
698	struct sshauthopt *ret;
699
700	if ((ret = sshauthopt_new()) == NULL)
701		return NULL;
702
703#define OPTSCALAR(x) ret->x = orig->x
704	OPTSCALAR(permit_port_forwarding_flag);
705	OPTSCALAR(permit_agent_forwarding_flag);
706	OPTSCALAR(permit_x11_forwarding_flag);
707	OPTSCALAR(permit_pty_flag);
708	OPTSCALAR(permit_user_rc);
709	OPTSCALAR(restricted);
710	OPTSCALAR(cert_authority);
711	OPTSCALAR(force_tun_device);
712	OPTSCALAR(valid_before);
713#undef OPTSCALAR
714#define OPTSTRING(x) \
715	do { \
716		if (orig->x != NULL && (ret->x = strdup(orig->x)) == NULL) { \
717			sshauthopt_free(ret); \
718			return NULL; \
719		} \
720	} while (0)
721	OPTSTRING(cert_principals);
722	OPTSTRING(force_command);
723	OPTSTRING(required_from_host_cert);
724	OPTSTRING(required_from_host_keys);
725#undef OPTSTRING
726
727	if (dup_strings(&ret->env, &ret->nenv, orig->env, orig->nenv) != 0 ||
728	    dup_strings(&ret->permitopen, &ret->npermitopen,
729	    orig->permitopen, orig->npermitopen) != 0 ||
730	    dup_strings(&ret->permitlisten, &ret->npermitlisten,
731	    orig->permitlisten, orig->npermitlisten) != 0) {
732		sshauthopt_free(ret);
733		return NULL;
734	}
735	return ret;
736}
737
738static int
739serialise_array(struct sshbuf *m, char **a, size_t n)
740{
741	struct sshbuf *b;
742	size_t i;
743	int r;
744
745	if (n > INT_MAX)
746		return SSH_ERR_INTERNAL_ERROR;
747
748	if ((b = sshbuf_new()) == NULL) {
749		return SSH_ERR_ALLOC_FAIL;
750	}
751	for (i = 0; i < n; i++) {
752		if ((r = sshbuf_put_cstring(b, a[i])) != 0) {
753			sshbuf_free(b);
754			return r;
755		}
756	}
757	if ((r = sshbuf_put_u32(m, n)) != 0 ||
758	    (r = sshbuf_put_stringb(m, b)) != 0) {
759		sshbuf_free(b);
760		return r;
761	}
762	/* success */
763	return 0;
764}
765
766static int
767deserialise_array(struct sshbuf *m, char ***ap, size_t *np)
768{
769	char **a = NULL;
770	size_t i, n = 0;
771	struct sshbuf *b = NULL;
772	u_int tmp;
773	int r = SSH_ERR_INTERNAL_ERROR;
774
775	if ((r = sshbuf_get_u32(m, &tmp)) != 0 ||
776	    (r = sshbuf_froms(m, &b)) != 0)
777		goto out;
778	if (tmp > INT_MAX) {
779		r = SSH_ERR_INVALID_FORMAT;
780		goto out;
781	}
782	n = tmp;
783	if (n > 0 && (a = calloc(n, sizeof(*a))) == NULL) {
784		r = SSH_ERR_ALLOC_FAIL;
785		goto out;
786	}
787	for (i = 0; i < n; i++) {
788		if ((r = sshbuf_get_cstring(b, &a[i], NULL)) != 0)
789			goto out;
790	}
791	/* success */
792	r = 0;
793	*ap = a;
794	a = NULL;
795	*np = n;
796	n = 0;
797 out:
798	for (i = 0; i < n; i++)
799		free(a[i]);
800	free(a);
801	sshbuf_free(b);
802	return r;
803}
804
805static int
806serialise_nullable_string(struct sshbuf *m, const char *s)
807{
808	int r;
809
810	if ((r = sshbuf_put_u8(m, s == NULL)) != 0 ||
811	    (r = sshbuf_put_cstring(m, s)) != 0)
812		return r;
813	return 0;
814}
815
816static int
817deserialise_nullable_string(struct sshbuf *m, char **sp)
818{
819	int r;
820	u_char flag;
821
822	*sp = NULL;
823	if ((r = sshbuf_get_u8(m, &flag)) != 0 ||
824	    (r = sshbuf_get_cstring(m, flag ? NULL : sp, NULL)) != 0)
825		return r;
826	return 0;
827}
828
829int
830sshauthopt_serialise(const struct sshauthopt *opts, struct sshbuf *m,
831    int untrusted)
832{
833	int r = SSH_ERR_INTERNAL_ERROR;
834
835	/* Flag and simple integer options */
836	if ((r = sshbuf_put_u8(m, opts->permit_port_forwarding_flag)) != 0 ||
837	    (r = sshbuf_put_u8(m, opts->permit_agent_forwarding_flag)) != 0 ||
838	    (r = sshbuf_put_u8(m, opts->permit_x11_forwarding_flag)) != 0 ||
839	    (r = sshbuf_put_u8(m, opts->permit_pty_flag)) != 0 ||
840	    (r = sshbuf_put_u8(m, opts->permit_user_rc)) != 0 ||
841	    (r = sshbuf_put_u8(m, opts->restricted)) != 0 ||
842	    (r = sshbuf_put_u8(m, opts->cert_authority)) != 0 ||
843	    (r = sshbuf_put_u64(m, opts->valid_before)) != 0)
844		return r;
845
846	/* tunnel number can be negative to indicate "unset" */
847	if ((r = sshbuf_put_u8(m, opts->force_tun_device == -1)) != 0 ||
848	    (r = sshbuf_put_u32(m, (opts->force_tun_device < 0) ?
849	    0 : (u_int)opts->force_tun_device)) != 0)
850		return r;
851
852	/* String options; these may be NULL */
853	if ((r = serialise_nullable_string(m,
854	    untrusted ? "yes" : opts->cert_principals)) != 0 ||
855	    (r = serialise_nullable_string(m,
856	    untrusted ? "true" : opts->force_command)) != 0 ||
857	    (r = serialise_nullable_string(m,
858	    untrusted ? NULL : opts->required_from_host_cert)) != 0 ||
859	    (r = serialise_nullable_string(m,
860	     untrusted ? NULL : opts->required_from_host_keys)) != 0)
861		return r;
862
863	/* Array options */
864	if ((r = serialise_array(m, opts->env,
865	    untrusted ? 0 : opts->nenv)) != 0 ||
866	    (r = serialise_array(m, opts->permitopen,
867	    untrusted ? 0 : opts->npermitopen)) != 0 ||
868	    (r = serialise_array(m, opts->permitlisten,
869	    untrusted ? 0 : opts->npermitlisten)) != 0)
870		return r;
871
872	/* success */
873	return 0;
874}
875
876int
877sshauthopt_deserialise(struct sshbuf *m, struct sshauthopt **optsp)
878{
879	struct sshauthopt *opts = NULL;
880	int r = SSH_ERR_INTERNAL_ERROR;
881	u_char f;
882	u_int tmp;
883
884	if ((opts = calloc(1, sizeof(*opts))) == NULL)
885		return SSH_ERR_ALLOC_FAIL;
886
887#define OPT_FLAG(x) \
888	do { \
889		if ((r = sshbuf_get_u8(m, &f)) != 0) \
890			goto out; \
891		opts->x = f; \
892	} while (0)
893	OPT_FLAG(permit_port_forwarding_flag);
894	OPT_FLAG(permit_agent_forwarding_flag);
895	OPT_FLAG(permit_x11_forwarding_flag);
896	OPT_FLAG(permit_pty_flag);
897	OPT_FLAG(permit_user_rc);
898	OPT_FLAG(restricted);
899	OPT_FLAG(cert_authority);
900#undef OPT_FLAG
901
902	if ((r = sshbuf_get_u64(m, &opts->valid_before)) != 0)
903		goto out;
904
905	/* tunnel number can be negative to indicate "unset" */
906	if ((r = sshbuf_get_u8(m, &f)) != 0 ||
907	    (r = sshbuf_get_u32(m, &tmp)) != 0)
908		goto out;
909	opts->force_tun_device = f ? -1 : (int)tmp;
910
911	/* String options may be NULL */
912	if ((r = deserialise_nullable_string(m, &opts->cert_principals)) != 0 ||
913	    (r = deserialise_nullable_string(m, &opts->force_command)) != 0 ||
914	    (r = deserialise_nullable_string(m,
915	    &opts->required_from_host_cert)) != 0 ||
916	    (r = deserialise_nullable_string(m,
917	    &opts->required_from_host_keys)) != 0)
918		goto out;
919
920	/* Array options */
921	if ((r = deserialise_array(m, &opts->env, &opts->nenv)) != 0 ||
922	    (r = deserialise_array(m,
923	    &opts->permitopen, &opts->npermitopen)) != 0 ||
924	    (r = deserialise_array(m,
925	    &opts->permitlisten, &opts->npermitlisten)) != 0)
926		goto out;
927
928	/* success */
929	r = 0;
930	*optsp = opts;
931	opts = NULL;
932 out:
933	sshauthopt_free(opts);
934	return r;
935}
936