chiark / gitweb /
crypto: Copy a SHA512 implementation into tree
[secnet.git] / transform.c
1 /* Transform module - bulk data transformation */
2
3 /* For now it's hard-coded to do sequence
4    number/pkcs5/serpent-cbcmac/serpent with a 256 bit key for each
5    instance of serpent. We also require key material for the IVs for
6    cbcmac and cbc. Hack: we're not using full 128-bit IVs, we're just
7    using 32 bits and encrypting to get the full IV to save space in
8    the packets sent over the wire. */
9
10 #include <stdio.h>
11 #include <string.h>
12 #include "secnet.h"
13 #include "util.h"
14 #include "serpent.h"
15 #include "unaligned.h"
16 #include "hexdebug.h"
17
18 /* Required key length in bytes */
19 #define REQUIRED_KEYLEN ((512+64+32)/8)
20
21 struct transform {
22     closure_t cl;
23     struct transform_if ops;
24     uint32_t max_seq_skew;
25 };
26
27 struct transform_inst {
28     struct transform_inst_if ops;
29     struct keyInstance cryptkey;
30     struct keyInstance mackey;
31     uint32_t cryptiv;
32     uint32_t maciv;
33     uint32_t sendseq;
34     uint32_t lastrecvseq;
35     uint32_t max_skew;
36     bool_t keyed;
37 };
38
39 #define PKCS5_MASK 15
40
41 static bool_t transform_setkey(void *sst, uint8_t *key, int32_t keylen)
42 {
43     struct transform_inst *ti=sst;
44
45     if (keylen<REQUIRED_KEYLEN) {
46         Message(M_ERR,"transform_create: insufficient key material supplied "
47                 "(need %d bytes, got %d)\n",REQUIRED_KEYLEN,keylen);
48         return False;
49     }
50
51 #if 0
52     {
53         printf("Setting key to: ");
54         hexdebug(stdout,key,keylen);
55         printf("\n");
56     }
57 #endif /* 0 */
58
59     serpentbe_makekey(&ti->cryptkey,256,key);
60     serpentbe_makekey(&ti->mackey,256,key+32);
61     ti->cryptiv=get_uint32(key+64);
62     ti->maciv=get_uint32(key+68);
63     ti->sendseq=get_uint32(key+72);
64     ti->lastrecvseq=ti->sendseq;
65     ti->keyed=True;
66
67     return True;
68 }
69
70 static bool_t transform_valid(void *sst)
71 {
72     struct transform_inst *ti=sst;
73
74     return ti->keyed;
75 }
76
77 static void transform_delkey(void *sst)
78 {
79     struct transform_inst *ti=sst;
80
81     FILLZERO(ti->cryptkey);
82     FILLZERO(ti->mackey);
83     ti->keyed=False;
84 }
85
86 static uint32_t transform_forward(void *sst, struct buffer_if *buf,
87                                   const char **errmsg)
88 {
89     struct transform_inst *ti=sst;
90     uint8_t *padp;
91     int padlen;
92     uint8_t iv[16];
93     uint8_t macplain[16];
94     uint8_t macacc[16];
95     uint8_t *p, *n;
96     int i;
97
98     if (!ti->keyed) {
99         *errmsg="transform unkeyed";
100         return 1;
101     }
102
103     /* Sequence number */
104     buf_prepend_uint32(buf,ti->sendseq);
105     ti->sendseq++;
106
107     /* PKCS5, stolen from IWJ */
108                                     /* eg with blocksize=4 mask=3 mask+2=5   */
109                                     /* msgsize    20    21    22    23   24  */
110     padlen= PKCS5_MASK-buf->size;   /*           -17   -18   -19   -16  -17  */
111     padlen &= PKCS5_MASK;           /*             3     2     1     0    3  */
112     padlen++;                       /*             4     3     2     1    4  */
113
114     padp=buf_append(buf,padlen);
115     memset(padp,padlen,padlen);
116
117     /* Serpent-CBCMAC. We expand the IV from 32-bit to 128-bit using
118        one encryption. Then we do the MAC and append the result. We don't
119        bother sending the IV - it's the same each time. (If we wanted to send
120        it we've have to add 16 bytes to each message, not 4, so that the
121        message stays a multiple of 16 bytes long.) */
122     memset(iv,0,16);
123     put_uint32(iv, ti->maciv);
124     serpentbe_encrypt(&ti->mackey,iv,macacc);
125
126     /* CBCMAC: encrypt in CBC mode. The MAC is the last encrypted
127        block encrypted once again. */
128     for (n=buf->start; n<buf->start+buf->size; n+=16)
129     {
130         for (i = 0; i < 16; i++)
131             macplain[i] = macacc[i] ^ n[i];
132         serpentbe_encrypt(&ti->mackey,macplain,macacc);
133     }
134     serpentbe_encrypt(&ti->mackey,macacc,macacc);
135     memcpy(buf_append(buf,16),macacc,16);
136
137     /* Serpent-CBC. We expand the ID as for CBCMAC, do the encryption,
138        and prepend the IV before increasing it. */
139     memset(iv,0,16);
140     put_uint32(iv, ti->cryptiv);
141     serpentbe_encrypt(&ti->cryptkey,iv,iv);
142
143     /* CBC: each block is XORed with the previous encrypted block (or the IV)
144        before being encrypted. */
145     p=iv;
146
147     for (n=buf->start; n<buf->start+buf->size; n+=16)
148     {
149         for (i = 0; i < 16; i++)
150             n[i] ^= p[i];
151         serpentbe_encrypt(&ti->cryptkey,n,n);
152         p=n;
153     }
154
155     buf_prepend_uint32(buf,ti->cryptiv);
156     ti->cryptiv++;
157     return 0;
158 }
159
160 static uint32_t transform_reverse(void *sst, struct buffer_if *buf,
161                                   const char **errmsg)
162 {
163     struct transform_inst *ti=sst;
164     uint8_t *padp;
165     int padlen;
166     int i;
167     uint32_t seqnum, skew;
168     uint8_t iv[16];
169     uint8_t pct[16];
170     uint8_t macplain[16];
171     uint8_t macacc[16];
172     uint8_t *n;
173     uint8_t *macexpected;
174
175     if (!ti->keyed) {
176         *errmsg="transform unkeyed";
177         return 1;
178     }
179
180     if (buf->size < 4 + 16 + 16) {
181         *errmsg="msg too short";
182         return 1;
183     }
184
185     /* CBC */
186     memset(iv,0,16);
187     {
188         uint32_t ivword = buf_unprepend_uint32(buf);
189         put_uint32(iv, ivword);
190     }
191     /* Assert bufsize is multiple of blocksize */
192     if (buf->size&0xf) {
193         *errmsg="msg not multiple of cipher blocksize";
194         return 1;
195     }
196     serpentbe_encrypt(&ti->cryptkey,iv,iv);
197     for (n=buf->start; n<buf->start+buf->size; n+=16)
198     {
199         for (i = 0; i < 16; i++)
200             pct[i] = n[i];
201         serpentbe_decrypt(&ti->cryptkey,n,n);
202         for (i = 0; i < 16; i++)
203             n[i] ^= iv[i];
204         memcpy(iv, pct, 16);
205     }
206
207     /* CBCMAC */
208     macexpected=buf_unappend(buf,16);
209     memset(iv,0,16);
210     put_uint32(iv, ti->maciv);
211     serpentbe_encrypt(&ti->mackey,iv,macacc);
212
213     /* CBCMAC: encrypt in CBC mode. The MAC is the last encrypted
214        block encrypted once again. */
215     for (n=buf->start; n<buf->start+buf->size; n+=16)
216     {
217         for (i = 0; i < 16; i++)
218             macplain[i] = macacc[i] ^ n[i];
219         serpentbe_encrypt(&ti->mackey,macplain,macacc);
220     }
221     serpentbe_encrypt(&ti->mackey,macacc,macacc);
222     if (!consttime_memeq(macexpected,macacc,16)!=0) {
223         *errmsg="invalid MAC";
224         return 1;
225     }
226
227     /* PKCS5, stolen from IWJ */
228
229     padp=buf_unappend(buf,1);
230     padlen=*padp;
231     if (!padlen || (padlen > PKCS5_MASK+1)) {
232         *errmsg="pkcs5: invalid length";
233         return 1;
234     }
235
236     buf_unappend(buf,padlen-1);
237
238     /* Sequence number must be within max_skew of lastrecvseq; lastrecvseq
239        is only allowed to increase. */
240     seqnum=buf_unprepend_uint32(buf);
241     skew=seqnum-ti->lastrecvseq;
242     if (skew<0x8fffffff) {
243         /* Ok */
244         ti->lastrecvseq=seqnum;
245     } else if ((0-skew)<ti->max_skew) {
246         /* Ok */
247     } else {
248         /* Too much skew */
249         *errmsg="seqnum: too much skew";
250         return 2;
251     }
252     
253     return 0;
254 }
255
256 static void transform_destroy(void *sst)
257 {
258     struct transform_inst *st=sst;
259
260     FILLZERO(*st); /* Destroy key material */
261     free(st);
262 }
263
264 static struct transform_inst_if *transform_create(void *sst)
265 {
266     struct transform_inst *ti;
267     struct transform *st=sst;
268
269     ti=safe_malloc(sizeof(*ti),"transform_create");
270     /* mlock XXX */
271
272     ti->ops.st=ti;
273     ti->ops.setkey=transform_setkey;
274     ti->ops.valid=transform_valid;
275     ti->ops.delkey=transform_delkey;
276     ti->ops.forwards=transform_forward;
277     ti->ops.reverse=transform_reverse;
278     ti->ops.destroy=transform_destroy;
279     ti->max_skew=st->max_seq_skew;
280     ti->keyed=False;
281
282     return &ti->ops;
283 }
284
285 static list_t *transform_apply(closure_t *self, struct cloc loc,
286                                dict_t *context, list_t *args)
287 {
288     struct transform *st;
289     item_t *item;
290     dict_t *dict;
291
292     st=safe_malloc(sizeof(*st),"serpent");
293     st->cl.description="serpent-cbc256";
294     st->cl.type=CL_TRANSFORM;
295     st->cl.apply=NULL;
296     st->cl.interface=&st->ops;
297     st->ops.st=st;
298     st->ops.max_start_pad=28; /* 4byte seqnum, 16byte pad, 4byte MACIV,
299                                  4byte IV */
300     st->ops.max_end_pad=16; /* 16byte CBCMAC */
301
302     /* We need 256*2 bits for serpent keys, 32 bits for CBC-IV and 32 bits
303        for CBCMAC-IV, and 32 bits for init sequence number */
304     st->ops.keylen=REQUIRED_KEYLEN;
305     st->ops.create=transform_create;
306
307     /* First parameter must be a dict */
308     item=list_elem(args,0);
309     if (!item || item->type!=t_dict)
310         cfgfatal(loc,"userv-ipif","parameter must be a dictionary\n");
311     
312     dict=item->data.dict;
313     st->max_seq_skew=dict_read_number(dict, "max-sequence-skew",
314                                       False, "serpent-cbc256", loc, 10);
315
316     return new_closure(&st->cl);
317 }
318
319 void transform_module(dict_t *dict)
320 {
321     struct keyInstance k;
322     uint8_t data[32];
323     uint8_t plaintext[16];
324     uint8_t ciphertext[16];
325
326     /*
327      * Serpent self-test.
328      * 
329      * This test pattern was taken directly from the Serpent test
330      * vectors, which results in a big-endian Serpent which is not
331      * compatible with other implementations.
332      */
333
334     /* Serpent self-test */
335     memcpy(data,
336            "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"
337            "\xff\xee\xdd\xcc\xbb\xaa\x99\x88\x77\x66\x55\x44\x33\x22\x11\x00",
338            32);
339     serpentbe_makekey(&k,256,data);
340
341     memcpy(plaintext,
342            "\x01\x23\x45\x67\x89\xab\xcd\xef\xfe\xdc\xba\x98\x76\x54\x32\x10",
343            16);
344     serpentbe_encrypt(&k,plaintext,ciphertext);
345
346     if (memcmp(ciphertext, "\xca\x7f\xa1\x93\xe3\xeb\x9e\x99"
347                "\xbd\x87\xe3\xaf\x3c\x9a\xdf\x93", 16)) {
348         fatal("transform_module: serpent failed self-test (encrypt)");
349     }
350     serpentbe_decrypt(&k,ciphertext,plaintext);
351     if (memcmp(plaintext, "\x01\x23\x45\x67\x89\xab\xcd\xef"
352                "\xfe\xdc\xba\x98\x76\x54\x32\x10", 16)) {
353         fatal("transform_module: serpent failed self-test (decrypt)");
354     }
355
356     add_closure(dict,"serpent256-cbc",transform_apply);
357
358 #ifdef TEST_WHOLE_TRANSFORM
359     {
360         struct transform *tr;
361         void *ti;
362         struct buffer_if buf;
363         const char text[] = "This is a piece of test text.";
364         char keymaterial[76] =
365             "Seventy-six bytes i"
366             "n four rows of 19; "
367             "this looks almost l"
368             "ike a poem but not.";
369         const char *errmsg;
370         int i;
371
372         tr = malloc(sizeof(struct transform));
373         tr->max_seq_skew = 20;
374         ti = transform_create(tr);
375
376         transform_setkey(ti, keymaterial, 76);
377
378         buf.base = malloc(4096);
379         buffer_init(&buf, 2048);
380         memcpy(buf_append(&buf, sizeof(text)), text, sizeof(text));
381         if (transform_forward(ti, &buf, &errmsg)) {
382             fatal("transform_forward test: %s", errmsg);
383         }
384         printf("transformed text is:\n");
385         for (i = 0; i < buf.size; i++)
386             printf("%02x%c", buf.start[i],
387                    (i%16==15 || i==buf.size-1 ? '\n' : ' '));
388         if (transform_reverse(ti, &buf, &errmsg)) {
389             fatal("transform_reverse test: %s", errmsg);
390         }
391         printf("transform reversal worked OK\n");
392     }
393 #endif
394 }