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