File: transform-cbcmac.c

package info (click to toggle)
secnet 0.6.8
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 1,956 kB
  • sloc: ansic: 15,234; python: 1,057; perl: 966; sh: 596; tcl: 484; java: 231; asm: 114; yacc: 89; php: 64; makefile: 48; awk: 40
file content (381 lines) | stat: -rw-r--r-- 10,396 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/* Transform module - bulk data transformation */

/*
 * This file is part of secnet.
 * See README for full list of copyright holders.
 *
 * secnet is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * secnet is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * version 3 along with secnet; if not, see
 * https://www.gnu.org/licenses/gpl.html.
 */

/* For now it's hard-coded to do sequence
   number/pkcs5/serpent-cbcmac/serpent with a 256 bit key for each
   instance of serpent. We also require key material for the IVs for
   cbcmac and cbc. Hack: we're not using full 128-bit IVs, we're just
   using 32 bits and encrypting to get the full IV to save space in
   the packets sent over the wire. */

#include <stdio.h>
#include <string.h>
#include "secnet.h"
#include "util.h"
#include "serpent.h"
#include "unaligned.h"
#include "hexdebug.h"

/* Required key length in bytes */
#define REQUIRED_KEYLEN ((512+64+32)/8)

#include "transform-common.h"

struct transform_params {
    SEQNUM_PARAMS_FIELDS;
};

struct transform {
    closure_t cl;
    struct transform_if ops;
    struct transform_params p;
};

struct transform_inst {
    struct transform_inst_if ops;
    struct transform_params p;
    struct keyInstance cryptkey;
    struct keyInstance mackey;
    uint32_t cryptiv;
    uint32_t maciv;
    SEQNUM_KEYED_FIELDS;
};

#define PKCS5_MASK 15

static bool_t transform_setkey(void *sst, uint8_t *key, int32_t keylen,
			       bool_t direction)
{
    struct transform_inst *ti=sst;

    if (keylen<REQUIRED_KEYLEN) {
	Message(M_ERR,"transform_create: insufficient key material supplied "
		"(need %d bytes, got %d)\n",REQUIRED_KEYLEN,keylen);
	return False;
    }

#if 0
    {
	printf("Setting key to: ");
	hexdebug(stdout,key,keylen);
	printf("\n");
    }
#endif /* 0 */

    serpentbe_makekey(&ti->cryptkey,256,key);
    serpentbe_makekey(&ti->mackey,256,key+32);
    ti->cryptiv=get_uint32(key+64);
    ti->maciv=get_uint32(key+68);
    uint32_t firstseq=get_uint32(key+72);
    SEQNUM_KEYED_INIT(firstseq,firstseq);

    return True;
}

TRANSFORM_VALID;

static void transform_delkey(void *sst)
{
    struct transform_inst *ti=sst;

    FILLZERO(ti->cryptkey);
    FILLZERO(ti->mackey);
    ti->keyed=False;
}

static transform_apply_return transform_forward(void *sst,
            struct buffer_if *buf, const char **errmsg)
{
    struct transform_inst *ti=sst;
    uint8_t *padp;
    int padlen;
    uint8_t iv[16];
    uint8_t macplain[16];
    uint8_t macacc[16];
    uint8_t *p, *n;
    int i;

    KEYED_CHECK;

    /* Sequence number */
    buf_prepend_uint32(buf,ti->sendseq);
    ti->sendseq++;

    /* PKCS5, stolen from IWJ */
                                    /* eg with blocksize=4 mask=3 mask+2=5   */
                                    /* msgsize    20    21    22    23   24  */
    padlen= PKCS5_MASK-buf->size;   /*           -17   -18   -19   -16  -17  */
    padlen &= PKCS5_MASK;           /*             3     2     1     0    3  */
    padlen++;                       /*             4     3     2     1    4  */

    padp=buf_append(buf,padlen);
    memset(padp,padlen,padlen);

    /* Serpent-CBCMAC. We expand the IV from 32-bit to 128-bit using
       one encryption. Then we do the MAC and append the result. We don't
       bother sending the IV - it's the same each time. (If we wanted to send
       it we've have to add 16 bytes to each message, not 4, so that the
       message stays a multiple of 16 bytes long.) */
    FILLZERO(iv);
    put_uint32(iv, ti->maciv);
    serpentbe_encrypt(&ti->mackey,iv,macacc);

