aboutsummaryrefslogtreecommitdiff
path: root/crypto.c
blob: e78032e016d5a67ef1faa4b4b4ec856f88d60552 (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
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
/* This file is part of libbrandt.
 * Copyright (C) 2016 GNUnet e.V.
 *
 * libbrandt is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * libbrandt is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * libbrandt.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @file crypto.c
 * @brief Implementation of the crypto primitives.
 */

#include <arpa/inet.h>

#include "crypto.h"
#include "util.h"

#define CURVE "Ed25519"

struct brandt_ec_skey {
	unsigned char d[256 / 8];
};

struct brandt_ec_pkey {
	unsigned char q_y[256 / 8];
};

gcry_mpi_point_t ec_gen;
gcry_ctx_t ec_ctx;

void
brandt_crypto_init ()
{
	gcry_error_t rc;

	rc = gcry_mpi_ec_new (&ec_ctx, NULL, CURVE);
	brandt_assert_gpgerr (rc);
	ec_gen = gcry_mpi_ec_get_point ("g", ec_ctx, 0);
	brandt_assert (NULL != ec_gen);
}

/* --- RANDOM --- */

void
brandt_rand_poll ()
{
	static unsigned char rand_amount = 255;

	if (!(rand_amount--))
		gcry_fast_random_poll ();
}

/* --- HASHING --- */

/**
 * Hash block of given size.
 *
 * @param block the data to #brandt_hash, length is given as a second argument
 * @param size the length of the data to #brandt_hash in @a block
 * @param ret pointer to where to write the hashcode
 */
void
brandt_hash (const void *block, size_t size, struct brandt_hash_code *ret)
{
	gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size);
}

/* --- MPI --- */

/**
 * If target != size, move @a target bytes to the end of the size-sized
 * buffer and zero out the first @a target - @a size bytes.
 *
 * @param buf original buffer
 * @param size number of bytes in @a buf
 * @param target target size of the buffer
 */
static void
adjust (void *buf, size_t size, size_t target)
{
	char *p = buf;

	if (size < target)
	{
		memmove (&p[target - size], buf, size);
		memset (buf, 0, target - size);
	}
}

/**
 * Output the given MPI value to the given buffer in
 * network byte order.
 * The MPI @a val may not be negative.
 *
 * @param buf where to output to
 * @param size number of bytes in @a buf
 * @param val value to write to @a buf
 */
void
brandt_mpi_print_unsigned (void *buf, size_t size, gcry_mpi_t val)
{
	size_t       rsize;
	gcry_error_t rc;

	if (gcry_mpi_get_flag (val, GCRYMPI_FLAG_OPAQUE))
	{
		/* Store opaque MPIs left aligned into the buffer.  */
		unsigned int nbits;
		const void   *p;

		p = gcry_mpi_get_opaque (val, &nbits);
		brandt_assert (NULL != p);
		rsize = (nbits + 7) / 8;
		if (rsize > size)
			rsize = size;
		memcpy (buf, p, rsize);
		if (rsize < size)
			memset (((char *)buf) + rsize, 0, size - rsize);
	}
	else
	{
		/* Store regular MPIs as unsigned integers right aligned into the buffer. */
		rsize = size;
		rc = gcry_mpi_print (GCRYMPI_FMT_USG, buf, rsize, &rsize, val);
		brandt_assert_gpgerr (rc);
		adjust (buf, rsize, size);
	}
}

/**
 * Convert data buffer into MPI value.
 * The buffer is interpreted as network
 * byte order, unsigned integer.
 *
 * @param result where to store MPI value (allocated)
 * @param data raw data (GCRYMPI_FMT_USG)
 * @param size number of bytes in @a data
 */
void
brandt_mpi_scan_unsigned (gcry_mpi_t *result, const void *data, size_t size)
{
	gcry_error_t rc;

	rc = gcry_mpi_scan (result, GCRYMPI_FMT_USG, data, size, &size);
	brandt_assert_gpgerr (rc);
}

/*
gcry_mpi_point_t
deserialize_point(const struct brandt_point* data, const int len)
{
	gcry_sexp_t s;
	gcry_ctx_t ctx;
	gcry_mpi_point_t ret;
	gcry_error_t rc;

	rc = gcry_sexp_build(&s, NULL, "(public-key(ecc(curve " CURVE ")(q %b)))",
						 len, data);
	brandt_assert_gpgerr(rc);

	rc = gcry_mpi_ec_new(&ctx, s, NULL);
	brandt_assert_gpgerr(rc);
	gcry_sexp_release(s);

	ret = gcry_mpi_ec_get_point("q", ctx, 0);
	brandt_assert(ret);
	gcry_ctx_release(ctx);
	return ret;
}
*/

