-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibcage.c
493 lines (425 loc) · 13.8 KB
/
libcage.c
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
#include <ctype.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#if defined(__linux__) || defined(__FreeBSD__)
# include <sys/random.h>
#endif
#ifdef __APPLE__
# include <sys/random.h>
#endif
#include "monocypher.h"
#include "libcage.h"
#define MAX(a, b) ((a) > (b) ? (a) : (b))
/* Return on != zero */
#define RETONNZ(exp) do { int rv = (exp); if (rv != 0) { return rv; } } while (0)
/* Write a literal string `lit` to `file` */
#define FWRITE_LSTR(file, lit) (fwrite(lit, sizeof (lit) - 1, 1, file))
const uint8_t basepoint[32] = {
0x20, 0xae, 0x19, 0xa1, 0xb8, 0xa0, 0x86, 0xb4,
0xe0, 0x1e, 0xdd, 0x2c, 0x77, 0x48, 0xd1, 0x4c,
0x92, 0x3d, 0x4d, 0x7e, 0x6d, 0x7c, 0x61, 0xb2,
0x29, 0xe9, 0xc5, 0xa2, 0x7e, 0xce, 0xd3, 0xd9,
};
/* Failable, returns 0 on success, -1 on failure */
static int bech32_encode(char *output, const char *hrp, const uint8_t *data, size_t data_len);
/* Failable, returns 0 on success, -1 on failure */
static int bech32_decode(char *hrp, uint8_t *data, size_t *data_len, const char *input);
/* Infailable */
// TODO: make things const
static void convert_bits(uint8_t *out, size_t *outlen, int outbits,
const uint8_t *in, size_t inlen, int inbits);
/**
* base64_encode - Base64 encode
* @src: Data to be encoded
* @len: Length of the data to be encoded
* @out_len: Pointer to output length variable, or %NULL if not used
* Returns: Allocated buffer of out_len bytes of encoded data,
* or %NULL on failure
*
* Caller is responsible for freeing the returned buffer. Returned buffer is
* nul terminated to make it easier to use as a C string. The nul terminator is
* not included in out_len.
*/
char *base64_encode(const uint8_t *src, size_t len, size_t *out_len);
/**
* base64_decode - Base64 decode
* @src: Data to be decoded
* @len: Length of the data to be decoded
* @out_len: Pointer to output length variable
* Returns: Allocated buffer of out_len bytes of decoded data,
* or %NULL on failure
*
* Caller is responsible for freeing the returned buffer.
*/
uint8_t *base64_decode(const char *src, size_t len, size_t *out_len);
#if defined(__linux__) || defined(__FreeBSD__)
int
get_random(void *buf, size_t size)
{
return getrandom(buf, size, 0);
}
#endif
#ifdef __APPLE__
int
get_random(void *buf, size_t size)
{
return getentropy(buf, size);
}
#endif
struct CageX25519Identity
cage_new_x25519_identity_from_scalar(const uint8_t scalar[32])
{
struct CageX25519Identity ret;
crypto_x25519_public_key(ret.public_key, scalar);
memcpy(ret.secret_key, scalar, 32);
return ret;
}
int
cage_generate_x25519_identity(struct CageX25519Identity *kp)
{
uint8_t secret_key[32];
if (get_random(secret_key, sizeof (secret_key) / sizeof (char)) == -1)
return -1;
*kp = cage_new_x25519_identity_from_scalar(secret_key);
return 0;
}
int
cage_parse_x25519_identity(struct CageX25519Identity *out, const char bech32_sk[75])
{
char hrp[75 - 6];
uint8_t decoded_5bit[75 - 8];
size_t decoded_5bit_len = 0;
if (bech32_decode(hrp, decoded_5bit, &decoded_5bit_len, bech32_sk) == -1)
return -1;
uint8_t decoded[32];
size_t decoded_len = 0;
convert_bits(decoded, &decoded_len, 8, decoded_5bit, decoded_5bit_len, 5);
*out = cage_new_x25519_identity_from_scalar(decoded);
return 0;
}
struct CageHumanReadableX25519Identity
cage_format_x25519_identity(const struct CageX25519Identity *identity)
{
struct CageHumanReadableX25519Identity out;
char key_out_buf[MAX(sizeof (out.public_key), sizeof (out.secret_key))];
uint8_t converted_bits[104];
size_t converted_bits_len = 0;
convert_bits(converted_bits, &converted_bits_len, 5, identity->public_key,
sizeof (identity->public_key), 8);
bech32_encode(key_out_buf, "age", converted_bits,
converted_bits_len);
memcpy(out.public_key, key_out_buf, sizeof (out.public_key));
convert_bits(converted_bits, &converted_bits_len, 5, identity->secret_key,
sizeof (identity->secret_key), 8);
bech32_encode(key_out_buf, "age-secret-key-", converted_bits,
converted_bits_len);
for (unsigned long i = 0; i < sizeof (out.secret_key); i++)
out.secret_key[i] = toupper(key_out_buf[i]);
return out;
}
int cage_decode_x25519_pk(uint8_t *out, const char *hr_pk)
{
uint8_t converted_bits[104];
size_t bits_len = 0, out_len;
char hrp[4];
RETONNZ(bech32_decode(hrp, converted_bits, &bits_len, hr_pk));
convert_bits(out, &out_len, 8, converted_bits, bits_len, 5);
return 0;
}
// todo: this func uses get_random
static void write_x25519_recipient_stanza(FILE *out, uint8_t *recipient)
{
FWRITE_LSTR(out, "-> X25519 ");
int cur_line_len = 10;
uint8_t ephemeral_secret[32], raw_ephemeral_share[32];
get_random(ephemeral_secret, 32);
crypto_x25519(raw_ephemeral_share, ephemeral_secret, basepoint);
size_t b64data_len = 0;
char *ephemeral_share = base64_encode(raw_ephemeral_share, 32, &b64data_len);
fwrite(ephemeral_share, b64data_len, 1, out);
}
// todo: this func uses get_random
// TODO: assumes all recipients are x25519
int cage_encrypt_file(FILE *in, FILE *out, const int n_recipients, uint8_t *const *recipients)
{
uint8_t file_key[16];
get_random(file_key, 16);
FWRITE_LSTR(out, "age-encryption.org/");
FWRITE_LSTR(out, CAGE_AGE_VERSION);
FWRITE_LSTR(out, "\n");
for (int i = 0; i < n_recipients; i++)
{
write_x25519_recipient_stanza(out, recipients[i]);
}
return 0;
}
/* From <https://github.com/sipa/bech32/blob/master/ref/c> */
/* Copyright (c) 2017, 2021 Pieter Wuille
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
static void
convert_bits(
uint8_t *out,
size_t *outlen,
int outbits,
const uint8_t *in,
size_t inlen,
int inbits
) {
uint32_t val = 0;
int bits = 0;
uint32_t maxv = (((uint32_t)1) << outbits) - 1;
*outlen = 0;
while (inlen--) {
val = (val << inbits) | *(in++);
bits += inbits;
while (bits >= outbits) {
bits -= outbits;
out[(*outlen)++] = (val >> bits) & maxv;
}
}
if (bits) {
out[(*outlen)++] = (val << (outbits - bits)) & maxv;
}
}
static const char* bech_charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
static const int8_t bech_charset_rev[128] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1,
-1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1,
-1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1,
1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1
};
static uint32_t
bech32_polymod_step(uint32_t pre)
{
uint8_t b = pre >> 25;
return ((pre & 0x1FFFFFF) << 5) ^
(-((b >> 0) & 1) & 0x3b6a57b2UL) ^
(-((b >> 1) & 1) & 0x26508e6dUL) ^
(-((b >> 2) & 1) & 0x1ea119faUL) ^
(-((b >> 3) & 1) & 0x3d4233ddUL) ^
(-((b >> 4) & 1) & 0x2a1462b3UL);
}
static int
bech32_encode(char *output, const char *hrp, const uint8_t *data, size_t data_len)
{
uint32_t chk = 1;
size_t i = 0;
while (hrp[i] != 0) {
int ch = hrp[i];
if (ch < 33 || ch > 126) {
return -1;
}
if (ch >= 'A' && ch <= 'Z') return -1;
chk = bech32_polymod_step(chk) ^ (ch >> 5);
++i;
}
if (i + 7 + data_len > 90) return -1;
chk = bech32_polymod_step(chk);
while (*hrp != 0) {
chk = bech32_polymod_step(chk) ^ (*hrp & 0x1f);
*(output++) = *(hrp++);
}
*(output++) = '1';
for (i = 0; i < data_len; ++i) {
if (*data >> 5) return -1;
chk = bech32_polymod_step(chk) ^ (*data);
*(output++) = bech_charset[*(data++)];
}
for (i = 0; i < 6; ++i) {
chk = bech32_polymod_step(chk);
}
chk ^= 1;
for (i = 0; i < 6; ++i) {
*(output++) = bech_charset[(chk >> ((5 - i) * 5)) & 0x1f];
}
*output = 0;
return 0;
}
static int
bech32_decode(char* hrp, uint8_t *data, size_t *data_len, const char *input)
{
uint32_t chk = 1;
size_t i;
size_t input_len = strlen(input);
size_t hrp_len;
int have_lower = 0, have_upper = 0;
*data_len = 0;
while (*data_len < input_len && input[(input_len - 1) - *data_len] != '1') {
++(*data_len);
}
hrp_len = input_len - (1 + *data_len);
if (1 + *data_len >= input_len || *data_len < 6) {
return -1;
}
*(data_len) -= 6;
for (i = 0; i < hrp_len; ++i) {
int ch = input[i];
if (ch < 33 || ch > 126) {
return -1;
}
if (ch >= 'a' && ch <= 'z') {
have_lower = 1;
} else if (ch >= 'A' && ch <= 'Z') {
have_upper = 1;
ch = (ch - 'A') + 'a';
}
hrp[i] = ch;
chk = bech32_polymod_step(chk) ^ (ch >> 5);
}
hrp[i] = 0;
chk = bech32_polymod_step(chk);
for (i = 0; i < hrp_len; ++i) {
chk = bech32_polymod_step(chk) ^ (input[i] & 0x1f);
}
++i;
while (i < input_len) {
int v = (input[i] & 0x80) ? -1 : bech_charset_rev[(int)input[i]];
if (v == -1) {
return -1;
}
if (input[i] >= 'a' && input[i] <= 'z') have_lower = 1;
if (input[i] >= 'A' && input[i] <= 'Z') have_upper = 1;
chk = bech32_polymod_step(chk) ^ v;
if (i + 6 < input_len) {
data[i - (1 + hrp_len)] = v;
}
++i;
}
if (have_lower && have_upper) {
return -1;
}
return (chk == 1) ? 0 : -1;
}
// modified to remove = padding
/*
* Base64 encoding/decoding (RFC1341)
* Copyright (c) 2005-2011, Jouni Malinen <[email protected]>
*
* This software may be distributed under the terms of the BSD license.
*/
static const unsigned char base64_table[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *base64_encode(const uint8_t *src, size_t len, size_t *out_len)
{
char *out, *pos;
const unsigned char *end, *in;
size_t olen;
int line_len;
olen = len * 4 / 3 + 4; /* 3-byte blocks to 4-byte */
olen += olen / 72; /* line feeds */
olen++; /* nul termination */
if (olen < len)
return NULL; /* integer overflow */
out = malloc(olen);
if (out == NULL)
return NULL;
end = src + len;
in = src;
pos = out;
line_len = 0;
while (end - in >= 3) {
*pos++ = base64_table[in[0] >> 2];
*pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
*pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
*pos++ = base64_table[in[2] & 0x3f];
in += 3;
line_len += 4;
if (line_len >= 72) {
*pos++ = '\n';
line_len = 0;
}
}
if (end - in) {
*pos++ = base64_table[in[0] >> 2];
if (end - in == 1) {
*pos++ = base64_table[(in[0] & 0x03) << 4];
line_len += 2;
} else {
*pos++ = base64_table[((in[0] & 0x03) << 4) |
(in[1] >> 4)];
*pos++ = base64_table[(in[1] & 0x0f) << 2];
line_len += 3;
}
}
if (line_len)
*pos++ = '\n';
*pos = '\0';
if (out_len)
*out_len = pos - out;
return out;
}
// todo: this might fail when seeing unpadded base64, which is what age uses
uint8_t *base64_decode(const char *src, size_t len, size_t *out_len)
{
unsigned char dtable[256], *out, *pos, block[4], tmp;
size_t i, count, olen;
int pad = 0;
memset(dtable, 0x80, 256);
for (i = 0; i < sizeof(base64_table) - 1; i++)
dtable[base64_table[i]] = (unsigned char) i;
dtable['='] = 0;
count = 0;
for (i = 0; i < len; i++) {
if (dtable[src[i]] != 0x80)
count++;
}
if (count == 0 || count % 4)
return NULL;
olen = count / 4 * 3;
pos = out = malloc(olen);
if (out == NULL)
return NULL;
count = 0;
for (i = 0; i < len; i++) {
tmp = dtable[src[i]];
if (tmp == 0x80)
continue;
if (src[i] == '=')
pad++;
block[count] = tmp;
count++;
if (count == 4) {
*pos++ = (block[0] << 2) | (block[1] >> 4);
*pos++ = (block[1] << 4) | (block[2] >> 2);
*pos++ = (block[2] << 6) | block[3];
count = 0;
if (pad) {
if (pad == 1)
pos--;
else if (pad == 2)
pos -= 2;
else {
/* Invalid padding */
free(out);
return NULL;
}
break;
}
}
}
*out_len = pos - out;
return out;
}