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,23 +1,33 @@
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 32
  * AES implementation - this is a small code version. There are much faster
23 33
  * versions around but they are much larger in size (i.e. they use large 
@@ -25,6 +35,7 @@ FILE_LICENCE ( GPL2_OR_LATER );
25 35
  */
26 36
 
27 37
 #include <string.h>
38
+#include "os_port.h"
28 39
 #include "crypto.h"
29 40
 
30 41
 /* all commented out in skeleton mode */
@@ -64,10 +75,6 @@ FILE_LICENCE ( GPL2_OR_LATER );
64 75
 			(f8)^=rot2(f4), \
65 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 79
  * AES S-box
73 80
  */
@@ -154,11 +161,15 @@ static const unsigned char Rcon[30]=
154 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 168
 /* Perform doubling in Galois Field GF(2^8) using the irreducible polynomial
158 169
    x^8+x^4+x^3+x+1 */
159 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,7 +258,7 @@ void AES_convert_key(AES_CTX *ctx)
247 258
     k = ctx->ks;
248 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 263
         w= *k;
253 264
         w = inv_mix_col(w,t1,t2,t3,t4);
@@ -255,52 +266,43 @@ void AES_convert_key(AES_CTX *ctx)
255 266
     }
256 267
 }
257 268
 
258
-#if 0
259 269
 /**
260 270
  * Encrypt a byte sequence (with a block size 16) using the AES cipher.
261 271
  */
262 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 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,61 +310,48 @@ void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg, uint8_t *out, int length)
308 310
  */
309 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 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 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 356
     /* To make this code smaller, generate the sbox entries on the fly.
368 357
      * This will have a really heavy effect upon performance.
@@ -375,9 +364,7 @@ void AES_encrypt(const AES_CTX *ctx, uint32_t *data)
375 364
 
376 365
     /* Pre-round key addition */
377 366
     for (row = 0; row < 4; row++)
378
-    {
379 367
         data[row] ^= *(k++);
380
-    }
381 368
 
382 369
     /* Encrypt one block. */
383 370
     for (curr_rnd = 0; curr_rnd < rounds; curr_rnd++)
@@ -395,12 +382,10 @@ void AES_encrypt(const AES_CTX *ctx, uint32_t *data)
395 382
             {
396 383
                 tmp1 = a0 ^ a1 ^ a2 ^ a3;
397 384
                 old_a0 = a0;
398
-
399 385
                 a0 ^= tmp1 ^ AES_xtime(a0 ^ a1);
400 386
                 a1 ^= tmp1 ^ AES_xtime(a1 ^ a2);
401 387
                 a2 ^= tmp1 ^ AES_xtime(a2 ^ a3);
402 388
                 a3 ^= tmp1 ^ AES_xtime(a3 ^ old_a0);
403
-
404 389
             }
405 390
 
406 391
             tmp[row] = ((a0 << 24) | (a1 << 16) | (a2 << 8) | a3);
@@ -409,32 +394,28 @@ void AES_encrypt(const AES_CTX *ctx, uint32_t *data)
409 394
         /* KeyAddition - note that it is vital that this loop is separate from
410 395
            the MixColumn operation, which must be atomic...*/ 
411 396
         for (row = 0; row < 4; row++)
412
-        {
413 397
             data[row] = tmp[row] ^ *(k++);
414
-        }
415 398
     }
416 399
 }
417 400
 
418 401
 /**
419 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 406
     uint32_t tmp[4];
424 407
     uint32_t xt0,xt1,xt2,xt3,xt4,xt5,xt6;
425 408
     uint32_t a0, a1, a2, a3, row;
426 409
     int curr_rnd;
427 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 413
     /* pre-round key addition */
431 414
     for (row=4; row > 0;row--)
432
-    {
433 415
         data[row-1] ^= *(--k);
434
-    }
435 416
 
436 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 420
         /* Perform ByteSub and ShiftRow operations together */
440 421
         for (row = 4; row > 0; row--)
@@ -469,9 +450,7 @@ void AES_decrypt(const AES_CTX *ctx, uint32_t *data)
469 450
         }