/* --- EC --- */

/**
 * Extract values from an S-expression.
 *
 * @param array where to store the result(s)
 * @param sexp S-expression to parse
 * @param topname top-level name in the S-expression that is of interest
 * @param elems names of the elements to extract
 * @return 0 on success
 */
static int
key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp, const char *topname,
               const char *elems)
{
	gcry_sexp_t  list;
	gcry_sexp_t  l2;
	const char   *s;
	unsigned int i;
	unsigned int idx;

	list = gcry_sexp_find_token (sexp, topname, 0);
	if (!list)
		return 1;
	l2 = gcry_sexp_cadr (list);
	gcry_sexp_release (list);
	list = l2;
	if (!list)
		return 2;
	idx = 0;
	for (s = elems; *s; s++, idx++)
	{
		l2 = gcry_sexp_find_token (list, s, 1);
		if (!l2)
		{
			for (i = 0; i < idx; i++)
			{
				gcry_free (array[i]);
				array[i] = NULL;
			}
			gcry_sexp_release (list);
			return 3;                 /* required parameter not found */
		}
		array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
		gcry_sexp_release (l2);
		if (!array[idx])
		{
			for (i = 0; i < idx; i++)
			{
				gcry_free (array[i]);
				array[i] = NULL;
			}
			gcry_sexp_release (list);
			return 4;                 /* required parameter is invalid */
		}
	}
	gcry_sexp_release (list);
	return 0;
}

void
brandt_ec_skey_create (gcry_mpi_t* skey)
{
	gcry_sexp_t  s_keyparam;
	gcry_sexp_t  priv_sexp;
	gcry_mpi_t   d;
	gcry_error_t rc;

	rc = gcry_sexp_build (&s_keyparam, NULL, "(genkey(ecc(curve \"" CURVE "\")"
	                      "(flags)))");
	brandt_assert_gpgerr (rc);
	rc = gcry_pk_genkey (&priv_sexp, s_keyparam);
	brandt_assert_gpgerr (rc);
	gcry_sexp_release (s_keyparam);
	rc = key_from_sexp (skey, priv_sexp, "private-key", "d");
	brandt_assert_gpgerr (rc);
	gcry_sexp_release (priv_sexp);
}


void
brandt_ec_pkey_compute (gcry_mpi_point_t* pkey, const gcry_mpi_t skey)
{

}


void
brandt_ec_keypair_create (gcry_mpi_point_t* pkey, gcry_mpi_t* skey)
{
	gcry_error_t rc;
	gcry_sexp_t  s_keyparam;
	gcry_sexp_t  priv_sexp;
	gcry_ctx_t   ctx;

	rc = gcry_sexp_build (&s_keyparam, NULL, "(genkey(ecc(curve \"" CURVE "\")"
	                      "(flags)))");
	brandt_assert_gpgerr (rc);

	rc = gcry_pk_genkey (&priv_sexp, s_keyparam);
	brandt_assert_gpgerr (rc);
	gcry_sexp_release (s_keyparam);

	rc = key_from_sexp (skey, priv_sexp, "private-key", "d");
	brandt_assert_gpgerr (rc);

	rc = gcry_mpi_ec_new (&ctx, priv_sexp, NULL);
	brandt_assert_gpgerr (rc);
	gcry_sexp_release (priv_sexp);

	*pkey = gcry_mpi_ec_get_point("q", ctx, 0);
	brandt_assert (NULL != *pkey);
	gcry_ctx_release (ctx);
}


/**
 * Convert the given private key from the network format to the
 * S-expression that can be used by libgcrypt.
 *
 * @param priv private key to decode
 * @return NULL on error
 */
static gcry_sexp_t
decode_private_ecdhe_key (const struct brandt_ec_skey *priv)
{
	gcry_sexp_t  result;
	gcry_error_t rc;

	rc = gcry_sexp_build (&result, NULL,
	                      "(private-key(ecc(curve \"" CURVE "\")"
	                      "(d %b)))",
	                      (int)sizeof (priv->d), priv->d);
	brandt_assert_gpgerr (rc);
	return result;
}

/**
 * Extract the public key for the given private key.
 *
 * @param priv the private key
 * @param pub where to write the public key
 */
void
brandt_ecdhe_key_get_public (const struct brandt_ec_skey *priv,
                             struct brandt_ec_pkey       *pub)
{
	gcry_sexp_t  sexp;
	gcry_ctx_t   ctx;
	gcry_mpi_t   q;
	gcry_error_t rc;

