Browse Source

[crypto] Upgrade AES and RSA code to upstream axTLS version 1.4.5

All axTLS files are now vanilla versions of the upstream axTLS files,
with one minor exception: the unused "ctx" parameter of
bi_int_divide() has been marked with "__unused" to avoid a compilation
error.

Signed-off-by: Michael Brown <mcb30@ipxe.org>
tags/v1.20.1
Michael Brown 12 years ago
parent
commit
1c29b4d979

+ 88
- 109
src/crypto/axtls/aes.c View File

1
 /*
1
 /*
2
- *  Copyright(C) 2006 Cameron Rich
2
+ * Copyright (c) 2007, Cameron Rich
3
  *
3
  *
4
- *  This library is free software; you can redistribute it and/or modify
5
- *  it under the terms of the GNU Lesser General Public License as published by
6
- *  the Free Software Foundation; either version 2 of the License, or
7
- *  (at your option) any later version.
4
+ * All rights reserved.
8
  *
5
  *
9
- *  This library is distributed in the hope that it will be useful,
10
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
- *  GNU Lesser General Public License for more details.
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
13
  *
8
  *
14
- *  You should have received a copy of the GNU Lesser General Public License
15
- *  along with this library; if not, write to the Free Software
16
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
9
+ * * Redistributions of source code must retain the above copyright notice,
10
+ *   this list of conditions and the following disclaimer.
11
+ * * Redistributions in binary form must reproduce the above copyright notice,
12
+ *   this list of conditions and the following disclaimer in the documentation
13
+ *   and/or other materials provided with the distribution.
14
+ * * Neither the name of the axTLS project nor the names of its contributors
15
+ *   may be used to endorse or promote products derived from this software
16
+ *   without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
  */
29
  */
18
 
30
 
19
-FILE_LICENCE ( GPL2_OR_LATER );
20
-
21
 /**
31
 /**
22
  * AES implementation - this is a small code version. There are much faster
32
  * AES implementation - this is a small code version. There are much faster
23
  * versions around but they are much larger in size (i.e. they use large 
33
  * versions around but they are much larger in size (i.e. they use large 
25
  */
35
  */
26
 
36
 
27
 #include <string.h>
37
 #include <string.h>
38
+#include "os_port.h"
28
 #include "crypto.h"
39
 #include "crypto.h"
29
 
40
 
30
 /* all commented out in skeleton mode */
41
 /* all commented out in skeleton mode */
64
 			(f8)^=rot2(f4), \
75
 			(f8)^=rot2(f4), \
65
 			(f8)^rot1(f9))
76
 			(f8)^rot1(f9))
66
 
77
 
67
-/* some macros to do endian independent byte extraction */
68
-#define n2l(c,l) l=ntohl(*c); c++
69
-#define l2n(l,c) *c++=htonl(l)
70
-
71
 /*
78
 /*
72
  * AES S-box
79
  * AES S-box
73
  */
80
  */
154
 	0xb3,0x7d,0xfa,0xef,0xc5,0x91,
161
 	0xb3,0x7d,0xfa,0xef,0xc5,0x91,
155
 };
162
 };
156
 
163
 
164
+/* ----- static functions ----- */
165
+static void AES_encrypt(const AES_CTX *ctx, uint32_t *data);
166
+static void AES_decrypt(const AES_CTX *ctx, uint32_t *data);
167
+
157
 /* Perform doubling in Galois Field GF(2^8) using the irreducible polynomial
168
 /* Perform doubling in Galois Field GF(2^8) using the irreducible polynomial
158
    x^8+x^4+x^3+x+1 */
169
    x^8+x^4+x^3+x+1 */
159
 static unsigned char AES_xtime(uint32_t x)
170
 static unsigned char AES_xtime(uint32_t x)
160
 {
171
 {
161
-	return x = (x&0x80) ? (x<<1)^0x1b : x<<1;
172
+	return (x&0x80) ? (x<<1)^0x1b : x<<1;
162
 }
173
 }
163
 
174
 
164
 /**
175
 /**
247
     k = ctx->ks;
258
     k = ctx->ks;
248
     k += 4;
259
     k += 4;
249
 
260
 
250
-    for (i=ctx->rounds*4; i>4; i--)
261
+    for (i= ctx->rounds*4; i > 4; i--)
251
     {
262
     {
252
         w= *k;
263
         w= *k;
253
         w = inv_mix_col(w,t1,t2,t3,t4);
264
         w = inv_mix_col(w,t1,t2,t3,t4);
255
     }
266
     }
256
 }
267
 }
257
 
268
 
258
-#if 0
259
 /**
269
 /**
260
  * Encrypt a byte sequence (with a block size 16) using the AES cipher.
270
  * Encrypt a byte sequence (with a block size 16) using the AES cipher.
261
  */
271
  */
262
 void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
272
 void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
263
 {
273
 {
264
-    uint32_t tin0, tin1, tin2, tin3;
265
-    uint32_t tout0, tout1, tout2, tout3;
266
-    uint32_t tin[4];
267
-    uint32_t *iv = (uint32_t *)ctx->iv;
268
-    uint32_t *msg_32 = (uint32_t *)msg;
269
-    uint32_t *out_32 = (uint32_t *)out;
270
-
271
-    n2l(iv, tout0);
272
-    n2l(iv, tout1);
273
-    n2l(iv, tout2);
274
-    n2l(iv, tout3);
275
-    iv -= 4;
274
+    int i;
275
+    uint32_t tin[4], tout[4], iv[4];
276
 
276
 
277
-    for (length -= 16; length >= 0; length -= 16)
277
+    memcpy(iv, ctx->iv, AES_IV_SIZE);
278
+    for (i = 0; i < 4; i++)
279
+        tout[i] = ntohl(iv[i]);
280
+
281
+    for (length -= AES_BLOCKSIZE; length >= 0; length -= AES_BLOCKSIZE)
278
     {
282
     {
279
-        n2l(msg_32, tin0);
280
-        n2l(msg_32, tin1);
281
-        n2l(msg_32, tin2);
282
-        n2l(msg_32, tin3);
283
-        tin[0] = tin0^tout0;
284
-        tin[1] = tin1^tout1;
285
-        tin[2] = tin2^tout2;
286
-        tin[3] = tin3^tout3;
283
+        uint32_t msg_32[4];
284
+        uint32_t out_32[4];
285
+        memcpy(msg_32, msg, AES_BLOCKSIZE);
286
+        msg += AES_BLOCKSIZE;
287
+
288
+        for (i = 0; i < 4; i++)
289
+            tin[i] = ntohl(msg_32[i])^tout[i];
287
 
290
 
288
         AES_encrypt(ctx, tin);
291
         AES_encrypt(ctx, tin);
289
 
292
 
290
-        tout0 = tin[0]; 
291
-        l2n(tout0, out_32);
292
-        tout1 = tin[1]; 
293
-        l2n(tout1, out_32);
294
-        tout2 = tin[2]; 
295
-        l2n(tout2, out_32);
296
-        tout3 = tin[3]; 
297
-        l2n(tout3, out_32);
293
+        for (i = 0; i < 4; i++)
294
+        {
295
+            tout[i] = tin[i];
296
+            out_32[i] = htonl(tout[i]);
297
+        }
298
+
299
+        memcpy(out, out_32, AES_BLOCKSIZE);
300
+        out += AES_BLOCKSIZE;
298
     }
301
     }
299
 
302
 
300
-    l2n(tout0, iv);
301
-    l2n(tout1, iv);
302
-    l2n(tout2, iv);
303
-    l2n(tout3, iv);
303
+    for (i = 0; i < 4; i++)
304
+        iv[i] = htonl(tout[i]);
305
+    memcpy(ctx->iv, iv, AES_IV_SIZE);
304
 }
306
 }
305
 
307
 
306
 /**
308
 /**
308
  */
310
  */
309
 void AES_cbc_decrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
311
 void AES_cbc_decrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
310
 {
312
 {
311
-    uint32_t tin0, tin1, tin2, tin3;
312
-    uint32_t xor0,xor1,xor2,xor3;
313
-    uint32_t tout0,tout1,tout2,tout3;
314
-    uint32_t data[4];
315
-    uint32_t *iv = (uint32_t *)ctx->iv;
316
-    uint32_t *msg_32 = (uint32_t *)msg;
317
-    uint32_t *out_32 = (uint32_t *)out;
318
-
319
-    n2l(iv ,xor0);
320
-    n2l(iv, xor1);
321
-    n2l(iv, xor2);
322
-    n2l(iv, xor3);
323
-    iv -= 4;
324
-
325
-    for (length-=16; length >= 0; length -= 16)
313
+    int i;
314
+    uint32_t tin[4], xor[4], tout[4], data[4], iv[4];
315
+
316
+    memcpy(iv, ctx->iv, AES_IV_SIZE);
317
+    for (i = 0; i < 4; i++)
318
+        xor[i] = ntohl(iv[i]);
319
+
320
+    for (length -= 16; length >= 0; length -= 16)
326
     {
321
     {
327
-        n2l(msg_32, tin0);
328
-        n2l(msg_32, tin1);
329
-        n2l(msg_32, tin2);
330
-        n2l(msg_32, tin3);
322
+        uint32_t msg_32[4];
323
+        uint32_t out_32[4];
324
+        memcpy(msg_32, msg, AES_BLOCKSIZE);
325
+        msg += AES_BLOCKSIZE;
331
 
326
 
332
-        data[0] = tin0;
333
-        data[1] = tin1;
334
-        data[2] = tin2;
335
-        data[3] = tin3;
327
+        for (i = 0; i < 4; i++)
328
+        {
329
+            tin[i] = ntohl(msg_32[i]);
330
+            data[i] = tin[i];
331
+        }
336
 
332
 
337
         AES_decrypt(ctx, data);
333
         AES_decrypt(ctx, data);
338
 
334
 
339
-        tout0 = data[0]^xor0;
340
-        tout1 = data[1]^xor1;
341
-        tout2 = data[2]^xor2;
342
-        tout3 = data[3]^xor3;
343
-
344
-        xor0 = tin0;
345
-        xor1 = tin1;
346
-        xor2 = tin2;
347
-        xor3 = tin3;
335
+        for (i = 0; i < 4; i++)
336
+        {
337
+            tout[i] = data[i]^xor[i];
338
+            xor[i] = tin[i];
339
+            out_32[i] = htonl(tout[i]);
340
+        }
348
 
341
 
349
-        l2n(tout0, out_32);
350
-        l2n(tout1, out_32);
351
-        l2n(tout2, out_32);
352
-        l2n(tout3, out_32);
342
+        memcpy(out, out_32, AES_BLOCKSIZE);
343
+        out += AES_BLOCKSIZE;
353
     }
344
     }
354
 
345
 
355
-    l2n(xor0, iv);
356
-    l2n(xor1, iv);
357
-    l2n(xor2, iv);
358
-    l2n(xor3, iv);
346
+    for (i = 0; i < 4; i++)
347
+        iv[i] = htonl(xor[i]);
348
+    memcpy(ctx->iv, iv, AES_IV_SIZE);
359
 }
349
 }
