aboutsummaryrefslogtreecommitdiffstats
path: root/libsecauth_parse_spec.c
blob: e1b0e7d39608d348ec7a2695a24a3cd4577b672f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* See LICENSE file for copyright and license details. */
#include "libsecauth.h"

#include <ctype.h>
#include <errno.h>
#include <string.h>


static char *
get_subhash(char *s, char **endp)
{
	size_t depth = 0;
	char *ret;

	if (s[0] == '{' && s[1] == '$') {
		s = ret = &s[2];
		depth += 1;
	} else {
		ret = s;
	}
	for (; s[0]; s++) {
		if (s[0] == '{' && s[1] == '$' && s[-1] == '$') {
			depth += 1;
		} else if (s[0] == '}' && s[1] == '$' && s[-1] == '$') {
			if (!depth)
				return NULL;
			if (!--depth) {
				s[-1] = '\0';
				*s++ = '\0';
				*s++ = '\0';
				*endp = s;
				return ret;
			}
		} else if (s[0] == '$' && !depth) {
			*s++ = '\0';
			*endp = s;
			return ret;
		}
	}

	return NULL;
}

static int
strtou32(const char *s, uint32_t *valp)
{
	for (*valp = 0; isdigit(*s); s++) {
		if (*valp > (UINT32_MAX - (uint32_t)(*s & 15)) / 10)
			return -1;
		*valp = *valp * 10 + (uint32_t)(*s & 15);
	}
	return *s ? -1 : 0;
}

int
libsecauth_parse_spec(struct libsecauth_spec *spec, char *s)
{
	const char *client_rounds, *server_rounds;
	size_t slen = strlen(s);
	char *sorig = s;

	memset(spec, 0, sizeof(*spec));

	if (strncmp(s, "$secauth$", sizeof("$secauth$") - 1))
		goto invalid;
	s = &s[sizeof("$secauth$") - 1];

	spec->prehash  = get_subhash(s, &s);
	spec->xferhash = get_subhash(s, &s);
	client_rounds  = get_subhash(s, &s);
	server_rounds  = get_subhash(s, &s);
	spec->posthash = get_subhash(s, &s);
	spec->expected = s;

	if (client_rounds && strtou32(client_rounds, &spec->client_rounds))
		goto invalid;
	if (server_rounds && strtou32(server_rounds, &spec->server_rounds))
		goto invalid;

	if (strchr(s, '$'))
		goto invalid;

	return 0;

invalid:
	memset(sorig, 0, slen);
	errno = EINVAL;
	return -1;
}