summaryrefslogtreecommitdiffstats
path: root/src/authkey.c
blob: 761562b26a1ed4f7a1477d0b4ac24292e8115f27 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
 * Copyright (c) 2018-2022 Yubico AB. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "fido.h"

static int
parse_authkey(const cbor_item_t *key, const cbor_item_t *val, void *arg)
{
	es256_pk_t *authkey = arg;

	if (cbor_isa_uint(key) == false ||
	    cbor_int_get_width(key) != CBOR_INT_8 ||
	    cbor_get_uint8(key) != 1) {
		fido_log_debug("%s: cbor type", __func__);
		return (0); /* ignore */
	}

	return (es256_pk_decode(val, authkey));
}

static int
fido_dev_authkey_tx(fido_dev_t *dev, int *ms)
{
	fido_blob_t	 f;
	cbor_item_t	*argv[2];
	int		 r;

	fido_log_debug("%s: dev=%p", __func__, (void *)dev);

	memset(&f, 0, sizeof(f));
	memset(argv, 0, sizeof(argv));

	/* add command parameters */
	if ((argv[0] = cbor_encode_pin_opt(dev)) == NULL ||
	    (argv[1] = cbor_build_uint8(2)) == NULL) {
		fido_log_debug("%s: cbor_build", __func__);
		r = FIDO_ERR_INTERNAL;
		goto fail;
	}

	/* frame and transmit */
	if (cbor_build_frame(CTAP_CBOR_CLIENT_PIN, argv, nitems(argv),
	    &f) < 0 || fido_tx(dev, CTAP_CMD_CBOR, f.ptr, f.len, ms) < 0) {
		fido_log_debug("%s: fido_tx", __func__);
		r = FIDO_ERR_TX;
		goto fail;
	}

	r = FIDO_OK;
fail:
	cbor_vector_free(argv, nitems(argv));
	free(f.ptr);

	return (r);
}

static int
fido_dev_authkey_rx(fido_dev_t *dev, es256_pk_t *authkey, int *ms)
{
	unsigned char	*msg;
	int		 msglen;
	int		 r;

	fido_log_debug("%s: dev=%p, authkey=%p, ms=%d", __func__, (void *)dev,
	    (void *)authkey, *ms);

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

	if ((msg = malloc(FIDO_MAXMSG)) == NULL) {
		r = FIDO_ERR_INTERNAL;
		goto out;
	}

	if ((msglen = fido_rx(dev, CTAP_CMD_CBOR, msg, FIDO_MAXMSG, ms)) < 0) {
		fido_log_debug("%s: fido_rx", __func__);
		r = FIDO_ERR_RX;
		goto out;
	}

	r = cbor_parse_reply(msg, (size_t)msglen, authkey, parse_authkey);
out:
	freezero(msg, FIDO_MAXMSG);

	return (r);
}

static int
fido_dev_authkey_wait(fido_dev_t *dev, es256_pk_t *authkey, int *ms)
{
	int r;

	if ((r = fido_dev_authkey_tx(dev, ms)) != FIDO_OK ||
	    (r = fido_dev_authkey_rx(dev, authkey, ms)) != FIDO_OK)
		return (r);

	return (FIDO_OK);
}

int
fido_dev_authkey(fido_dev_t *dev, es256_pk_t *authkey, int *ms)
{
	return (fido_dev_authkey_wait(dev, authkey, ms));
}