360
-#endif
361
 
350
 
362
 /**
351
 /**
363
  * Encrypt a single block (16 bytes) of data
352
  * Encrypt a single block (16 bytes) of data
364
  */
353
  */
365
-void AES_encrypt(const AES_CTX *ctx, uint32_t *data)
354
+static void AES_encrypt(const AES_CTX *ctx, uint32_t *data)
366
 {
355
 {
367
     /* To make this code smaller, generate the sbox entries on the fly.
356
     /* To make this code smaller, generate the sbox entries on the fly.
368
      * This will have a really heavy effect upon performance.
357
      * This will have a really heavy effect upon performance.
375
 
364
 
376
     /* Pre-round key addition */
365
     /* Pre-round key addition */
377
     for (row = 0; row < 4; row++)
366
     for (row = 0; row < 4; row++)
378
-    {
379
         data[row] ^= *(k++);
367
         data[row] ^= *(k++);
380
-    }
381
 
368
 
382
     /* Encrypt one block. */
369
     /* Encrypt one block. */
383
     for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++)
370
     for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++)
395
             {
382
             {
396
                 tmp1 = a0 ^ a1 ^ a2 ^ a3;
383
                 tmp1 = a0 ^ a1 ^ a2 ^ a3;
397
                 old_a0 = a0;
384
                 old_a0 = a0;
398
-
399
                 a0 ^= tmp1 ^ AES_xtime(a0 ^ a1);
385
                 a0 ^= tmp1 ^ AES_xtime(a0 ^ a1);
400
                 a1 ^= tmp1 ^ AES_xtime(a1 ^ a2);
386
                 a1 ^= tmp1 ^ AES_xtime(a1 ^ a2);
401
                 a2 ^= tmp1 ^ AES_xtime(a2 ^ a3);
387
                 a2 ^= tmp1 ^ AES_xtime(a2 ^ a3);
402
                 a3 ^= tmp1 ^ AES_xtime(a3 ^ old_a0);
388
                 a3 ^= tmp1 ^ AES_xtime(a3 ^ old_a0);
403
-
404
             }
389
             }
405
 
390
 
406
             tmp[row] = ((a0 << 24) | (a1 << 16) | (a2 << 8) | a3);
391
             tmp[row] = ((a0 << 24) | (a1 << 16) | (a2 << 8) | a3);
409
         /* KeyAddition - note that it is vital that this loop is separate from
394
         /* KeyAddition - note that it is vital that this loop is separate from
410
            the MixColumn operation, which must be atomic...*/ 
395
            the MixColumn operation, which must be atomic...*/ 
411
         for (row = 0; row < 4; row++)
396
         for (row = 0; row < 4; row++)
412
-        {
413
             data[row] = tmp[row] ^ *(k++);
397
             data[row] = tmp[row] ^ *(k++);
414
-        }
415
     }
398
     }
416
 }
399
 }
417
 
400
 
418
 /**
401
 /**
419
  * Decrypt a single block (16 bytes) of data
402
  * Decrypt a single block (16 bytes) of data
420
  */
403
  */
421
-void AES_decrypt(const AES_CTX *ctx, uint32_t *data)
404
+static void AES_decrypt(const AES_CTX *ctx, uint32_t *data)
422
 { 
405
 { 
423
     uint32_t tmp[4];
406
     uint32_t tmp[4];
424
     uint32_t xt0,xt1,xt2,xt3,xt4,xt5,xt6;
407
     uint32_t xt0,xt1,xt2,xt3,xt4,xt5,xt6;
425
     uint32_t a0, a1, a2, a3, row;
408
     uint32_t a0, a1, a2, a3, row;
426
     int curr_rnd;
409
     int curr_rnd;
427
     int rounds = ctx->rounds;
410
     int rounds = ctx->rounds;
428
-    uint32_t *k = (uint32_t*)ctx->ks + ((rounds+1)*4);
411
+    const uint32_t *k = ctx->ks + ((rounds+1)*4);
429
 
412
 
430
     /* pre-round key addition */
413
     /* pre-round key addition */
431
     for (row=4; row > 0;row--)
414
     for (row=4; row > 0;row--)
432
-    {
433
         data[row-1] ^= *(--k);
415
         data[row-1] ^= *(--k);
434
-    }
435
 
416
 
436
     /* Decrypt one block */
417
     /* Decrypt one block */
437
-    for (curr_rnd=0; curr_rnd < rounds; curr_rnd++)
418
+    for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++)
438
     {
419
     {
439
         /* Perform ByteSub and ShiftRow operations together */
420
         /* Perform ByteSub and ShiftRow operations together */
440
         for (row = 4; row > 0; row--)
421
         for (row = 4; row > 0; row--)
469
         }
450
         }
470
 
451
 
471
         for (row = 4; row > 0; row--)
452
         for (row = 4; row > 0; row--)
472
-        {
473
             data[row-1] = tmp[row-1] ^ *(--k);
453
             data[row-1] = tmp[row-1] ^ *(--k);
474
-        }
475
     }
454
     }
476
 }
455
 }
477
 
456
 

+ 160
- 143
src/crypto/axtls/bigint.c View File

1
 /*
1
 /*
2
- *  Copyright(C) 2006 Cameron Rich
2
+ * Copyright (c) 2007, Cameron Rich
3
  *
3
  *
4
- *  This library is free software; you can redistribute it and/or modify
5
- *  it under the terms of the GNU Lesser General Public License as published by
6
- *  the Free Software Foundation; either version 2.1 of the License, or
7
- *  (at your option) any later version.
4
+ * All rights reserved.
8
  *
5
  *
9
- *  This library is distributed in the hope that it will be useful,
10
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
- *  GNU Lesser General Public License for more details.
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
13
  *
8
  *
14
- *  You should have received a copy of the GNU Lesser General Public License
15
- *  along with this library; if not, write to the Free Software
16
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
9
+ * * Redistributions of source code must retain the above copyright notice,
10
+ *   this list of conditions and the following disclaimer.
11
+ * * Redistributions in binary form must reproduce the above copyright notice,
12
+ *   this list of conditions and the following disclaimer in the documentation
13
+ *   and/or other materials provided with the distribution.
14
+ * * Neither the name of the axTLS project nor the names of its contributors
15
+ *   may be used to endorse or promote products derived from this software
16
+ *   without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
  */
29
  */
18
 
30
 
19
 /**
31
 /**
53
 #include <string.h>
65
 #include <string.h>
54
 #include <stdio.h>
66
 #include <stdio.h>
55
 #include <time.h>
67
 #include <time.h>
68
+#include "os_port.h"
56
 #include "bigint.h"
69
 #include "bigint.h"
57
-#include "crypto.h"
70
+
71
+#define V1      v->comps[v->size-1]                 /**< v1 for division */
72
+#define V2      v->comps[v->size-2]                 /**< v2 for division */
73
+#define U(j)    tmp_u->comps[tmp_u->size-j-1]       /**< uj for division */
74
+#define Q(j)    quotient->comps[quotient->size-j-1] /**< qj for division */
58
 
75
 
59
 static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i);
76
 static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i);
60
 static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom);
77
 static bigint *bi_int_divide(BI_CTX *ctx, bigint *biR, comp denom);
61
-static bigint __malloc *alloc(BI_CTX *ctx, int size);
78
+static bigint *alloc(BI_CTX *ctx, int size);
62
 static bigint *trim(bigint *bi);
79
 static bigint *trim(bigint *bi);
63
 static void more_comps(bigint *bi, int n);
80
 static void more_comps(bigint *bi, int n);
64
 #if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
81
 #if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
69
 
86
 
70
 #ifdef CONFIG_BIGINT_CHECK_ON
87
 #ifdef CONFIG_BIGINT_CHECK_ON
71
 static void check(const bigint *bi);
88
 static void check(const bigint *bi);
89
+#else
90
+#define check(A)                /**< disappears in normal production mode */
72
 #endif
91
 #endif
73
 
92
 
93
+
74
 /**
94
 /**
75
  * @brief Start a new bigint context.
95
  * @brief Start a new bigint context.
76
  * @return A bigint context.
96
  * @return A bigint context.
97
  */
117
  */
98
 void bi_terminate(BI_CTX *ctx)
118
 void bi_terminate(BI_CTX *ctx)
99
 {
119
 {
100
-    bigint *p, *pn;
101
-
102
     bi_depermanent(ctx->bi_radix); 
120
     bi_depermanent(ctx->bi_radix); 
103
     bi_free(ctx, ctx->bi_radix);
121
     bi_free(ctx, ctx->bi_radix);
104
 
122
 
111
         abort();
129
         abort();
112
     }
130
     }
113
 
131
 
132
+    bi_clear_cache(ctx);
133
+    free(ctx);
134
+}
135
+
136
+/**
137
+ *@brief Clear the memory cache.
138
+ */
139
+void bi_clear_cache(BI_CTX *ctx)
140
+{
141
+    bigint *p, *pn;
142
+
143
+    if (ctx->free_list == NULL)
144
+        return;
145
+
114
     for (p = ctx->free_list; p != NULL; p = pn)
146
     for (p = ctx->free_list; p != NULL; p = pn)
115
     {
147
     {
116
         pn = p->next;
148
         pn = p->next;
118
         free(p);
150
         free(p);
119
     }
151
     }
120
 
152
 
121
-    free(ctx);
153
+    ctx->free_count = 0;
154
+    ctx->free_list = NULL;
122
 }
155
 }
123
 
156
 