    /* CBCMAC: encrypt in CBC mode. The MAC is the last encrypted
       block encrypted once again. */
    for (n=buf->start; n<buf->start+buf->size; n+=16)
    {
	for (i = 0; i < 16; i++)
	    macplain[i] = macacc[i] ^ n[i];
	serpentbe_encrypt(&ti->mackey,macplain,macacc);
    }
    serpentbe_encrypt(&ti->mackey,macacc,macacc);
    BUF_ADD_BYTES(append,buf,macacc,16);

    /* Serpent-CBC. We expand the ID as for CBCMAC, do the encryption,
       and prepend the IV before increasing it. */
    FILLZERO(iv);
    put_uint32(iv, ti->cryptiv);
    serpentbe_encrypt(&ti->cryptkey,iv,iv);

    /* CBC: each block is XORed with the previous encrypted block (or the IV)
       before being encrypted. */
    p=iv;

    for (n=buf->start; n<buf->start+buf->size; n+=16)
    {
	for (i = 0; i < 16; i++)
	    n[i] ^= p[i];
	serpentbe_encrypt(&ti->cryptkey,n,n);
	p=n;
    }

    buf_prepend_uint32(buf,ti->cryptiv);
    ti->cryptiv++;
    return 0;
}

static transform_apply_return transform_reverse(void *sst,
                struct buffer_if *buf, const char **errmsg)
{
    struct transform_inst *ti=sst;
    uint8_t *padp;
    int padlen;
    int i;
    uint32_t seqnum;
    uint8_t iv[16];
    uint8_t pct[16];
    uint8_t macplain[16];
    uint8_t macacc[16];
    uint8_t *n;
    uint8_t *macexpected;

    KEYED_CHECK;

    if (buf->size < 4 + 16 + 16) {
	*errmsg="msg too short";
	return transform_apply_err;
    }

    /* CBC */
    FILLZERO(iv);
    {
	uint32_t ivword = buf_unprepend_uint32(buf);
	put_uint32(iv, ivword);
    }
    /* Assert bufsize is multiple of blocksize */
    if (buf->size&0xf) {
	*errmsg="msg not multiple of cipher blocksize";
	return transform_apply_err;
    }
    serpentbe_encrypt(&ti->cryptkey,iv,iv);
    for (n=buf->start; n<buf->start+buf->size; n+=16)
    {
	for (i = 0; i < 16; i++)
	    pct[i] = n[i];
	serpentbe_decrypt(&ti->cryptkey,n,n);
	for (i = 0; i < 16; i++)
	    n[i] ^= iv[i];
	COPY_OBJ(iv, pct);
    }

    /* CBCMAC */
    macexpected=buf_unappend(buf,16);
    FILLZERO(iv);
    put_uint32(iv, ti->maciv);
    serpentbe_encrypt(&ti->mackey,iv,macacc);

    /* CBCMAC: encrypt in CBC mode. The MAC is the last encrypted
       block encrypted once again. */
    for (n=buf->start; n<buf->start+buf->size; n+=16)
    {
	for (i = 0; i < 16; i++)
	    macplain[i] = macacc[i] ^ n[i];
	serpentbe_encrypt(&ti->mackey,macplain,macacc);
    }
    serpentbe_encrypt(&ti->mackey,macacc,macacc);
    if (!consttime_memeq(macexpected,macacc,16)) {
	*errmsg="invalid MAC";
	return transform_apply_err;
    }

    /* PKCS5, stolen from IWJ */

    padp=buf_unappend(buf,1);
    padlen=*padp;
    if (!padlen || (padlen > PKCS5_MASK+1)) {
	*errmsg="pkcs5: invalid length";
	return transform_apply_err;
    }

    buf_unappend(buf,padlen-1);

    /* Sequence number must be within max_skew of lastrecvseq; lastrecvseq
       is only allowed to increase. */
    seqnum=buf_unprepend_uint32(buf);
    SEQNUM_CHECK(seqnum, &ti->p);
    
    return 0;
}

TRANSFORM_DESTROY;

static struct transform_inst_if *transform_create(void *sst)
{
    struct transform *st=sst;