470 451
 
471 452
         for (row = 4; row > 0; row--)
472
-        {
473 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,19 +1,31 @@
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,12 +65,17 @@
53 65
 #include <string.h>
54 66
 #include <stdio.h>
55 67
 #include <time.h>
68
+#include "os_port.h"
56 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 76
 static bigint *bi_int_multiply(BI_CTX *ctx, bigint *bi, comp i);
60 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 79
 static bigint *trim(bigint *bi);
63 80
 static void more_comps(bigint *bi, int n);
64 81
 #if defined(CONFIG_BIGINT_KARATSUBA) || defined(CONFIG_BIGINT_BARRETT) || \
@@ -69,8 +86,11 @@ static bigint *comp_left_shift(bigint *biR, int num_shifts);
69 86
 
70 87
 #ifdef CONFIG_BIGINT_CHECK_ON
71 88
 static void check(const bigint *bi);
89
+#else
90
+#define check(A)                /**< disappears in normal production mode */
72 91
 #endif
73 92
 
93
+
74 94
 /**
75 95
  * @brief Start a new bigint context.
76 96
  * @return A bigint context.
@@ -97,8 +117,6 @@ BI_CTX *bi_initialize(void)
97 117
  */
98 118
 void bi_terminate(BI_CTX *ctx)
99 119
 {
100
-    bigint *p, *pn;
101
-
102 120
     bi_depermanent(ctx->bi_radix); 
103 121
     bi_free(ctx, ctx->bi_radix);
104 122
 
@@ -111,6 +129,20 @@ void bi_terminate(BI_CTX *ctx)
111 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 146
     for (p = ctx->free_list; p != NULL; p = pn)
115 147
     {
116 148
         pn = p->next;
@@ -118,7 +150,8 @@ void bi_terminate(BI_CTX *ctx)
118 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,18 +443,18 @@ bigint *bi_divide(BI_CTX *ctx, bigint *u, bigint *v, int is_mod)
410 443
         else
411 444
         {
412 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,6 +506,7 @@ bigint *bi_divide(BI_CTX *ctx, bigint *u, bigint *v, int is_mod)
473 506
 /*
474 507
  * Perform an integer divide on a bigint.
475 508
  */
509
+// mcb30 - mark ctx with __unused to avoid a compilation error
476 510
 static bigint *bi_int_divide(BI_CTX *ctx __unused, bigint *biR, comp denom)
477 511
 {
478 512
     int i = biR->size - 1;
@@ -485,7 +519,7 @@ static bigint *bi_int_divide(BI_CTX *ctx __unused, bigint *biR, comp denom)
485 519
         r = (r<<COMP_BIT_SIZE) + biR->comps[i];
486 520
         biR->comps[i] = (comp)(r / denom);
487 521
         r %= denom;
488
-    } while (--i != 0);
522
+    } while (--i >= 0);
489 523
 
490 524
     return trim(biR);
491 525
 }
@@ -690,10 +724,11 @@ void bi_export(BI_CTX *ctx, bigint *x, uint8_t *data, int size)
690 724
 
691 725
             if (k < 0)
692 726
             {
693
-                break;
727
+                goto buf_done;
694 728
             }
695 729
         }
696 730
     }
731
+buf_done:
697 732
 
698 733
     bi_free(ctx, x);
699 734
 }
@@ -769,11 +804,16 @@ void bi_free_mod(BI_CTX *ctx, int mod_offset)
769 804
 
770 805
 /** 
771 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 817
     int t = bib->size;
778 818
     bigint *biR = alloc(ctx, n + t);
779 819
     comp *sr = biR->comps;
@@ -785,23 +825,33 @@ static bigint *regular_multiply(BI_CTX *ctx, bigint *bia, bigint *bib)
785 825
 
786 826
     /* clear things to start with */
787 827
     memset(biR->comps, 0, ((n+t)*COMP_BYTE_SIZE));
788
-    i = 0;
789 828
 
790 829
     do 