124
 /**
157
 /**
410
         else
443
         else
411
         {
444
         {
412
             q_dash = (comp)(((long_comp)U(0)*COMP_RADIX + U(1))/V1);
445
             q_dash = (comp)(((long_comp)U(0)*COMP_RADIX + U(1))/V1);
413
-        }
414
 
446
 
415
-        if (v->size > 1 && V2)
416
-        {
417
-            /* we are implementing the following:
418
-            if (V2*q_dash > (((U(0)*COMP_RADIX + U(1) - 
419
-                    q_dash*V1)*COMP_RADIX) + U(2))) ... */
420
-            comp inner = (comp)((long_comp)COMP_RADIX*U(0) + U(1) - 
421
-                                        (long_comp)q_dash*V1);
422
-            if ((long_comp)V2*q_dash > (long_comp)inner*COMP_RADIX + U(2))
447
+            if (v->size > 1 && V2)
423
             {
448
             {
424
-                q_dash--;
449
+                /* we are implementing the following:
450
+                if (V2*q_dash > (((U(0)*COMP_RADIX + U(1) -
451
+                        q_dash*V1)*COMP_RADIX) + U(2))) ... */
452
+                comp inner = (comp)((long_comp)COMP_RADIX*U(0) + U(1) -
453
+                                            (long_comp)q_dash*V1);
454
+                if ((long_comp)V2*q_dash > (long_comp)inner*COMP_RADIX + U(2))
455
+                {
456
+                    q_dash--;
457
+                }
425
             }
458
             }
426
         }
459
         }
427
 
460
 
473
 /*
506
 /*
474
  * Perform an integer divide on a bigint.
507
  * Perform an integer divide on a bigint.
475
  */
508
  */
509
+// mcb30 - mark ctx with __unused to avoid a compilation error
476
 static bigint *bi_int_divide(BI_CTX *ctx __unused, bigint *biR, comp denom)
510
 static bigint *bi_int_divide(BI_CTX *ctx __unused, bigint *biR, comp denom)
477
 {
511
 {
478
     int i = biR->size - 1;
512
     int i = biR->size - 1;
485
         r = (r<<COMP_BIT_SIZE) + biR->comps[i];
519
         r = (r<<COMP_BIT_SIZE) + biR->comps[i];
486
         biR->comps[i] = (comp)(r / denom);
520
         biR->comps[i] = (comp)(r / denom);
487
         r %= denom;
521
         r %= denom;
488
-    } while (--i != 0);
522
+    } while (--i >= 0);
489
 
523
 
490
     return trim(biR);
524
     return trim(biR);
491
 }
525
 }
690
 
724
 
691
             if (k < 0)
725
             if (k < 0)
692
             {
726
             {
693
-                break;
727
+                goto buf_done;
694
             }
728
             }
695
         }
729
         }
696
     }
730
     }
731
+buf_done:
697
 
732
 
698
     bi_free(ctx, x);
733
     bi_free(ctx, x);
699
 }
734
 }
769
 
804
 
770
 /** 
805
 /** 
771
  * Perform a standard multiplication between two bigints.
806
  * Perform a standard multiplication between two bigints.
807
+ *
808
+ * Barrett reduction has no need for some parts of the product, so ignore bits
809
+ * of the multiply. This routine gives Barrett its big performance
810
+ * improvements over Classical/Montgomery reduction methods.
772
  */
811
  */
773
-static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib)
812
+static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib,
813
+        int inner_partial, int outer_partial)
774
 {
814
 {
775
-    int i, j, i_plus_j;
776
-    int n = bia->size; 
815
+    int i = 0, j;
816
+    int n = bia->size;
777
     int t = bib->size;
817
     int t = bib->size;
778
     bigint *biR = alloc(ctx, n + t);
818
     bigint *biR = alloc(ctx, n + t);
779
     comp *sr = biR->comps;
819
     comp *sr = biR->comps;
785
 
825
 
786
     /* clear things to start with */
826
     /* clear things to start with */
787
     memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE));
827
     memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE));
788
-    i = 0;
789
 
828
 
790
     do 
829
     do 
791
     {
830
     {
831
+        long_comp tmp;
792
         comp carry = 0;
832
         comp carry = 0;
793
-        comp b = *sb++;
794
-        i_plus_j = i;
833
+        int r_index = i;
795
         j = 0;
834
         j = 0;
796
 
835
 
836
+        if (outer_partial && outer_partial-i > 0 && outer_partial < n)
837
+        {
838
+            r_index = outer_partial-1;
839
+            j = outer_partial-i-1;
840
+        }
841
+
797
         do
842
         do
798
         {
843
         {
799
-            long_comp tmp = sr[i_plus_j] + (long_comp)sa[j]*b + carry;
800
-            sr[i_plus_j++] = (comp)tmp;              /* downsize */
801
-            carry = (comp)(tmp >> COMP_BIT_SIZE);
844
+            if (inner_partial && r_index >= inner_partial)
845
+            {
846
+                break;
847
+            }
848
+
849
+            tmp = sr[r_index] + ((long_comp)sa[j])*sb[i] + carry;
850
+            sr[r_index++] = (comp)tmp;              /* downsize */
851
+            carry = tmp >> COMP_BIT_SIZE;
802
         } while (++j < n);
852
         } while (++j < n);
803
 
853
 
804
-        sr[i_plus_j] = carry;
854
+        sr[r_index] = carry;
805
     } while (++i < t);
855
     } while (++i < t);
806
 
856
 
807
     bi_free(ctx, bia);
857
     bi_free(ctx, bia);
881
 #ifdef CONFIG_BIGINT_KARATSUBA
931
 #ifdef CONFIG_BIGINT_KARATSUBA
882
     if (min(bia->size, bib->size) < MUL_KARATSUBA_THRESH)
932
     if (min(bia->size, bib->size) < MUL_KARATSUBA_THRESH)
883
     {
933
     {
884
-        return regular_multiply(ctx, bia, bib);
934
+        return regular_multiply(ctx, bia, bib, 0, 0);
885
     }
935
     }
886
 
936
 
887
     return karatsuba(ctx, bia, bib, 0);
937
     return karatsuba(ctx, bia, bib, 0);
888
 #else
938
 #else
889
-    return regular_multiply(ctx, bia, bib);
939
+    return regular_multiply(ctx, bia, bib, 0, 0);
890
 #endif
940
 #endif
891
 }
941
 }
892
 
942
 
898
 {
948
 {
899
     int t = bi->size;
949
     int t = bi->size;
900
     int i = 0, j;
950
     int i = 0, j;
901
-    bigint *biR = alloc(ctx, t*2);
951
+    bigint *biR = alloc(ctx, t*2+1);
902
     comp *w = biR->comps;
952
     comp *w = biR->comps;
903
     comp *x = bi->comps;
953
     comp *x = bi->comps;
904
-    comp carry;
905
-
954
+    long_comp carry;
906
     memset(w, 0, biR->size*COMP_BYTE_SIZE);
955
     memset(w, 0, biR->size*COMP_BYTE_SIZE);
907
 
956
 
908
     do
957
     do
909
     {
958
     {
910
         long_comp tmp = w[2*i] + (long_comp)x[i]*x[i];
959
         long_comp tmp = w[2*i] + (long_comp)x[i]*x[i];
911
-        comp u = 0;
912
         w[2*i] = (comp)tmp;
960
         w[2*i] = (comp)tmp;
913
-        carry = (comp)(tmp >> COMP_BIT_SIZE);
961
+        carry = tmp >> COMP_BIT_SIZE;
914
 
962
 
915
         for (j = i+1; j < t; j++)
963
         for (j = i+1; j < t; j++)
916
         {
964
         {
965
+            uint8_t c = 0;
917
             long_comp xx = (long_comp)x[i]*x[j];
966
             long_comp xx = (long_comp)x[i]*x[j];
918
-            long_comp blob = (long_comp)w[i+j]+carry;
967
+            if ((COMP_MAX-xx) < xx)
968
+                c = 1;
919
 
969
 
920
-            if (u)                  /* previous overflow */
921
-            {
922
-                blob += COMP_RADIX;
923
-            }
970
+            tmp = (xx<<1);
924
 
971
 
925
-            u = 0;
926
-            if (xx & COMP_BIG_MSB)  /* check for overflow */
927
-            {
928
-                u = 1;
929
-            }
972
+            if ((COMP_MAX-tmp) < w[i+j])
973
+                c = 1;
930
 
974
 
931
-            tmp = 2*xx + blob;
932
-            w[i+j] = (comp)tmp;
933
-            carry = (comp)(tmp >> COMP_BIT_SIZE);
934
-        }
975
+            tmp += w[i+j];
935
 
976
 
936
-        w[i+t] += carry;
977
+            if ((COMP_MAX-tmp) < carry)
978
+                c = 1;
937
 
979
 
938
-        if (u)
939
-        {
940
-            w[i+t+1] = 1;   /* add carry */
980
+            tmp += carry;
981
+            w[i+j] = (comp)tmp;
982
+            carry = tmp >> COMP_BIT_SIZE;
983
+
984
+            if (c)
985
+                carry += COMP_RADIX;
941
         }
986
         }
987
+
988
+        tmp = w[i+t] + carry;
989
+        w[i+t] = (comp)tmp;
990
+        w[i+t+1] = tmp >> COMP_BIT_SIZE;
942
     } while (++i < t);
991
     } while (++i < t);
943
 
992
 
944
     bi_free(ctx, bi);
993
     bi_free(ctx, bi);
1092
         }
1141
         }
1093
 
1142
 
1094
         shift >>= 1;
1143
         shift >>= 1;
1095
-    } while (--i != 0);
1144
+    } while (i-- != 0);
1096
 
1145
 
1097
     return -1;      /* error - must have been a leading 0 */
1146
     return -1;      /* error - must have been a leading 0 */
1098
 }
1147
 }
1115
         shift <<= 1;
1164
         shift <<= 1;
1116
     }
1165
     }
1117
 
1166
 
1118
-    return test & shift;
1167
+    return (test & shift) != 0;
1119
 }
1168
 }
1120
 
1169
 
1121
 #ifdef CONFIG_BIGINT_CHECK_ON
1170
 #ifdef CONFIG_BIGINT_CHECK_ON
1210
     return bi;
1259
     return bi;
1211
 }
1260
 }
1212
 
1261
 
