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