791 830
     {
831
+        long_comp tmp;
792 832
         comp carry = 0;
793
-        comp b = *sb++;
794
-        i_plus_j = i;
833
+        int r_index = i;
795 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 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 852
         } while (++j < n);
803 853
 
804
-        sr[i_plus_j] = carry;
854
+        sr[r_index] = carry;
805 855
     } while (++i < t);
806 856
 
807 857
     bi_free(ctx, bia);
@@ -881,12 +931,12 @@ bigint *bi_multiply(BI_CTX *ctx, bigint *bia, bigint *bib)
881 931
 #ifdef CONFIG_BIGINT_KARATSUBA
882 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 937
     return karatsuba(ctx, bia, bib, 0);
888 938
 #else
889
-    return regular_multiply(ctx, bia, bib);
939
+    return regular_multiply(ctx, bia, bib, 0, 0);
890 940
 #endif
891 941
 }
892 942
 
@@ -898,47 +948,46 @@ static bigint *regular_square(BI_CTX *ctx, bigint *bi)
898 948
 {
899 949
     int t = bi->size;
900 950
     int i = 0, j;
901
-    bigint *biR = alloc(ctx, t*2);
951
+    bigint *biR = alloc(ctx, t*2+1);
902 952
     comp *w = biR->comps;
903 953
     comp *x = bi->comps;
904
-    comp carry;
905
-
954
+    long_comp carry;
906 955
     memset(w, 0, biR->size*COMP_BYTE_SIZE);
907 956
 
908 957
     do
909 958
     {
910 959
         long_comp tmp = w[2*i] + (long_comp)x[i]*x[i];
911
-        comp u = 0;
912 960
         w[2*i] = (comp)tmp;
913
-        carry = (comp)(tmp >> COMP_BIT_SIZE);
961
+        carry = tmp >> COMP_BIT_SIZE;
914 962
 
915 963
         for (j = i+1; j < t; j++)
916 964
         {
965
+            uint8_t c = 0;
917 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 991
     } while (++i < t);
943 992
 
944 993
     bi_free(ctx, bi);
@@ -1092,7 +1141,7 @@ static int find_max_exp_index(bigint *biexp)
1092 1141
         }
1093 1142
 
1094 1143
         shift >>= 1;
1095
-    } while (--i != 0);
1144
+    } while (i-- != 0);
1096 1145
 
1097 1146
     return -1;      /* error - must have been a leading 0 */
1098 1147
 }
@@ -1115,7 +1164,7 @@ static int exp_bit_is_one(bigint *biexp, int offset)
1115 1164
         shift <<= 1;
1116 1165
     }
1117 1166
 
1118
-    return test & shift;
1167
+    return (test & shift) != 0;
1119 1168
 }
1120 1169
 
1121 1170
 #ifdef CONFIG_BIGINT_CHECK_ON
@@ -1210,81 +1259,6 @@ static bigint *comp_mod(bigint *bi, int mod)
1210 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 1263
  * @brief Perform a single Barrett reduction.
1290 1264
  * @param ctx [in]  The bigint session context.
@@ -1310,12 +1284,12 @@ bigint *bi_barrett(BI_CTX *ctx, bigint *bi)
1310 1284
     q1 = comp_right_shift(bi_clone(ctx, bi), k-1);
1311 1285
 
1312 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 1288
     q3 = comp_right_shift(q2, k+1);
1315 1289
     r1 = comp_mod(bi, k+1);
1316 1290
 
1317 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 1293
     r = bi_subtract(ctx, r1, r2, NULL);
1320 1294
 
1321 1295
     /* if (r >= m) r = r - m; */
@@ -1366,6 +1340,7 @@ static void precompute_slide_window(BI_CTX *ctx, int window, bigint *g1)
1366 1340
  * @param ctx [in]  The bigint session context.
1367 1341
  * @param bi  [in]  The bigint on which to perform the mod power operation.
1368 1342
  * @param biexp [in] The bigint exponent.
1343
+ * @return The result of the mod exponentiation operation
1369 1344
  * @see bi_set_mod().
1370 1345
  */
1371 1346
 bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