1213
-/*
1214
- * Barrett reduction has no need for some parts of the product, so ignore bits
1215
- * of the multiply. This routine gives Barrett its big performance
1216
- * improvements over Classical/Montgomery reduction methods. 
1217
- */
1218
-static bigint *partial_multiply(BI_CTX *ctx, bigint *bia, bigint *bib, 
1219
-        int inner_partial, int outer_partial)
1220
-{
1221
-    int i = 0, j, n = bia->size, t = bib->size;
1222
-    bigint *biR;
1223
-    comp carry;
1224
-    comp *sr, *sa, *sb;
1225
-
1226
-    check(bia);
1227
-    check(bib);
1228
-
1229
-    biR = alloc(ctx, n + t);
1230
-    sa = bia->comps;
1231
-    sb = bib->comps;
1232
-    sr = biR->comps;
1233
-
1234
-    if (inner_partial)
1235
-    {
1236
-        memset(sr, 0, inner_partial*COMP_BYTE_SIZE); 
1237
-    }
1238
-    else    /* outer partial */
1239
-    {
1240
-        if (n < outer_partial || t < outer_partial) /* should we bother? */
1241
-        {
1242
-            bi_free(ctx, bia);
1243
-            bi_free(ctx, bib);
1244
-            biR->comps[0] = 0;      /* return 0 */
1245
-            biR->size = 1;
1246
-            return biR;
1247
-        }
1248
-
1249
-        memset(&sr[outer_partial], 0, (n+t-outer_partial)*COMP_BYTE_SIZE);
1250
-    }
1251
-
1252
-    do 
1253
-    {
1254
-        comp *a = sa;
1255
-        comp b = *sb++;
1256
-        long_comp tmp;
1257
-        int i_plus_j = i;
1258
-        carry = 0;
1259
-        j = n;
1260
-
1261
-        if (outer_partial && i_plus_j < outer_partial)
1262
-        {
1263
-            i_plus_j = outer_partial;
1264
-            a = &sa[outer_partial-i];
1265
-            j = n-(outer_partial-i);
1266
-        }
1267
-
1268
-        do
1269
-        {
1270
-            if (inner_partial && i_plus_j >= inner_partial) 
1271
-            {
1272
-                break;
1273
-            }
1274
-
1275
-            tmp = sr[i_plus_j] + ((long_comp)*a++)*b + carry;
1276
-            sr[i_plus_j++] = (comp)tmp;              /* downsize */
1277
-            carry = (comp)(tmp >> COMP_BIT_SIZE);
1278
-        } while (--j != 0);
1279
-
1280
-        sr[i_plus_j] = carry;
1281
-    } while (++i < t);
1282
-
1283
-    bi_free(ctx, bia);
1284
-    bi_free(ctx, bib);
1285
-    return trim(biR);
1286
-}
1287
-
1288
 /**
1262
 /**
1289
  * @brief Perform a single Barrett reduction.
1263
  * @brief Perform a single Barrett reduction.
1290
  * @param ctx [in]  The bigint session context.
1264
  * @param ctx [in]  The bigint session context.
1310
     q1 = comp_right_shift(bi_clone(ctx, bi), k-1);
1284
     q1 = comp_right_shift(bi_clone(ctx, bi), k-1);
1311
 
1285
 
1312
     /* do outer partial multiply */
1286
     /* do outer partial multiply */
1313
-    q2 = partial_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1); 
1287
+    q2 = regular_multiply(ctx, q1, ctx->bi_mu[mod_offset], 0, k-1);
1314
     q3 = comp_right_shift(q2, k+1);
1288
     q3 = comp_right_shift(q2, k+1);
1315
     r1 = comp_mod(bi, k+1);
1289
     r1 = comp_mod(bi, k+1);
1316
 
1290
 
1317
     /* do inner partial multiply */
1291
     /* do inner partial multiply */
1318
-    r2 = comp_mod(partial_multiply(ctx, q3, bim, k+1, 0), k+1);
1292
+    r2 = comp_mod(regular_multiply(ctx, q3, bim, k+1, 0), k+1);
1319
     r = bi_subtract(ctx, r1, r2, NULL);
1293
     r = bi_subtract(ctx, r1, r2, NULL);
1320
 
1294
 
1321
     /* if (r >= m) r = r - m; */
1295
     /* if (r >= m) r = r - m; */
1366
  * @param ctx [in]  The bigint session context.
1340
  * @param ctx [in]  The bigint session context.
1367
  * @param bi  [in]  The bigint on which to perform the mod power operation.
1341
  * @param bi  [in]  The bigint on which to perform the mod power operation.
1368
  * @param biexp [in] The bigint exponent.
1342
  * @param biexp [in] The bigint exponent.
1343
+ * @return The result of the mod exponentiation operation
1369
  * @see bi_set_mod().
1344
  * @see bi_set_mod().
1370
  */
1345
  */
1371
 bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
1346
 bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
1467
  * @param bi  [in]  The bigint to perform the exp/mod.
1442
  * @param bi  [in]  The bigint to perform the exp/mod.
1468
  * @param bim [in]  The temporary modulus.
1443
  * @param bim [in]  The temporary modulus.
1469
  * @param biexp [in] The bigint exponent.
1444
  * @param biexp [in] The bigint exponent.
1445
+ * @return The result of the mod exponentiation operation
1470
  * @see bi_set_mod().
1446
  * @see bi_set_mod().
1471
  */
1447
  */
1472
 bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
1448
 bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
1493
     return biR;
1469
     return biR;
1494
 }
1470
 }
1495
 #endif
1471
 #endif
1472
+
1473
+#ifdef CONFIG_BIGINT_CRT
1474
+/**
1475
+ * @brief Use the Chinese Remainder Theorem to quickly perform RSA decrypts.
1476
+ *
1477
+ * @param ctx [in]  The bigint session context.
1478
+ * @param bi  [in]  The bigint to perform the exp/mod.
1479
+ * @param dP [in] CRT's dP bigint
1480
+ * @param dQ [in] CRT's dQ bigint
1481
+ * @param p [in] CRT's p bigint
1482
+ * @param q [in] CRT's q bigint
1483
+ * @param qInv [in] CRT's qInv bigint
1484
+ * @return The result of the CRT operation
1485
+ */
1486
+bigint *bi_crt(BI_CTX *ctx, bigint *bi,
1487
+        bigint *dP, bigint *dQ,
1488
+        bigint *p, bigint *q, bigint *qInv)
1489
+{
1490
+    bigint *m1, *m2, *h;
1491
+
1492
+    /* Montgomery has a condition the 0 < x, y < m and these products violate
1493
+     * that condition. So disable Montgomery when using CRT */
1494
+#if defined(CONFIG_BIGINT_MONTGOMERY)
1495
+    ctx->use_classical = 1;
1496
+#endif
1497
+    ctx->mod_offset = BIGINT_P_OFFSET;
1498
+    m1 = bi_mod_power(ctx, bi_copy(bi), dP);
1499
+
1500
+    ctx->mod_offset = BIGINT_Q_OFFSET;
1501
+    m2 = bi_mod_power(ctx, bi, dQ);
1502
+
1503
+    h = bi_subtract(ctx, bi_add(ctx, m1, p), bi_copy(m2), NULL);
1504
+    h = bi_multiply(ctx, h, qInv);
1505
+    ctx->mod_offset = BIGINT_P_OFFSET;
1506
+    h = bi_residue(ctx, h);
1507
+#if defined(CONFIG_BIGINT_MONTGOMERY)
1508
+    ctx->use_classical = 0;         /* reset for any further operation */
1509
+#endif
1510
+    return bi_add(ctx, m2, bi_multiply(ctx, q, h));
1511
+}
1512
+#endif
1496
 /** @} */
1513
 /** @} */

+ 33
- 27
src/crypto/axtls/bigint.h View File

1
 /*
1
 /*
2
- *  Copyright(C) 2006 Cameron Rich
2
+ * Copyright (c) 2007, Cameron Rich
3
  *
3
  *
4
- *  This library is free software; you can redistribute it and/or modify
5
- *  it under the terms of the GNU Lesser General Public License as published by
6
- *  the Free Software Foundation; either version 2 of the License, or
7
- *  (at your option) any later version.
4
+ * All rights reserved.
8
  *
5
  *
9
- *  This library is distributed in the hope that it will be useful,
10
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
- *  GNU Lesser General Public License for more details.
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
13
  *
8
  *
14
- *  You should have received a copy of the GNU Lesser General Public License
15
- *  along with this library; if not, write to the Free Software
16
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
9
+ * * Redistributions of source code must retain the above copyright notice,
10
+ *   this list of conditions and the following disclaimer.
11
+ * * Redistributions in binary form must reproduce the above copyright notice,
12
+ *   this list of conditions and the following disclaimer in the documentation
13
+ *   and/or other materials provided with the distribution.
14
+ * * Neither the name of the axTLS project nor the names of its contributors
15
+ *   may be used to endorse or promote products derived from this software
16
+ *   without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
  */
29
  */
18
 
30
 
19
-FILE_LICENCE ( GPL2_OR_LATER );
20
-
21
 #ifndef BIGINT_HEADER
31
 #ifndef BIGINT_HEADER
22
 #define BIGINT_HEADER
32
 #define BIGINT_HEADER
23
 
33
 
24
-/* enable features based on a 'super-set' capbaility. */
25
-#if defined(CONFIG_SSL_FULL_MODE) 
26
-#define CONFIG_SSL_ENABLE_CLIENT
27
-#define CONFIG_SSL_CERT_VERIFICATION
28
-#elif defined(CONFIG_SSL_ENABLE_CLIENT)
29
-#define CONFIG_SSL_CERT_VERIFICATION
30
-#endif
31
-
32
-#include "os_port.h"
33
-#include "bigint_impl.h"
34
+#include "crypto.h"
34
 
35
 
35
-#ifndef CONFIG_BIGINT_CHECK_ON
36
-#define check(A)                /**< disappears in normal production mode */
37
-#endif
38
 BI_CTX *bi_initialize(void);
36
 BI_CTX *bi_initialize(void);
39
 void bi_terminate(BI_CTX *ctx);
37
 void bi_terminate(BI_CTX *ctx);
40
 void bi_permanent(bigint *bi);
38
 void bi_permanent(bigint *bi);
41
 void bi_depermanent(bigint *bi);
39
 void bi_depermanent(bigint *bi);
40
+void bi_clear_cache(BI_CTX *ctx);
42
 void bi_free(BI_CTX *ctx, bigint *bi);
41
 void bi_free(BI_CTX *ctx, bigint *bi);
43
 bigint *bi_copy(bigint *bi);
42
 bigint *bi_copy(bigint *bi);
44
 bigint *bi_clone(BI_CTX *ctx, const bigint *bi);
43
 bigint *bi_clone(BI_CTX *ctx, const bigint *bi);
90
 #define bi_square(A, B)     bi_multiply(A, bi_copy(B), B)
89
 #define bi_square(A, B)     bi_multiply(A, bi_copy(B), B)
91
 #endif
90
 #endif
92
 
91
 
92
+#ifdef CONFIG_BIGINT_CRT
93
+bigint *bi_crt(BI_CTX *ctx, bigint *bi,
94
+        bigint *dP, bigint *dQ,
95
+        bigint *p, bigint *q,
96
+        bigint *qInv);
97
+#endif
98
+
93
 #endif
99
 #endif

+ 46
- 20
src/crypto/axtls/bigint_impl.h View File

