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