@@ -1467,6 +1442,7 @@ bigint *bi_mod_power(BI_CTX *ctx, bigint *bi, bigint *biexp)
1467 1442
  * @param bi  [in]  The bigint to perform the exp/mod.
1468 1443
  * @param bim [in]  The temporary modulus.
1469 1444
  * @param biexp [in] The bigint exponent.
1445
+ * @return The result of the mod exponentiation operation
1470 1446
  * @see bi_set_mod().
1471 1447
  */
1472 1448
 bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
@@ -1493,4 +1469,45 @@ bigint *bi_mod_power2(BI_CTX *ctx, bigint *bi, bigint *bim, bigint *biexp)
1493 1469
     return biR;
1494 1470
 }
1495 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,44 +1,43 @@
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
 #ifndef BIGINT_HEADER
22 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 36
 BI_CTX *bi_initialize(void);
39 37
 void bi_terminate(BI_CTX *ctx);
40 38
 void bi_permanent(bigint *bi);
41 39
 void bi_depermanent(bigint *bi);
40
+void bi_clear_cache(BI_CTX *ctx);
42 41
 void bi_free(BI_CTX *ctx, bigint *bi);
43 42
 bigint *bi_copy(bigint *bi);
44 43
 bigint *bi_clone(BI_CTX *ctx, const bigint *bi);
@@ -90,4 +89,11 @@ bigint *bi_square(BI_CTX *ctx, bigint *bi);
90 89
 #define bi_square(A, B)     bi_multiply(A, bi_copy(B), B)
91 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 99
 #endif

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

@@ -1,19 +1,31 @@
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
 #ifndef BIGINT_IMPL_HEADER
@@ -30,20 +42,39 @@
30 42
 #endif
31 43
 
32 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 64
 #ifdef WIN32
34 65
 #define COMP_RADIX          4294967296i64         
35
-#define COMP_BIG_MSB        0x8000000000000000i64 
66
+#define COMP_MAX            0xFFFFFFFFFFFFFFFFui64
36 67
 #else
37 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 70
 #endif
40 71
 #define COMP_BIT_SIZE       32  /**< Number of bits in a component. */
41 72
 #define COMP_BYTE_SIZE      4   /**< Number of bytes in a component. */
42 73
 #define COMP_NUM_NIBBLES    8   /**< Used For diagnostics only. */
43
-
44 74
 typedef uint32_t comp;	        /**< A single precision component. */
45 75
 typedef uint64_t long_comp;     /**< A double precision component. */
46 76
 typedef int64_t slong_comp;     /**< A signed double precision component. */
77
+#endif
47 78
 
48 79
 /**
49 80
  * @struct  _bigint
@@ -97,9 +128,4 @@ typedef struct /**< A big integer "session" context. */
97 128
 
98 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 131
 #endif

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

@@ -0,0 +1,13 @@
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,23 +1,33 @@
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 32
  * @file crypto.h
23 33
  */