1
 /*
1
 /*
2
- *  Copyright(C) 2006 Cameron Rich
2
+ * Copyright (c) 2007, Cameron Rich
3
  *
3
  *
4
- *  This library is free software; you can redistribute it and/or modify
5
- *  it under the terms of the GNU Lesser General Public License as published by
6
- *  the Free Software Foundation; either version 2.1 of the License, or
7
- *  (at your option) any later version.
4
+ * All rights reserved.
8
  *
5
  *
9
- *  This library is distributed in the hope that it will be useful,
10
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
- *  GNU Lesser General Public License for more details.
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
13
  *
8
  *
14
- *  You should have received a copy of the GNU Lesser General Public License
15
- *  along with this library; if not, write to the Free Software
16
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
9
+ * * Redistributions of source code must retain the above copyright notice,
10
+ *   this list of conditions and the following disclaimer.
11
+ * * Redistributions in binary form must reproduce the above copyright notice,
12
+ *   this list of conditions and the following disclaimer in the documentation
13
+ *   and/or other materials provided with the distribution.
14
+ * * Neither the name of the axTLS project nor the names of its contributors
15
+ *   may be used to endorse or promote products derived from this software
16
+ *   without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
  */
29
  */
18
 
30
 
19
 #ifndef BIGINT_IMPL_HEADER
31
 #ifndef BIGINT_IMPL_HEADER
30
 #endif
42
 #endif
31
 
43
 
32
 /* Architecture specific functions for big ints */
44
 /* Architecture specific functions for big ints */
45
+#if defined(CONFIG_INTEGER_8BIT)
46
+#define COMP_RADIX          256U       /**< Max component + 1 */
47
+#define COMP_MAX            0xFFFFU/**< (Max dbl comp -1) */
48
+#define COMP_BIT_SIZE       8   /**< Number of bits in a component. */
49
+#define COMP_BYTE_SIZE      1   /**< Number of bytes in a component. */
50
+#define COMP_NUM_NIBBLES    2   /**< Used For diagnostics only. */
51
+typedef uint8_t comp;	        /**< A single precision component. */
52
+typedef uint16_t long_comp;     /**< A double precision component. */
53
+typedef int16_t slong_comp;     /**< A signed double precision component. */
54
+#elif defined(CONFIG_INTEGER_16BIT)
55
+#define COMP_RADIX          65536U       /**< Max component + 1 */
56
+#define COMP_MAX            0xFFFFFFFFU/**< (Max dbl comp -1) */
57
+#define COMP_BIT_SIZE       16  /**< Number of bits in a component. */
58
+#define COMP_BYTE_SIZE      2   /**< Number of bytes in a component. */
59
+#define COMP_NUM_NIBBLES    4   /**< Used For diagnostics only. */
60
+typedef uint16_t comp;	        /**< A single precision component. */
61
+typedef uint32_t long_comp;     /**< A double precision component. */
62
+typedef int32_t slong_comp;     /**< A signed double precision component. */
63
+#else /* regular 32 bit */
33
 #ifdef WIN32
64
 #ifdef WIN32
34
 #define COMP_RADIX          4294967296i64         
65
 #define COMP_RADIX          4294967296i64         
35
-#define COMP_BIG_MSB        0x8000000000000000i64 
66
+#define COMP_MAX            0xFFFFFFFFFFFFFFFFui64
36
 #else
67
 #else
37
 #define COMP_RADIX          4294967296ULL         /**< Max component + 1 */
68
 #define COMP_RADIX          4294967296ULL         /**< Max component + 1 */
38
-#define COMP_BIG_MSB        0x8000000000000000ULL /**< (Max dbl comp + 1)/ 2 */
69
+#define COMP_MAX            0xFFFFFFFFFFFFFFFFULL/**< (Max dbl comp -1) */
39
 #endif
70
 #endif
40
 #define COMP_BIT_SIZE       32  /**< Number of bits in a component. */
71
 #define COMP_BIT_SIZE       32  /**< Number of bits in a component. */
41
 #define COMP_BYTE_SIZE      4   /**< Number of bytes in a component. */
72
 #define COMP_BYTE_SIZE      4   /**< Number of bytes in a component. */
42
 #define COMP_NUM_NIBBLES    8   /**< Used For diagnostics only. */
73
 #define COMP_NUM_NIBBLES    8   /**< Used For diagnostics only. */
43
-
44
 typedef uint32_t comp;	        /**< A single precision component. */
74
 typedef uint32_t comp;	        /**< A single precision component. */
45
 typedef uint64_t long_comp;     /**< A double precision component. */
75
 typedef uint64_t long_comp;     /**< A double precision component. */
46
 typedef int64_t slong_comp;     /**< A signed double precision component. */
76
 typedef int64_t slong_comp;     /**< A signed double precision component. */
77
+#endif
47
 
78
 
48
 /**
79
 /**
49
  * @struct  _bigint
80
  * @struct  _bigint
97
 
128
 
98
 #define PERMANENT           0x7FFF55AA  /**< A magic number for permanents. */
129
 #define PERMANENT           0x7FFF55AA  /**< A magic number for permanents. */
99
 
130
 
100
-#define V1      v->comps[v->size-1]                 /**< v1 for division */
101
-#define V2      v->comps[v->size-2]                 /**< v2 for division */
102
-#define U(j)    tmp_u->comps[tmp_u->size-j-1]       /**< uj for division */
103
-#define Q(j)    quotient->comps[quotient->size-j-1] /**< qj for division */
104
-
105
 #endif
131
 #endif

+ 13
- 0
src/crypto/axtls/config.h View File

1
+#ifndef AXTLS_CONFIG_H
2
+#define AXTLS_CONFIG_H
3
+
4
+/**
5
+ * @file config.h
6
+ *
7
+ * Trick the axtls code into building within our build environment.
8
+ */
9
+
10
+#define CONFIG_SSL_ENABLE_CLIENT 1
11
+#define CONFIG_BIGINT_CLASSICAL 1
12
+
13
+#endif

+ 81
- 161
src/crypto/axtls/crypto.h View File

1
 /*
1
 /*
2
- *  Copyright(C) 2006 Cameron Rich
2
+ * Copyright (c) 2007, Cameron Rich
3
  *
3
  *
4
- *  This library is free software; you can redistribute it and/or modify
5
- *  it under the terms of the GNU Lesser General Public License as published by
6
- *  the Free Software Foundation; either version 2 of the License, or
7
- *  (at your option) any later version.
4
+ * All rights reserved.
8
  *
5
  *
9
- *  This library is distributed in the hope that it will be useful,
10
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
- *  GNU Lesser General Public License for more details.
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
13
  *
8
  *
14
- *  You should have received a copy of the GNU Lesser General Public License
15
- *  along with this library; if not, write to the Free Software
16
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
9
+ * * Redistributions of source code must retain the above copyright notice,
10
+ *   this list of conditions and the following disclaimer.
11
+ * * Redistributions in binary form must reproduce the above copyright notice,
12
+ *   this list of conditions and the following disclaimer in the documentation
13
+ *   and/or other materials provided with the distribution.
14
+ * * Neither the name of the axTLS project nor the names of its contributors
15
+ *   may be used to endorse or promote products derived from this software
16
+ *   without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
  */
29
  */
18
 
30
 
19
-FILE_LICENCE ( GPL2_OR_LATER );
20
-
21
 /**
31
 /**
22
  * @file crypto.h
32
  * @file crypto.h
23
  */
33
  */
29
 extern "C" {
39
 extern "C" {
30
 #endif
40
 #endif
31
 
41
 
42
+#include "config.h"
43
+#include "bigint_impl.h"
32
 #include "bigint.h"
44
 #include "bigint.h"
33
 
45
 
46
+#ifndef STDCALL
47
+#define STDCALL
48
+#endif
49
+#ifndef EXP_FUNC
50
+#define EXP_FUNC
51
+#endif
52
+
53
+
54
+/* enable features based on a 'super-set' capbaility. */
55
+#if defined(CONFIG_SSL_FULL_MODE)
56
+#define CONFIG_SSL_ENABLE_CLIENT
57
+#define CONFIG_SSL_CERT_VERIFICATION
58
+#elif defined(CONFIG_SSL_ENABLE_CLIENT)
59
+#define CONFIG_SSL_CERT_VERIFICATION
60
+#endif
61
+
34
 /**************************************************************************
62
 /**************************************************************************
35
  * AES declarations 
63
  * AES declarations 
36
  **************************************************************************/
64
  **************************************************************************/
37
 
65
 
38
 #define AES_MAXROUNDS			14
66
 #define AES_MAXROUNDS			14
67
+#define AES_BLOCKSIZE           16
68
+#define AES_IV_SIZE             16
39
 
69
 
40
 typedef struct aes_key_st 
70
 typedef struct aes_key_st 
41
 {
71
 {
42
     uint16_t rounds;
72
     uint16_t rounds;
43
     uint16_t key_size;
73
     uint16_t key_size;
44
     uint32_t ks[(AES_MAXROUNDS+1)*8];
74
     uint32_t ks[(AES_MAXROUNDS+1)*8];
45
-    uint8_t iv[16];
75
+    uint8_t iv[AES_IV_SIZE];
46
 } AES_CTX;
76
 } AES_CTX;
47
 
77
 
48
 typedef enum
78
 typedef enum
57
         uint8_t *out, int length);
87
         uint8_t *out, int length);
58
 void AES_cbc_decrypt(AES_CTX *ks, const uint8_t *in, uint8_t *out, int length);
88
 void AES_cbc_decrypt(AES_CTX *ks, const uint8_t *in, uint8_t *out, int length);
59
 void AES_convert_key(AES_CTX *ctx);
89
 void AES_convert_key(AES_CTX *ctx);
60
-void AES_encrypt(const AES_CTX *ctx, uint32_t *data);
61
-void AES_decrypt(const AES_CTX *ctx, uint32_t *data);
62
 
90
 
63
 /**************************************************************************
91
 /**************************************************************************
64
  * RC4 declarations 
92
  * RC4 declarations 
66
 
94
 
67
 typedef struct 
95
 typedef struct 
68
 {
96
 {
69
-    int x, y, m[256];
97
+    uint8_t x, y, m[256];
70
 } RC4_CTX;
98
 } RC4_CTX;
71
 
99
 
72
 void RC4_setup(RC4_CTX *s, const uint8_t *key, int length);
100
 void RC4_setup(RC4_CTX *s, const uint8_t *key, int length);
84
  */
112
  */
85
 typedef struct 
113
 typedef struct 
