7caa19ba9d9e80e05256fbaec62e8f705fda6bdb
[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 "sha1.h"
30 #include "cookie.h"
31
32 const u_char zero_cookie[COOKIE_SIZE]; /* guaranteed 0 */
33
34 /* Generate a cookie.
35 * First argument is true if we're to create an Initiator cookie.
36 * Length SHOULD be a multiple of sizeof(u_int32_t).
37 */
38 void get_cookie(bool initiator, u_int8_t *cookie, int length,
39 const ip_address *addr)
40 {
41 u_char buffer[SHA1_DIGEST_SIZE];
42 SHA1_CTX ctx;
43
44 do {
45 if (initiator)
46 {
47 rng_t *rng;
48
49 rng = lib->crypto->create_rng(lib->crypto, RNG_STRONG);
50 rng->get_bytes(rng, length, cookie);
51 rng->destroy(rng);
52 }
53 else /* Responder cookie */
54 {
55 /* This looks as good as any way */
56 size_t addr_length;
57 static u_int32_t counter = 0;
58 unsigned char addr_buff[
59 sizeof(union {struct in_addr A; struct in6_addr B;})];
60
61 addr_length = addrbytesof(addr, addr_buff, sizeof(addr_buff));
62 SHA1Init(&ctx);
63 SHA1Update(&ctx, addr_buff, addr_length);
64 SHA1Update(&ctx, secret_of_the_day, sizeof(secret_of_the_day));
65 counter++;
66 SHA1Update(&ctx, (const void *) &counter, sizeof(counter));
67 SHA1Final(buffer, &ctx);
68 memcpy(cookie, buffer, length);
69 }
70 } while (is_zero_cookie(cookie)); /* probably never loops */
71 }