@@ -29,20 +39,40 @@ FILE_LICENCE ( GPL2_OR_LATER );
29 39
 extern "C" {
30 40
 #endif
31 41
 
42
+#include "config.h"
43
+#include "bigint_impl.h"
32 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 63
  * AES declarations 
36 64
  **************************************************************************/
37 65
 
38 66
 #define AES_MAXROUNDS			14
67
+#define AES_BLOCKSIZE           16
68
+#define AES_IV_SIZE             16
39 69
 
40 70
 typedef struct aes_key_st 
41 71
 {
42 72
     uint16_t rounds;
43 73
     uint16_t key_size;
44 74
     uint32_t ks[(AES_MAXROUNDS+1)*8];
45
-    uint8_t iv[16];
75
+    uint8_t iv[AES_IV_SIZE];
46 76
 } AES_CTX;
47 77
 
48 78
 typedef enum
@@ -57,8 +87,6 @@ void AES_cbc_encrypt(AES_CTX *ctx, const uint8_t *msg,
57 87
         uint8_t *out, int length);
58 88
 void AES_cbc_decrypt(AES_CTX *ks, const uint8_t *in, uint8_t *out, int length);
59 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 92
  * RC4 declarations 
@@ -66,7 +94,7 @@ void AES_decrypt(const AES_CTX *ctx, uint32_t *data);
66 94
 
67 95
 typedef struct 
68 96
 {
69
-    int x, y, m[256];
97
+    uint8_t x, y, m[256];
70 98
 } RC4_CTX;
71 99
 
72 100
 void RC4_setup(RC4_CTX *s, const uint8_t *key, int length);
@@ -84,22 +112,38 @@ void RC4_crypt(RC4_CTX *s, const uint8_t *msg, uint8_t *data, int length);
84 112
  */
85 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 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 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 148
 #define MD5_SIZE    16
105 149
 
@@ -110,9 +154,9 @@ typedef struct
110 154
   uint8_t buffer[64];       /* input buffer */
111 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 162
  * HMAC declarations 
@@ -122,26 +166,6 @@ void hmac_md5(const uint8_t *msg, int length, const uint8_t *key,
122 166
 void hmac_sha1(const uint8_t *msg, int length, const uint8_t *key, 
123 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 170
  * RSA declarations 
147 171
  **************************************************************************/
@@ -159,7 +183,6 @@ typedef struct
159 183
     bigint *qInv;           /* q^-1 mod p */
160 184
 #endif
161 185
     int num_octets;
162
-    bigint *sig_m;         /* signature modulus */
163 186
     BI_CTX *bi_ctx;
164 187
 } RSA_CTX;
165 188
 
@@ -182,125 +205,22 @@ void RSA_free(RSA_CTX *ctx);
182 205
 int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint8_t *out_data,
183 206
         int is_decryption);
184 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 209
 bigint *RSA_sign_verify(BI_CTX *ctx, const uint8_t *sig, int sig_len,
188 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 212
 int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len, 
191 213
         uint8_t *out_data, int is_signing);
192 214
 void RSA_print(const RSA_CTX *ctx);
193 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 225
 #ifdef __cplusplus
306 226
 }

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

@@ -1,61 +1,54 @@
1
+#ifndef AXTLS_OS_PORT_H
2
+#define AXTLS_OS_PORT_H
3
+
1 4
 /**
2 5
  * @file os_port.h
3 6
  *
4 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 10
 #include <stdint.h>
11
-#include <stddef.h>
12
-#include <stdlib.h>
13
-#include <time.h>
14
-#include <sys/time.h>
15 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 16
 /** We can't actually abort, since we are effectively a kernel... */
22 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 54
 #endif 

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

@@ -1,19 +1,31 @@
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,12 +37,9 @@
25 37
 #include <string.h>
26 38
 #include <time.h>
27 39
 #include <stdlib.h>