86
 {
114
 {
87
-    uint32_t Intermediate_Hash[SHA1_SIZE/4]; /* Message Digest  */
88
-    uint32_t Length_Low;            /* Message length in bits      */
89
-    uint32_t Length_High;           /* Message length in bits      */
115
+    uint32_t Intermediate_Hash[SHA1_SIZE/4]; /* Message Digest */
116
+    uint32_t Length_Low;            /* Message length in bits */
117
+    uint32_t Length_High;           /* Message length in bits */
90
     uint16_t Message_Block_Index;   /* Index into message block array   */
118
     uint16_t Message_Block_Index;   /* Index into message block array   */
91
-    uint8_t Message_Block[64];      /* 512-bit message blocks      */
119
+    uint8_t Message_Block[64];      /* 512-bit message blocks */
92
 } SHA1_CTX;
120
 } SHA1_CTX;
93
 
121
 
94
-void SHA1Init(SHA1_CTX *);
95
-void SHA1Update(SHA1_CTX *, const uint8_t * msg, int len);
96
-void SHA1Final(SHA1_CTX *, uint8_t *digest);
122
+void SHA1_Init(SHA1_CTX *);
123
+void SHA1_Update(SHA1_CTX *, const uint8_t * msg, int len);
124
+void SHA1_Final(uint8_t *digest, SHA1_CTX *);
97
 
125
 
98
 /**************************************************************************
126
 /**************************************************************************
99
- * MD5 declarations 
127
+ * MD2 declarations
100
  **************************************************************************/
128
  **************************************************************************/
101
 
129
 
102
-/* MD5 context. */
130
+#define MD2_SIZE 16
131
+
132
+typedef struct
133
+{
134
+    unsigned char cksum[16];    /* checksum of the data block */
135
+    unsigned char state[48];    /* intermediate digest state */
136
+    unsigned char buffer[16];   /* data block being processed */
137
+    int left;                   /* amount of data in buffer */
138
+} MD2_CTX;
139
+
140
+EXP_FUNC void STDCALL MD2_Init(MD2_CTX *ctx);
141
+EXP_FUNC void STDCALL MD2_Update(MD2_CTX *ctx, const uint8_t *input, int ilen);
142
+EXP_FUNC void STDCALL MD2_Final(uint8_t *digest, MD2_CTX *ctx);
143
+
144
+/**************************************************************************
145
+ * MD5 declarations
146
+ **************************************************************************/
103
 
147
 
104
 #define MD5_SIZE    16
148
 #define MD5_SIZE    16
105
 
149
 
110
   uint8_t buffer[64];       /* input buffer */
154
   uint8_t buffer[64];       /* input buffer */
111
 } MD5_CTX;
155
 } MD5_CTX;
112
 
156
 
113
-void MD5Init(MD5_CTX *);
114
-void MD5Update(MD5_CTX *, const uint8_t *msg, int len);
115
-void MD5Final(MD5_CTX *, uint8_t *digest);
157
+EXP_FUNC void STDCALL MD5_Init(MD5_CTX *);
158
+EXP_FUNC void STDCALL MD5_Update(MD5_CTX *, const uint8_t *msg, int len);
159
+EXP_FUNC void STDCALL MD5_Final(uint8_t *digest, MD5_CTX *);
116
 
160
 
117
 /**************************************************************************
161
 /**************************************************************************
118
  * HMAC declarations 
162
  * HMAC declarations 
122
 void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, 
166
 void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, 
123
         int key_len, uint8_t *digest);
167
         int key_len, uint8_t *digest);
124
 
168
 
125
-/**************************************************************************
126
- * RNG declarations 
127
- **************************************************************************/
128
-void RNG_initialize(const uint8_t *seed_buf, int size);
129
-void RNG_terminate(void);
130
-void get_random(int num_rand_bytes, uint8_t *rand_data);
131
-//void get_random_NZ(int num_rand_bytes, uint8_t *rand_data);
132
-
133
-#include <ipxe/random_nz.h>
134
-static inline void get_random_NZ(int num_rand_bytes, uint8_t *rand_data) {
135
-	/* AXTLS does not check for failures when generating random
136
-	 * data.  Rely on the fact that get_random_nz() does not
137
-	 * request prediction resistance (and so cannot introduce new
138
-	 * failures) and therefore any potential failure must already
139
-	 * have been encountered by e.g. tls_generate_random(), which
140
-	 * does check for failures.
141
-	 */
142
-	get_random_nz ( rand_data, num_rand_bytes );
143
-}
144
-
145
 /**************************************************************************
169
 /**************************************************************************
146
  * RSA declarations 
170
  * RSA declarations 
147
  **************************************************************************/
171
  **************************************************************************/
159
     bigint *qInv;           /* q^-1 mod p */
183
     bigint *qInv;           /* q^-1 mod p */
160
 #endif
184
 #endif
161
     int num_octets;
185
     int num_octets;
162
-    bigint *sig_m;         /* signature modulus */
163
     BI_CTX *bi_ctx;
186
     BI_CTX *bi_ctx;
164
 } RSA_CTX;
187
 } RSA_CTX;
165
 
188
 
182
 int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint8_t *out_data,
205
 int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint8_t *out_data,
183
         int is_decryption);
206
         int is_decryption);
184
 bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg);
207
 bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg);
185
-#ifdef CONFIG_SSL_CERT_VERIFICATION
186
-bigint *RSA_raw_sign_verify(RSA_CTX *c, bigint *bi_msg);
208
+#if defined(CONFIG_SSL_CERT_VERIFICATION) || defined(CONFIG_SSL_GENERATE_X509_CERT)
187
 bigint *RSA_sign_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len,
209
 bigint *RSA_sign_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len,
188
         bigint *modulus, bigint *pub_exp);
210
         bigint *modulus, bigint *pub_exp);
189
-bigint *RSA_public(const RSA_CTX *c, bigint *bi_msg);
211
+bigint *RSA_public(const RSA_CTX * c, bigint *bi_msg);
190
 int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, 
212
 int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, 
191
         uint8_t *out_data, int is_signing);
213
         uint8_t *out_data, int is_signing);
192
 void RSA_print(const RSA_CTX *ctx);
214
 void RSA_print(const RSA_CTX *ctx);
193
 #endif
215
 #endif
194
 
216
 
195
 /**************************************************************************
217
 /**************************************************************************
196
- * ASN1 declarations 
197
- **************************************************************************/
198
-#define X509_OK                             0
199
-#define X509_NOT_OK                         -1
200
-#define X509_VFY_ERROR_NO_TRUSTED_CERT      -2
201
-#define X509_VFY_ERROR_BAD_SIGNATURE        -3      
202
-#define X509_VFY_ERROR_NOT_YET_VALID        -4
203
-#define X509_VFY_ERROR_EXPIRED              -5
204
-#define X509_VFY_ERROR_SELF_SIGNED          -6
205
-#define X509_VFY_ERROR_INVALID_CHAIN        -7
206
-#define X509_VFY_ERROR_UNSUPPORTED_DIGEST   -8
207
-#define X509_INVALID_PRIV_KEY               -9
208
-
209
-/*
210
- * The Distinguished Name
211
- */
212
-#define X509_NUM_DN_TYPES                   3
213
-#define X509_COMMON_NAME                    0
214
-#define X509_ORGANIZATION                   1
215
-#define X509_ORGANIZATIONAL_TYPE            2
216
-
217
-#define ASN1_INTEGER            0x02
218
-#define ASN1_BIT_STRING         0x03
219
-#define ASN1_OCTET_STRING       0x04
220
-#define ASN1_NULL               0x05
221
-#define ASN1_OID                0x06
222
-#define ASN1_PRINTABLE_STR      0x13
223
-#define ASN1_TELETEX_STR        0x14
224
-#define ASN1_IA5_STR            0x16
225
-#define ASN1_UTC_TIME           0x17
226
-#define ASN1_SEQUENCE           0x30
227
-#define ASN1_SET                0x31
228
-#define ASN1_IMPLICIT_TAG       0x80
229
-#define ASN1_EXPLICIT_TAG       0xa0
230
-
231
-#define SALT_SIZE               8
232
-
233
-struct _x509_ctx
234
-{
235
-    char *ca_cert_dn[X509_NUM_DN_TYPES];
236
-    char *cert_dn[X509_NUM_DN_TYPES];
237
-#if defined(_WIN32_WCE)
238
-    long not_before;
239
-    long not_after;
240
-#else
241
-    time_t not_before;
242
-    time_t not_after;
243
-#endif
244
-    uint8_t *signature;
245
-    uint16_t sig_len;
246
-    uint8_t sig_type;
247
-    RSA_CTX *rsa_ctx;
248
-    bigint *digest;
249
-    struct _x509_ctx *next;
250
-};
251
-
252
-typedef struct _x509_ctx X509_CTX;
253
-
254
-#ifdef CONFIG_SSL_CERT_VERIFICATION
255
-typedef struct 
256
-{
257
-    X509_CTX *cert[CONFIG_X509_MAX_CA_CERTS];
258
-} CA_CERT_CTX;
259
-#endif
260
-
261
-int asn1_get_private_key(const uint8_t *buf, int len, RSA_CTX **rsa_ctx);
262
-int asn1_next_obj(const uint8_t *buf, int *offset, int obj_type);
263
-int asn1_skip_obj(const uint8_t *buf, int *offset, int obj_type);
264
-int asn1_get_int(const uint8_t *buf, int *offset, uint8_t **object);
265
-int x509_new(const uint8_t *cert, int *len, X509_CTX **ctx);
266
-void x509_free(X509_CTX *x509_ctx);
267
-#ifdef CONFIG_SSL_CERT_VERIFICATION
268
-int x509_verify(const CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert);
269
-const uint8_t *x509_get_signature(const uint8_t *asn1_signature, int *len);
270
-#endif
271
-#ifdef CONFIG_SSL_FULL_MODE
272
-void x509_print(CA_CERT_CTX *ca_cert_ctx, const X509_CTX *cert);
273
-void x509_display_error(int error);
274
-#endif
275
-
276
-/**************************************************************************
277
- * MISC declarations 
218
+ * RNG declarations
278
  **************************************************************************/
219
  **************************************************************************/