	sexp = decode_private_ecdhe_key (priv);
	brandt_assert (NULL != sexp);
	rc = gcry_mpi_ec_new (&ctx, sexp, NULL);
	brandt_assert_gpgerr (rc);
	gcry_sexp_release (sexp);
	q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0);
	brandt_assert (NULL != q);
	brandt_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q);
	gcry_mpi_release (q);
	gcry_ctx_release (ctx);
}

/**
 * Derive key material from a public and a private ECDHE key.
 *
 * @param priv private key to use for the ECDH (x)
 * @param pub public key to use for the ECDH (yG)
 * @param key_material where to write the key material (xyG)
 * @return 0 on error, 1 on success
 */
int
brandt_ecdhe (const struct brandt_ec_skey *priv,
              const struct brandt_ec_pkey *pub,
              struct brandt_hash_code      *key_material)
{
	gcry_error_t     rc;
	int              rc2;
	gcry_mpi_point_t result;
	gcry_mpi_point_t q;
	gcry_mpi_t       d;
	gcry_ctx_t       ctx;
	gcry_sexp_t      pub_sexpr;
	gcry_mpi_t       result_x;
	unsigned char    xbuf[256 / 8];
	size_t           rsize;

	/* first, extract the q = dP value from the public key */
	if (0 != gcry_sexp_build (&pub_sexpr, NULL,
	                          "(public-key(ecc(curve " CURVE ")(q %b)))",
	                          (int)sizeof (pub->q_y), pub->q_y))
		return 0;
	rc = gcry_mpi_ec_new (&ctx, pub_sexpr, NULL);
	brandt_assert_gpgerr (rc);
	gcry_sexp_release (pub_sexpr);
	q = gcry_mpi_ec_get_point ("q", ctx, 0);

	/* second, extract the d value from our private key */
	brandt_mpi_scan_unsigned (&d, priv->d, sizeof (priv->d));

	/* then call the 'multiply' function, to compute the product */
	result = gcry_mpi_point_new (0);
	gcry_mpi_ec_mul (result, d, q, ctx);
	gcry_mpi_point_release (q);
	gcry_mpi_release (d);

	/* finally, convert point to string for hashing */
	result_x = gcry_mpi_new (256);
	rc = gcry_mpi_ec_get_affine (result_x, NULL, result, ctx);
	brandt_assert (0 == rc);
	gcry_mpi_point_release (result);
	gcry_ctx_release (ctx);

	rsize = sizeof (xbuf);
	rc2 = gcry_mpi_get_flag (result_x, GCRYMPI_FLAG_OPAQUE);
	brandt_assert (0 == rc2);
	/* result_x can be negative here, so we do not use 'brandt_mpi_print_unsigned'
	 * as that does not include the sign bit; x should be a 255-bit
	 * value, so with the sign it should fit snugly into the 256-bit
	 * xbuf */
	rc = gcry_mpi_print (GCRYMPI_FMT_STD, xbuf, rsize, &rsize, result_x);
	brandt_assert_gpgerr (rc);
	brandt_hash (xbuf, rsize, key_material);
	gcry_mpi_release (result_x);
	return 1;
}

/**
 * Clear memory that was used to store a private key.
 *
 * @param skey location of the key
 */
void
brandt_ec_key_clear (struct brandt_ec_skey *skey)
{
	memset (skey, 0, sizeof (struct brandt_ec_skey));
}

/**
 * Generate a random value mod n.
 *
 * @param edc ECC context
 * @return random value mod n.
 */
//gcry_mpi_t
//GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc)
//{
//  gcry_mpi_t n;
//  unsigned int highbit;
//  gcry_mpi_t r;
//
//  n = gcry_mpi_ec_get_mpi ("n", edc->ctx, 1);
//
//  /* check public key for number of bits, bail out if key is all zeros */
//  highbit = 256; /* Curve25519 */
//  while ( (! gcry_mpi_test_bit (n, highbit)) &&
//          (0 != highbit) )
//    highbit--;
//  GNUNET_assert (0 != highbit);
//  /* generate fact < n (without bias) */
//  GNUNET_assert (NULL != (r = gcry_mpi_new (0)));
//  do {
//    gcry_mpi_randomize (r,
//			highbit + 1,
//			GCRY_STRONG_RANDOM);
//  }
//  while (gcry_mpi_cmp (r, n) >= 0);
//  gcry_mpi_release (n);
//  return r;
//}