    TRANSFORM_CREATE_CORE;

    ti->p=st->p;

    return &ti->ops;
}

static list_t *transform_apply(closure_t *self, struct cloc loc,
			       dict_t *context, list_t *args)
{
    struct transform *st;
    item_t *item;
    dict_t *dict;

    NEW(st);
    st->cl.description="serpent-cbc256";
    st->cl.type=CL_TRANSFORM;
    st->cl.apply=NULL;
    st->cl.interface=&st->ops;
    st->ops.st=st;
    update_max_start_pad(&transform_max_start_pad, 28);
        /* 4byte seqnum, 16byte pad, 4byte MACIV, 4byte IV */

    /* We need 256*2 bits for serpent keys, 32 bits for CBC-IV and 32 bits
       for CBCMAC-IV, and 32 bits for init sequence number */
    st->ops.keylen=REQUIRED_KEYLEN;
    st->ops.create=transform_create;

    /* First parameter must be a dict */
    item=list_elem(args,0);
    if (!item || item->type!=t_dict)
	cfgfatal(loc,"serpent256-cbc","parameter must be a dictionary\n");
    
    dict=item->data.dict;

    SEQNUM_PARAMS_INIT(dict,&st->p,"serpent-cbc256",loc);

    SET_CAPAB_BIT(CAPAB_BIT_SERPENT256CBC);

    return new_closure(&st->cl);
}

void transform_cbcmac_module(dict_t *dict)
{
    struct keyInstance k;
    uint8_t data[32];
    uint8_t plaintext[16];
    uint8_t ciphertext[16];

    /*
     * Serpent self-test.
     * 
     * This test pattern was taken directly from the Serpent test
     * vectors, which results in a big-endian Serpent which is not
     * compatible with other implementations.
     */

    /* Serpent self-test */
    memcpy(data,
           "\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff"
           "\xff\xee\xdd\xcc\xbb\xaa\x99\x88\x77\x66\x55\x44\x33\x22\x11\x00",
           32);
    serpentbe_makekey(&k,256,data);

    memcpy(plaintext,
           "\x01\x23\x45\x67\x89\xab\xcd\xef\xfe\xdc\xba\x98\x76\x54\x32\x10",
           16);
    serpentbe_encrypt(&k,plaintext,ciphertext);

    if (memcmp(ciphertext, "\xca\x7f\xa1\x93\xe3\xeb\x9e\x99"
               "\xbd\x87\xe3\xaf\x3c\x9a\xdf\x93", 16)) {
	fatal("transform_module: serpent failed self-test (encrypt)");
    }
    serpentbe_decrypt(&k,ciphertext,plaintext);
    if (memcmp(plaintext, "\x01\x23\x45\x67\x89\xab\xcd\xef"
               "\xfe\xdc\xba\x98\x76\x54\x32\x10", 16)) {
	fatal("transform_module: serpent failed self-test (decrypt)");
    }

    add_closure(dict,"serpent256-cbc",transform_apply);

#ifdef TEST_WHOLE_TRANSFORM
    {
	struct transform *tr;
	void *ti;
	struct buffer_if buf;
	const char text[] = "This is a piece of test text.";
	char keymaterial[76] =
	    "Seventy-six bytes i"
	    "n four rows of 19; "
	    "this looks almost l"
	    "ike a poem but not.";
	const char *errmsg;
	int i;

	NEW(tr);
	tr->max_seq_skew = 20;
	ti = transform_create(tr);

	transform_setkey(ti, keymaterial, 76);

        buf.base = malloc(4096);
	buffer_init(&buf, 2048);
	BUF_ADD_OBJ(append, buf, text, sizeof(text));
	if (transform_forward(ti, &buf, &errmsg)) {
	    fatal("transform_forward test: %s", errmsg);
	}
	printf("transformed text is:\n");
	for (i = 0; i < buf.size; i++)
	    printf("%02x%c", buf.start[i],
		   (i%16==15 || i==buf.size-1 ? '\n' : ' '));
	if (transform_reverse(ti, &buf, &errmsg)) {
	    fatal("transform_reverse test: %s", errmsg);
	}
	printf("transform reversal worked OK\n");
    }
#endif
}