279
-
280
-extern const char * const unsupported_str;
281
-
282
-typedef void (*crypt_func)(void *, const uint8_t *, uint8_t *, int);
283
-typedef void (*hmac_func)(const uint8_t *msg, int length, const uint8_t *key, 
284
-        int key_len, uint8_t *digest);
285
-
286
-typedef struct
287
-{
288
-    uint8_t *pre_data;	/* include the ssl record bytes */
289
-    uint8_t *data;	/* the regular ssl data */
290
-    int max_len;
291
-    int index;
292
-} BUF_MEM;
293
-
294
-BUF_MEM buf_new(void);
295
-void buf_grow(BUF_MEM *bm, int len);
296
-void buf_free(BUF_MEM *bm);
297
-int get_file(const char *filename, uint8_t **buf);
298
-
299
-#if defined(CONFIG_SSL_FULL_MODE) || defined(WIN32) || defined(CONFIG_DEBUG)
300
-void print_blob(const char *format, const uint8_t *data, int size, ...);
301
-#else
302
-    #define print_blob(...)
303
-#endif
220
+EXP_FUNC void STDCALL RNG_initialize(const uint8_t *seed_buf, int size);
221
+EXP_FUNC void STDCALL RNG_terminate(void);
222
+EXP_FUNC void STDCALL get_random(int num_rand_bytes, uint8_t *rand_data);
223
+void get_random_NZ(int num_rand_bytes, uint8_t *rand_data);
304
 
224
 
305
 #ifdef __cplusplus
225
 #ifdef __cplusplus
306
 }
226
 }

+ 30
- 37
src/crypto/axtls/os_port.h View File

1
+#ifndef AXTLS_OS_PORT_H
2
+#define AXTLS_OS_PORT_H
3
+
1
 /**
4
 /**
2
  * @file os_port.h
5
  * @file os_port.h
3
  *
6
  *
4
  * Trick the axtls code into building within our build environment.
7
  * Trick the axtls code into building within our build environment.
5
  */
8
  */
6
 
9
 
7
-#ifndef HEADER_OS_PORT_H
8
-#define HEADER_OS_PORT_H
9
-
10
 #include <stdint.h>
10
 #include <stdint.h>
11
-#include <stddef.h>
12
-#include <stdlib.h>
13
-#include <time.h>
14
-#include <sys/time.h>
15
 #include <byteswap.h>
11
 #include <byteswap.h>
16
 
12
 
17
-#define STDCALL
18
-#define EXP_FUNC
19
-#define TTY_FLUSH()
13
+/** All imported axTLS files are licensed using the three-clause BSD licence */
14
+FILE_LICENCE ( BSD3 );
20
 
15
 
21
 /** We can't actually abort, since we are effectively a kernel... */
16
 /** We can't actually abort, since we are effectively a kernel... */
22
 #define abort() assert ( 0 )
17
 #define abort() assert ( 0 )
23
 
18
 
24
-/** crypto_misc.c has a bad #ifdef */
25
-static inline void close ( int fd __unused ) {
26
-	/* Do nothing */
19
+/** rsa.c uses alloca() */
20
+#define alloca( size ) __builtin_alloca ( size )
21
+
22
+#include <ipxe/random_nz.h>
23
+static inline void get_random_NZ ( int num_rand_bytes, uint8_t *rand_data ) {
24
+	/* AXTLS does not check for failures when generating random
25
+	 * data.  Rely on the fact that get_random_nz() does not
26
+	 * request prediction resistance (and so cannot introduce new
27
+	 * failures) and therefore any potential failure must already
28
+	 * have been encountered by e.g. tls_generate_random(), which
29
+	 * does check for failures.
30
+	 */
31
+	get_random_nz ( rand_data, num_rand_bytes );
27
 }
32
 }
28
 
33
 
29
-typedef void FILE;
30
-
31
-static inline FILE * fopen ( const char *filename __unused,
32
-			     const char *mode __unused ) {
33
-	return NULL;
34
-}
34
+/* Expose AES_encrypt() and AES_decrypt() in aes.o */
35
+#define aes 1
36
+#if OBJECT
35
 
37
 
36
-static inline int fseek ( FILE *stream __unused, long offset __unused,
37
-			  int whence __unused ) {
38
-	return -1;
39
-}
38
+/* AES_CTX is not defined at this point, so omit prototypes */
40
 
39
 
41
-static inline long ftell ( FILE *stream __unused ) {
42
-	return -1;
43
-}
40
+static void AES_encrypt();
41
+static void AES_decrypt();
44
 
42
 
45
-static inline size_t fread ( void *ptr __unused, size_t size __unused,
46
-			     size_t nmemb __unused, FILE *stream __unused ) {
47
-	return -1;
43
+void axtls_aes_encrypt ( void *ctx, uint32_t *data ) {
44
+	AES_encrypt ( ctx, data );
48
 }
45
 }
49
 
46
 
50
-static inline int fclose ( FILE *stream __unused ) {
51
-	return -1;
47
+void axtls_aes_decrypt ( void *ctx, uint32_t *data ) {
48
+	AES_decrypt ( ctx, data );
52
 }
49
 }
53
 
50
 
54
-#define CONFIG_SSL_CERT_VERIFICATION 1
55
-#define CONFIG_SSL_MAX_CERTS 1
56
-#define CONFIG_X509_MAX_CA_CERTS 1
57
-#define CONFIG_SSL_EXPIRY_TIME 24
58
-#define CONFIG_SSL_ENABLE_CLIENT 1
59
-#define CONFIG_BIGINT_CLASSICAL 1
51
+#endif
52
+#undef aes
60
 
53
 
61
 #endif 
54
 #endif 

+ 40
- 103
src/crypto/axtls/rsa.c View File

1
 /*
1
 /*
2
- *  Copyright(C) 2006 Cameron Rich
2
+ * Copyright (c) 2007, Cameron Rich
3
  *
3
  *
4
- *  This library is free software; you can redistribute it and/or modify
5
- *  it under the terms of the GNU Lesser General Public License as published by
6
- *  the Free Software Foundation; either version 2.1 of the License, or
7
- *  (at your option) any later version.
4
+ * All rights reserved.
8
  *
5
  *
9
- *  This library is distributed in the hope that it will be useful,
10
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
- *  GNU Lesser General Public License for more details.
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
13
  *
8
  *
14
- *  You should have received a copy of the GNU Lesser General Public License
15
- *  along with this library; if not, write to the Free Software
16
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
9
+ * * Redistributions of source code must retain the above copyright notice,
10
+ *   this list of conditions and the following disclaimer.
11
+ * * Redistributions in binary form must reproduce the above copyright notice,
12
+ *   this list of conditions and the following disclaimer in the documentation
13
+ *   and/or other materials provided with the distribution.
14
+ * * Neither the name of the axTLS project nor the names of its contributors
15
+ *   may be used to endorse or promote products derived from this software
16
+ *   without specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
  */
29
  */
18
 
30
 
19
 /**
31
 /**
25
 #include <string.h>
37
 #include <string.h>
26
 #include <time.h>
38
 #include <time.h>
27
 #include <stdlib.h>
39
 #include <stdlib.h>
40
+#include "os_port.h"
28
 #include "crypto.h"
41
 #include "crypto.h"
29
 
42
 
30
-#ifdef CONFIG_BIGINT_CRT
31
-static bigint *bi_crt(const RSA_CTX *rsa, bigint *bi);
32
-#endif
33
-
34
 void RSA_priv_key_new(RSA_CTX **ctx, 
43
 void RSA_priv_key_new(RSA_CTX **ctx, 
35
         const uint8_t *modulus, int mod_len,
44
         const uint8_t *modulus, int mod_len,
36
         const uint8_t *pub_exp, int pub_len,
45
         const uint8_t *pub_exp, int pub_len,
71
         const uint8_t *pub_exp, int pub_len)
80
         const uint8_t *pub_exp, int pub_len)
72
 {
81
 {
73
     RSA_CTX *rsa_ctx;
82
     RSA_CTX *rsa_ctx;
74
-    BI_CTX *bi_ctx = bi_initialize();
83
+    BI_CTX *bi_ctx;
84
+
85
+    if (*ctx)   /* if we load multiple certs, dump the old one */
86
+        RSA_free(*ctx);
87
+
88
+    bi_ctx = bi_initialize();
75
     *ctx = (RSA_CTX *)calloc(1, sizeof(RSA_CTX));
89
     *ctx = (RSA_CTX *)calloc(1, sizeof(RSA_CTX));
76
     rsa_ctx = *ctx;
90
     rsa_ctx = *ctx;
77
     rsa_ctx->bi_ctx = bi_ctx;
91
     rsa_ctx->bi_ctx = bi_ctx;
78
-    rsa_ctx->num_octets = (mod_len & 0xFFF0);
92
+    rsa_ctx->num_octets = mod_len;
79
     rsa_ctx->m = bi_import(bi_ctx, modulus, mod_len);
93
     rsa_ctx->m = bi_import(bi_ctx, modulus, mod_len);
80
     bi_set_mod(bi_ctx, rsa_ctx->m, BIGINT_M_OFFSET);
94
     bi_set_mod(bi_ctx, rsa_ctx->m, BIGINT_M_OFFSET);
81
     rsa_ctx->e = bi_import(bi_ctx, pub_exp, pub_len);
95
     rsa_ctx->e = bi_import(bi_ctx, pub_exp, pub_len);
129
 int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, 
143
 int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, 
130
                             uint8_t *out_data, int is_decryption)
144
                             uint8_t *out_data, int is_decryption)
131
 {
145
 {
132
-    int byte_size = ctx->num_octets;
133
-    uint8_t *block;
146
+    const int byte_size = ctx->num_octets;
134
     int i, size;
147
     int i, size;
135
     bigint *decrypted_bi, *dat_bi;
148
     bigint *decrypted_bi, *dat_bi;
149
+    uint8_t *block = (uint8_t *)alloca(byte_size);
136
 
150
 
137
     memset(out_data, 0, byte_size); /* initialise */
151
     memset(out_data, 0, byte_size); /* initialise */
138
 
152
 
146
 #endif
160
 #endif
147
 
161
 
148
     /* convert to a normal block */
162
     /* convert to a normal block */
149
-    block = (uint8_t *)malloc(byte_size);
150
     bi_export(ctx->bi_ctx, decrypted_bi, block, byte_size);
163
     bi_export(ctx->bi_ctx, decrypted_bi, block, byte_size);
151
 
164
 
152
     i = 10; /* start at the first possible non-padded byte */
165
     i = 10; /* start at the first possible non-padded byte */
170
     if (size > 0)
183
     if (size > 0)
171
         memcpy(out_data, &block[i], size);
184
         memcpy(out_data, &block[i], size);
172
     
185
     
173
-    free(block);
174
     return size ? size : -1;
186
     return size ? size : -1;
175
 }
187
 }
176
 
188
 
180
 bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg)
192
 bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg)
