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