40
+#include "os_port.h"
28 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 43
 void RSA_priv_key_new(RSA_CTX **ctx, 
35 44
         const uint8_t *modulus, int mod_len,
36 45
         const uint8_t *pub_exp, int pub_len,
@@ -71,11 +80,16 @@ void RSA_pub_key_new(RSA_CTX **ctx,
71 80
         const uint8_t *pub_exp, int pub_len)
72 81
 {
73 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 89
     *ctx = (RSA_CTX *)calloc(1, sizeof(RSA_CTX));
76 90
     rsa_ctx = *ctx;
77 91
     rsa_ctx->bi_ctx = bi_ctx;
78
-    rsa_ctx->num_octets = (mod_len & 0xFFF0);
92
+    rsa_ctx->num_octets = mod_len;
79 93
     rsa_ctx->m = bi_import(bi_ctx, modulus, mod_len);
80 94
     bi_set_mod(bi_ctx, rsa_ctx->m, BIGINT_M_OFFSET);
81 95
     rsa_ctx->e = bi_import(bi_ctx, pub_exp, pub_len);
@@ -129,10 +143,10 @@ void RSA_free(RSA_CTX *rsa_ctx)
129 143
 int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data, 
130 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 147
     int i, size;
135 148
     bigint *decrypted_bi, *dat_bi;
149
+    uint8_t *block = (uint8_t *)alloca(byte_size);
136 150
 
137 151
     memset(out_data, 0, byte_size); /* initialise */
138 152
 
@@ -146,7 +160,6 @@ int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data,
146 160
 #endif
147 161
 
148 162
     /* convert to a normal block */
149
-    block = (uint8_t *)malloc(byte_size);
150 163
     bi_export(ctx->bi_ctx, decrypted_bi, block, byte_size);
151 164
 
152 165
     i = 10; /* start at the first possible non-padded byte */
@@ -170,7 +183,6 @@ int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data,
170 183
     if (size > 0)
171 184
         memcpy(out_data, &block[i], size);
172 185
     
173
-    free(block);
174 186
     return size ? size : -1;
175 187
 }
176 188
 
@@ -180,7 +192,7 @@ int RSA_decrypt(const RSA_CTX *ctx, const uint8_t *in_data,
180 192
 bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg)
181 193
 {
182 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 196
 #else
185 197
     BI_CTX *ctx = c->bi_ctx;
186 198
     ctx->mod_offset = BIGINT_M_OFFSET;
@@ -188,39 +200,6 @@ bigint *RSA_private(const RSA_CTX *c, bigint *bi_msg)
188 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 203
 #ifdef CONFIG_SSL_FULL_MODE
225 204
 /**
226 205
  * Used for diagnostics.
@@ -238,7 +217,7 @@ void RSA_print(const RSA_CTX *rsa_ctx)
238 217
 }
239 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 222
  * Performs c = m^e mod n
244 223
  */
@@ -279,54 +258,12 @@ int RSA_encrypt(const RSA_CTX *ctx, const uint8_t *in_data, uint16_t in_len,
279 258
     /* now encrypt it */
280 259
     dat_bi = bi_import(ctx->bi_ctx, out_data, byte_size);
281 260
     encrypt_bi = is_signing ? RSA_private(ctx, dat_bi) : 
282
-        RSA_public(ctx, dat_bi);
261
+                              RSA_public(ctx, dat_bi);
283 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 269
 #endif  /* CONFIG_SSL_CERT_VERIFICATION */

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

@@ -20,6 +20,7 @@ FILE_LICENCE ( GPL2_OR_LATER );
20 20
 
21 21
 #include <string.h>
22 22
 #include <errno.h>
23
+#include <assert.h>
23 24
 #include <byteswap.h>
24 25
 #include <ipxe/crypto.h>
25 26
 #include <ipxe/cbc.h>
@@ -119,7 +120,7 @@ static void aes_encrypt ( void *ctx, const void *src, void *dst,
119 120
 	assert ( len == AES_BLOCKSIZE );
120 121
 	if ( aes_ctx->decrypting )
121 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,7 +140,7 @@ static void aes_decrypt ( void *ctx, const void *src, void *dst,
139 140
 		AES_convert_key ( &aes_ctx->axtls_ctx );
140 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 146
 /** Basic AES algorithm */

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

@@ -155,6 +155,11 @@ int x509_rsa_public_key ( const struct asn1_cursor *certificate,
155 155
 		DBG_HDA ( 0, certificate->data, certificate->len );
156 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 163
 	memcpy ( &exponent, &pubkey, sizeof ( exponent ) );
159 164
 	rc = ( asn1_skip ( &exponent, ASN1_INTEGER ), /* modulus */
160 165
 	       asn1_enter ( &exponent, ASN1_INTEGER ) /* publicExponent */ );
@@ -163,6 +168,11 @@ int x509_rsa_public_key ( const struct asn1_cursor *certificate,
163 168
 		DBG_HDA ( 0, certificate->data, certificate->len );
164 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 177
 	/* Allocate space and copy out modulus and exponent */
168 178
 	rsa_pubkey->modulus = malloc ( modulus.len + exponent.len );

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

@@ -21,6 +21,10 @@ struct aes_context {
21 21
 /** AES context size */
22 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 28
 extern struct cipher_algorithm aes_algorithm;
25 29
 extern struct cipher_algorithm aes_cbc_algorithm;
26 30
 

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

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

Loading…
Cancel
Save