SKEYID derivation based on libstrongswan
[strongswan.git] / src / pluto / cookie.c
1 /* cookie generation/verification routines.
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <stdio.h>
17 #include <string.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <netinet/in.h>
21
22 #include <freeswan.h>
23
24 #include <library.h>
25 #include <crypto/rngs/rng.h>
26
27 #include "constants.h"
28 #include "defs.h"
29 #include "cookie.h"
30
31 const u_char zero_cookie[COOKIE_SIZE]; /* guaranteed 0 */
32
33 /* Generate a cookie.
34 * First argument is true if we're to create an Initiator cookie.
35 * Length SHOULD be a multiple of sizeof(u_int32_t).
36 */
37 void get_cookie(bool initiator, u_int8_t *cookie, int length, ip_address *addr)
38 {
39 hasher_t *hasher = lib->crypto->create_hasher(lib->crypto, HASH_SHA1);
40 u_char buffer[HASH_SIZE_SHA1];
41
42 do {
43 if (initiator)
44 {
45 rng_t *rng;
46
47 rng = lib->crypto->create_rng(lib->crypto, RNG_STRONG);
48 rng->get_bytes(rng, length, cookie);
49 rng->destroy(rng);
50 }
51 else /* Responder cookie */
52 {
53 chunk_t addr_chunk, secret_chunk, counter_chunk;
54 size_t addr_len;
55 static u_int32_t counter = 0;
56 unsigned char addr_buf[
57 sizeof(union {struct in_addr A; struct in6_addr B;})];
58
59 addr_len = addrbytesof(addr, addr_buf, sizeof(addr_buf));
60 addr_chunk = chunk_create(addr_buf, addr_len);
61 secret_chunk = chunk_create(secret_of_the_day, HASH_SIZE_SHA1);
62 counter++;
63 counter_chunk = chunk_create((void *) &counter, sizeof(counter));
64 hasher->get_hash(hasher, addr_chunk, NULL);
65 hasher->get_hash(hasher, secret_chunk, NULL);
66 hasher->get_hash(hasher, counter_chunk, buffer);
67 memcpy(cookie, buffer, length);
68 }
69 } while (is_zero_cookie(cookie)); /* probably never loops */
70
71 hasher->destroy(hasher);
72 }