181
 {
193
 {
182
 #ifdef CONFIG_BIGINT_CRT
194
 #ifdef CONFIG_BIGINT_CRT
183
-    return bi_crt(c, bi_msg);
195
+    return bi_crt(c->bi_ctx, bi_msg, c->dP, c->dQ, c->p, c->q, c->qInv);
184
 #else
196
 #else
185
     BI_CTX *ctx = c->bi_ctx;
197
     BI_CTX *ctx = c->bi_ctx;
186
     ctx->mod_offset = BIGINT_M_OFFSET;
198
     ctx->mod_offset = BIGINT_M_OFFSET;
188
 #endif
200
 #endif
189
 }
201
 }
190
 
202
 
191
-#ifdef CONFIG_BIGINT_CRT
192
-/**
193
- * Use the Chinese Remainder Theorem to quickly perform RSA decrypts.
194
- * This should really be in bigint.c (and was at one stage), but needs 
195
- * access to the RSA_CTX context...
196
- */
197
-static bigint *bi_crt(const RSA_CTX *rsa, bigint *bi)
198
-{
199
-    BI_CTX *ctx = rsa->bi_ctx;
200
-    bigint *m1, *m2, *h;
201
-
202
-    /* Montgomery has a condition the 0 < x, y < m and these products violate
203
-     * that condition. So disable Montgomery when using CRT */
204
-#if defined(CONFIG_BIGINT_MONTGOMERY)
205
-    ctx->use_classical = 1;
206
-#endif
207
-    ctx->mod_offset = BIGINT_P_OFFSET;
208
-    m1 = bi_mod_power(ctx, bi_copy(bi), rsa->dP);
209
-
210
-    ctx->mod_offset = BIGINT_Q_OFFSET;
211
-    m2 = bi_mod_power(ctx, bi, rsa->dQ);
212
-
213
-    h = bi_subtract(ctx, bi_add(ctx, m1, rsa->p), bi_copy(m2), NULL);
214
-    h = bi_multiply(ctx, h, rsa->qInv);
215
-    ctx->mod_offset = BIGINT_P_OFFSET;
216
-    h = bi_residue(ctx, h);
217
-#if defined(CONFIG_BIGINT_MONTGOMERY)
218
-    ctx->use_classical = 0;         /* reset for any further operation */
219
-#endif
220
-    return bi_add(ctx, m2, bi_multiply(ctx, rsa->q, h));
221
-}
222
-#endif
223
-
224
 #ifdef CONFIG_SSL_FULL_MODE
203
 #ifdef CONFIG_SSL_FULL_MODE
225
 /**
204
 /**
226
  * Used for diagnostics.
205
  * Used for diagnostics.
238
 }
217
 }
239
 #endif
218
 #endif
240
 
219
 
241
-#ifdef CONFIG_SSL_CERT_VERIFICATION
220
+#if defined(CONFIG_SSL_CERT_VERIFICATION) || defined(CONFIG_SSL_GENERATE_X509_CERT)
242
 /**
221
 /**
243
  * Performs c = m^e mod n
222
  * Performs c = m^e mod n
244
  */
223
  */
279
     /* now encrypt it */
258
     /* now encrypt it */
280
     dat_bi = bi_import(ctx->bi_ctx, out_data, byte_size);
259
     dat_bi = bi_import(ctx->bi_ctx, out_data, byte_size);
281
     encrypt_bi = is_signing ? RSA_private(ctx, dat_bi) : 
260
     encrypt_bi = is_signing ? RSA_private(ctx, dat_bi) : 
282
-        RSA_public(ctx, dat_bi);
261
+                              RSA_public(ctx, dat_bi);
283
     bi_export(ctx->bi_ctx, encrypt_bi, out_data, byte_size);
262
     bi_export(ctx->bi_ctx, encrypt_bi, out_data, byte_size);
284
-    return byte_size;
285
-}
286
 
263
 
287
-#if 0
288
-/**
289
- * Take a signature and decrypt it.
290
- */
291
-bigint *RSA_sign_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len,
292
-        bigint *modulus, bigint *pub_exp)
293
-{
294
-    uint8_t *block;
295
-    int i, size;
296
-    bigint *decrypted_bi, *dat_bi;
297
-    bigint *bir = NULL;
298
-
299
-    block = (uint8_t *)malloc(sig_len);
300
-
301
-    /* decrypt */
302
-    dat_bi = bi_import(ctx, sig, sig_len);
303
-    ctx->mod_offset = BIGINT_M_OFFSET;
304
-
305
-    /* convert to a normal block */
306
-    decrypted_bi = bi_mod_power2(ctx, dat_bi, modulus, pub_exp);
307
-
308
-    bi_export(ctx, decrypted_bi, block, sig_len);
309
-    ctx->mod_offset = BIGINT_M_OFFSET;
310
-
311
-    i = 10; /* start at the first possible non-padded byte */
312
-    while (block[i++] && i < sig_len);
313
-    size = sig_len - i;
314
-
315
-    /* get only the bit we want */
316
-    if (size > 0)
317
-    {
318
-        int len;
319
-        const uint8_t *sig_ptr = x509_get_signature(&block[i], &len);
320
-
321
-        if (sig_ptr)
322
-        {
323
-            bir = bi_import(ctx, sig_ptr, len);
324
-        }
325
-    }
326
-
327
-    free(block);
328
-    return bir;
264
+    /* save a few bytes of memory */
265
+    bi_clear_cache(ctx->bi_ctx);
266
+    return byte_size;
329
 }
267
 }
330
-#endif
331
 
268
 
332
 #endif  /* CONFIG_SSL_CERT_VERIFICATION */
269
 #endif  /* CONFIG_SSL_CERT_VERIFICATION */

+ 3
- 2
src/crypto/axtls_aes.c View File

20
 
20
 
21
 #include <string.h>
21
 #include <string.h>
22
 #include <errno.h>
22
 #include <errno.h>
23
+#include <assert.h>
23
 #include <byteswap.h>
24
 #include <byteswap.h>
24
 #include <ipxe/crypto.h>
25
 #include <ipxe/crypto.h>
25
 #include <ipxe/cbc.h>
26
 #include <ipxe/cbc.h>
119
 	assert ( len == AES_BLOCKSIZE );
120
 	assert ( len == AES_BLOCKSIZE );
120
 	if ( aes_ctx->decrypting )
121
 	if ( aes_ctx->decrypting )
121
 		assert ( 0 );
122
 		assert ( 0 );
122
-	aes_call_axtls ( &aes_ctx->axtls_ctx, src, dst, AES_encrypt );
123
+	aes_call_axtls ( &aes_ctx->axtls_ctx, src, dst, axtls_aes_encrypt );
123
 }
124
 }
124
 
125
 
125
 /**
126
 /**
139
 		AES_convert_key ( &aes_ctx->axtls_ctx );
140
 		AES_convert_key ( &aes_ctx->axtls_ctx );
140
 		aes_ctx->decrypting = 1;
141
 		aes_ctx->decrypting = 1;
141
 	}
142
 	}
142
-	aes_call_axtls ( &aes_ctx->axtls_ctx, src, dst, AES_decrypt );
143
+	aes_call_axtls ( &aes_ctx->axtls_ctx, src, dst, axtls_aes_decrypt );
143
 }
144
 }
144
 
145
 
145
 /** Basic AES algorithm */
146
 /** Basic AES algorithm */

+ 10
- 0
src/crypto/x509.c View File

155
 		DBG_HDA ( 0, certificate->data, certificate->len );
155
 		DBG_HDA ( 0, certificate->data, certificate->len );
156
 		return -ENOTSUP;
156
 		return -ENOTSUP;
157
 	}
157
 	}
158
+	if ( modulus.len && ( ! *( ( uint8_t * ) modulus.data ) ) ) {
159
+		/* Skip positive sign byte */
160
+		modulus.data++;
161
+		modulus.len--;
162
+	}
158
 	memcpy ( &exponent, &pubkey, sizeof ( exponent ) );
163
 	memcpy ( &exponent, &pubkey, sizeof ( exponent ) );
159
 	rc = ( asn1_skip ( &exponent, ASN1_INTEGER ), /* modulus */
164
 	rc = ( asn1_skip ( &exponent, ASN1_INTEGER ), /* modulus */
160
 	       asn1_enter ( &exponent, ASN1_INTEGER ) /* publicExponent */ );
165
 	       asn1_enter ( &exponent, ASN1_INTEGER ) /* publicExponent */ );
163
 		DBG_HDA ( 0, certificate->data, certificate->len );
168
 		DBG_HDA ( 0, certificate->data, certificate->len );
164
 		return -ENOTSUP;
169
 		return -ENOTSUP;
165
 	}
170
 	}
171
+	if ( exponent.len && ( ! *( ( uint8_t * ) exponent.data ) ) ) {
172
+		/* Skip positive sign byte */
173
+		exponent.data++;
174
+		exponent.len--;
175
+	}
166
 
176
 
167
 	/* Allocate space and copy out modulus and exponent */
177
 	/* Allocate space and copy out modulus and exponent */
168
 	rsa_pubkey->modulus = malloc ( modulus.len + exponent.len );
178
 	rsa_pubkey->modulus = malloc ( modulus.len + exponent.len );

+ 4
- 0
src/include/ipxe/aes.h View File

21
 /** AES context size */
21
 /** AES context size */
22
 #define AES_CTX_SIZE sizeof ( struct aes_context )
22
 #define AES_CTX_SIZE sizeof ( struct aes_context )
23
 
23
 
24
+/* AXTLS functions */
25
+extern void axtls_aes_encrypt ( const AES_CTX *ctx, uint32_t *data );
26
+extern void axtls_aes_decrypt ( const AES_CTX *ctx, uint32_t *data );
27
+
24
 extern struct cipher_algorithm aes_algorithm;
28
 extern struct cipher_algorithm aes_algorithm;
25
 extern struct cipher_algorithm aes_cbc_algorithm;
29
 extern struct cipher_algorithm aes_cbc_algorithm;
26
 
30
 

+ 1
- 1
src/net/tls.c View File

794
  */
794
  */
795
 static int tls_send_client_key_exchange ( struct tls_session *tls ) {
795
 static int tls_send_client_key_exchange ( struct tls_session *tls ) {
796
 	/* FIXME: Hack alert */
796
 	/* FIXME: Hack alert */
797
-	RSA_CTX *rsa_ctx;
797
+	RSA_CTX *rsa_ctx = NULL;
798
 	RSA_pub_key_new ( &rsa_ctx, tls->rsa.modulus, tls->rsa.modulus_len,
798
 	RSA_pub_key_new ( &rsa_ctx, tls->rsa.modulus, tls->rsa.modulus_len,
799
 			  tls->rsa.exponent, tls->rsa.exponent_len );
799
 			  tls->rsa.exponent, tls->rsa.exponent_len );
800
 	struct {
800
 	struct {

Loading…
Cancel
Save