security/nss/lib/freebl/gcm.c

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 /* This Source Code Form is subject to the terms of the Mozilla Public
     2  * License, v. 2.0. If a copy of the MPL was not distributed with this
     3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     5 #ifdef FREEBL_NO_DEPEND
     6 #include "stubs.h"
     7 #endif
     8 #include "blapii.h"
     9 #include "blapit.h"
    10 #include "gcm.h"
    11 #include "ctr.h"
    12 #include "secerr.h"
    13 #include "prtypes.h"
    14 #include "pkcs11t.h"
    16 #include <limits.h>
    18 /**************************************************************************
    19  *          First implement the Galois hash function of GCM (gcmHash)     *
    20  **************************************************************************/
    21 #define GCM_HASH_LEN_LEN 8 /* gcm hash defines lengths to be 64 bits */
    23 typedef struct gcmHashContextStr gcmHashContext;
    25 static SECStatus gcmHash_InitContext(gcmHashContext *hash,
    26 				     const unsigned char *H,
    27 				     unsigned int blocksize);
    28 static void gcmHash_DestroyContext(gcmHashContext *ghash, PRBool freeit);
    29 static SECStatus gcmHash_Update(gcmHashContext *ghash,
    30 				const unsigned char *buf, unsigned int len,
    31 				unsigned int blocksize);
    32 static SECStatus gcmHash_Sync(gcmHashContext *ghash, unsigned int blocksize);
    33 static SECStatus gcmHash_Final(gcmHashContext *gcm, unsigned char *outbuf,
    34 			       unsigned int *outlen, unsigned int maxout,
    35 			       unsigned int blocksize);
    36 static SECStatus gcmHash_Reset(gcmHashContext *ghash,
    37 			       const unsigned char *inbuf,
    38 			       unsigned int inbufLen, unsigned int blocksize);
    40 /* compile time defines to select how the GF2 multiply is calculated.
    41  * There are currently 2 algorithms implemented here: MPI and ALGORITHM_1.
    42  *
    43  * MPI uses the GF2m implemented in mpi to support GF2 ECC.
    44  * ALGORITHM_1 is the Algorithm 1 in both NIST SP 800-38D and
    45  * "The Galois/Counter Mode of Operation (GCM)", McGrew & Viega.
    46  */
    47 #if !defined(GCM_USE_ALGORITHM_1) && !defined(GCM_USE_MPI)
    48 #define GCM_USE_MPI 1 /* MPI is about 5x faster with the
    49 		       * same or less complexity. It's possible to use
    50 		       * tables to speed things up even more */
    51 #endif
    53 /* GCM defines the bit string to be LSB first, which is exactly
    54  * opposite everyone else, including hardware. build array
    55  * to reverse everything. */
    56 static const unsigned char gcm_byte_rev[256] = {
    57     0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
    58     0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
    59     0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
    60     0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
    61     0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
    62     0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
    63     0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
    64     0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
    65     0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
    66     0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
    67     0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
    68     0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
    69     0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
    70     0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
    71     0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
    72     0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
    73     0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
    74     0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
    75     0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
    76     0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
    77     0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
    78     0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
    79     0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
    80     0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
    81     0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
    82     0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
    83     0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
    84     0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
    85     0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
    86     0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
    87     0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
    88     0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff
    89 };
    92 #ifdef GCM_TRACE
    93 #include <stdio.h>
    95 #define GCM_TRACE_X(ghash,label) { \
    96 	unsigned char _X[MAX_BLOCK_SIZE]; int i; \
    97 	gcm_getX(ghash, _X, blocksize); \
    98 	printf(label,(ghash)->m); \
    99 	for (i=0; i < blocksize; i++) printf("%02x",_X[i]); \
   100 	printf("\n"); }
   101 #define GCM_TRACE_BLOCK(label,buf,blocksize) {\
   102 	printf(label); \
   103 	for (i=0; i < blocksize; i++) printf("%02x",buf[i]); \
   104 	printf("\n"); }
   105 #else
   106 #define GCM_TRACE_X(ghash,label)
   107 #define GCM_TRACE_BLOCK(label,buf,blocksize)
   108 #endif
   110 #ifdef GCM_USE_MPI
   112 #ifdef GCM_USE_ALGORITHM_1
   113 #error "Only define one of GCM_USE_MPI, GCM_USE_ALGORITHM_1"
   114 #endif
   115 /* use the MPI functions to calculate Xn = (Xn-1^C_i)*H mod poly */
   116 #include "mpi.h"
   117 #include "secmpi.h"
   118 #include "mplogic.h"
   119 #include "mp_gf2m.h"
   121 /* state needed to handle GCM Hash function */
   122 struct gcmHashContextStr {
   123      mp_int H;
   124      mp_int X;
   125      mp_int C_i;
   126      const unsigned int *poly;
   127      unsigned char buffer[MAX_BLOCK_SIZE];
   128      unsigned int bufLen;
   129      int m; /* XXX what is m? */
   130      unsigned char counterBuf[2*GCM_HASH_LEN_LEN];
   131      PRUint64 cLen;
   132 };
   134 /* f = x^128 + x^7 + x^2 + x + 1 */
   135 static const unsigned int poly_128[] = { 128, 7, 2, 1, 0 };
   137 /* sigh, GCM defines the bit strings exactly backwards from everything else */
   138 static void
   139 gcm_reverse(unsigned char *target, const unsigned char *src,
   140 							unsigned int blocksize)
   141 {
   142     unsigned int i;
   143     for (i=0; i < blocksize; i++) {
   144 	target[blocksize-i-1] = gcm_byte_rev[src[i]];
   145     }
   146 }
   148 /* Initialize a gcmHashContext */
   149 static SECStatus
   150 gcmHash_InitContext(gcmHashContext *ghash, const unsigned char *H,
   151 		    unsigned int blocksize)
   152 {
   153     mp_err err = MP_OKAY;
   154     unsigned char H_rev[MAX_BLOCK_SIZE];
   156     MP_DIGITS(&ghash->H) = 0;
   157     MP_DIGITS(&ghash->X) = 0;
   158     MP_DIGITS(&ghash->C_i) = 0;
   159     CHECK_MPI_OK( mp_init(&ghash->H) );
   160     CHECK_MPI_OK( mp_init(&ghash->X) );
   161     CHECK_MPI_OK( mp_init(&ghash->C_i) );
   163     mp_zero(&ghash->X);
   164     gcm_reverse(H_rev, H, blocksize);
   165     CHECK_MPI_OK( mp_read_unsigned_octets(&ghash->H, H_rev, blocksize) );
   167     /* set the irreducible polynomial. Each blocksize has its own polynomial.
   168      * for now only blocksize 16 (=128 bits) is defined */
   169     switch (blocksize) {
   170     case 16: /* 128 bits */
   171 	ghash->poly = poly_128;
   172 	break;
   173     default:
   174 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   175 	goto cleanup;
   176     }
   177     ghash->cLen = 0;
   178     ghash->bufLen = 0;
   179     ghash->m = 0;
   180     PORT_Memset(ghash->counterBuf, 0, sizeof(ghash->counterBuf));
   181     return SECSuccess;
   182 cleanup:
   183     gcmHash_DestroyContext(ghash, PR_FALSE);
   184     return SECFailure;
   185 }
   187 /* Destroy a HashContext (Note we zero the digits so this function
   188  * is idempotent if called with freeit == PR_FALSE */
   189 static void
   190 gcmHash_DestroyContext(gcmHashContext *ghash, PRBool freeit)
   191 {
   192     mp_clear(&ghash->H);
   193     mp_clear(&ghash->X);
   194     mp_clear(&ghash->C_i);
   195     MP_DIGITS(&ghash->H) = 0;
   196     MP_DIGITS(&ghash->X) = 0;
   197     MP_DIGITS(&ghash->C_i) = 0;
   198     if (freeit) {
   199 	PORT_Free(ghash);
   200     }
   201 }
   203 static SECStatus
   204 gcm_getX(gcmHashContext *ghash, unsigned char *T, unsigned int blocksize)
   205 {
   206     int len;
   207     mp_err err;
   208     unsigned char tmp_buf[MAX_BLOCK_SIZE];
   209     unsigned char *X;
   211     len = mp_unsigned_octet_size(&ghash->X);
   212     if (len <= 0) {
   213 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   214 	return SECFailure;
   215     }
   216     X = tmp_buf;
   217     PORT_Assert((unsigned int)len <= blocksize);
   218     if ((unsigned int)len > blocksize) {
   219 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   220 	return SECFailure;
   221     }
   222     /* zero pad the result */
   223     if (len != blocksize) {
   224 	PORT_Memset(X,0,blocksize-len);
   225 	X += blocksize-len;
   226     }
   228     err = mp_to_unsigned_octets(&ghash->X, X, len);
   229     if (err < 0) {
   230 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   231 	return SECFailure;
   232     }
   233     gcm_reverse(T, tmp_buf, blocksize);
   234     return SECSuccess;
   235 }
   237 static SECStatus
   238 gcm_HashMult(gcmHashContext *ghash, const unsigned char *buf,
   239 		unsigned int count, unsigned int blocksize)
   240 {
   241     SECStatus rv = SECFailure;
   242     mp_err err = MP_OKAY;
   243     unsigned char tmp_buf[MAX_BLOCK_SIZE];
   244     unsigned int i;
   246     for (i=0; i < count; i++, buf += blocksize) {
   247 	ghash->m++;
   248 	gcm_reverse(tmp_buf, buf, blocksize);
   249 	CHECK_MPI_OK(mp_read_unsigned_octets(&ghash->C_i, tmp_buf, blocksize));
   250 	CHECK_MPI_OK(mp_badd(&ghash->X, &ghash->C_i, &ghash->C_i));
   251 	/*
   252 	 * Looking to speed up GCM, this the the place to do it.
   253 	 * There are two areas that can be exploited to speed up this code.
   254 	 *
   255 	 * 1) H is a constant in this multiply. We can precompute H * (0 - 255)
   256 	 * at init time and this becomes an blockize xors of our table lookup.
   257 	 *
   258 	 * 2) poly is a constant for each blocksize. We can calculate the
   259 	 * modulo reduction by a series of adds and shifts.
   260 	 *
   261 	 * For now we are after functionality, so we will go ahead and use
   262 	 * the builtin bmulmod from mpi
   263 	 */
   264         CHECK_MPI_OK(mp_bmulmod(&ghash->C_i, &ghash->H,
   265 					ghash->poly, &ghash->X));
   266 	GCM_TRACE_X(ghash, "X%d = ")
   267     }
   268     rv = SECSuccess;
   269 cleanup:
   270     if (rv != SECSuccess) {
   271 	MP_TO_SEC_ERROR(err);
   272     }
   273     return rv;
   274 }
   276 static void
   277 gcm_zeroX(gcmHashContext *ghash)
   278 {
   279     mp_zero(&ghash->X);
   280     ghash->m = 0;
   281 }
   283 #endif
   285 #ifdef GCM_USE_ALGORITHM_1
   286 /* use algorithm 1 of McGrew & Viega "The Galois/Counter Mode of Operation" */
   288 #define GCM_ARRAY_SIZE (MAX_BLOCK_SIZE/sizeof(unsigned long))
   290 struct gcmHashContextStr {
   291      unsigned long H[GCM_ARRAY_SIZE];
   292      unsigned long X[GCM_ARRAY_SIZE];
   293      unsigned long R;
   294      unsigned char buffer[MAX_BLOCK_SIZE];
   295      unsigned int bufLen;
   296      int m;
   297      unsigned char counterBuf[2*GCM_HASH_LEN_LEN];
   298      PRUint64 cLen;
   299 };
   301 static void
   302 gcm_bytes_to_longs(unsigned long *l, const unsigned char *c, unsigned int len)
   303 {
   304     int i,j;
   305     int array_size = len/sizeof(unsigned long);
   307     PORT_Assert(len % sizeof(unsigned long) == 0);
   308     for (i=0; i < array_size; i++) {
   309 	unsigned long tmp = 0;
   310 	int byte_offset = i * sizeof(unsigned long);
   311 	for (j=sizeof(unsigned long)-1; j >= 0; j--) {
   312 	    tmp = (tmp << PR_BITS_PER_BYTE) | gcm_byte_rev[c[byte_offset+j]];
   313 	}
   314 	l[i] = tmp;
   315     }
   316 }
   318 static void
   319 gcm_longs_to_bytes(const unsigned long *l, unsigned char *c, unsigned int len)
   320 {
   321     int i,j;
   322     int array_size = len/sizeof(unsigned long);
   324     PORT_Assert(len % sizeof(unsigned long) == 0);
   325     for (i=0; i < array_size; i++) {
   326 	unsigned long tmp = l[i];
   327 	int byte_offset = i * sizeof(unsigned long);
   328 	for (j=0; j < sizeof(unsigned long); j++) {
   329 	    c[byte_offset+j] = gcm_byte_rev[tmp & 0xff];
   330 	    tmp = (tmp >> PR_BITS_PER_BYTE);
   331 	}
   332     }
   333 }
   336 /* Initialize a gcmHashContext */
   337 static SECStatus
   338 gcmHash_InitContext(gcmHashContext *ghash, const unsigned char *H,
   339 		    unsigned int blocksize)
   340 {
   341     PORT_Memset(ghash->X, 0, sizeof(ghash->X));
   342     PORT_Memset(ghash->H, 0, sizeof(ghash->H));
   343     gcm_bytes_to_longs(ghash->H, H, blocksize);
   345     /* set the irreducible polynomial. Each blocksize has its own polynommial
   346      * for now only blocksize 16 (=128 bits) is defined */
   347     switch (blocksize) {
   348     case 16: /* 128 bits */
   349 	ghash->R = (unsigned long) 0x87; /* x^7 + x^2 + x +1 */
   350 	break;
   351     default:
   352 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   353 	goto cleanup;
   354     }
   355     ghash->cLen = 0;
   356     ghash->bufLen = 0;
   357     ghash->m = 0;
   358     PORT_Memset(ghash->counterBuf, 0, sizeof(ghash->counterBuf));
   359     return SECSuccess;
   360 cleanup:
   361     return SECFailure;
   362 }
   364 /* Destroy a HashContext (Note we zero the digits so this function
   365  * is idempotent if called with freeit == PR_FALSE */
   366 static void
   367 gcmHash_DestroyContext(gcmHashContext *ghash, PRBool freeit)
   368 {
   369     if (freeit) {
   370 	PORT_Free(ghash);
   371     }
   372 }
   374 static unsigned long
   375 gcm_shift_one(unsigned long *t, unsigned int count)
   376 {
   377     unsigned long carry = 0;
   378     unsigned long nextcarry = 0;
   379     unsigned int i;
   380     for (i=0; i < count; i++) {
   381 	nextcarry = t[i] >> ((sizeof(unsigned long)*PR_BITS_PER_BYTE)-1);
   382 	t[i] = (t[i] << 1) | carry;
   383 	carry = nextcarry;
   384     }
   385     return carry;
   386 }
   388 static SECStatus
   389 gcm_getX(gcmHashContext *ghash, unsigned char *T, unsigned int blocksize)
   390 {
   391     gcm_longs_to_bytes(ghash->X, T, blocksize);
   392     return SECSuccess;
   393 }
   395 #define GCM_XOR(t, s, len) \
   396 	for (l=0; l < len; l++) t[l] ^= s[l]
   398 static SECStatus
   399 gcm_HashMult(gcmHashContext *ghash, const unsigned char *buf,
   400 		unsigned int count, unsigned int blocksize)
   401 {
   402     unsigned long C_i[GCM_ARRAY_SIZE];
   403     unsigned int arraysize = blocksize/sizeof(unsigned long);
   404     unsigned int i, j, k, l;
   406     for (i=0; i < count; i++, buf += blocksize) {
   407 	ghash->m++;
   408 	gcm_bytes_to_longs(C_i, buf, blocksize);
   409 	GCM_XOR(C_i, ghash->X, arraysize);
   410 	/* multiply X = C_i * H */
   411 	PORT_Memset(ghash->X, 0, sizeof(ghash->X));
   412 	for (j=0; j < arraysize; j++) {
   413 	    unsigned long H = ghash->H[j];
   414 	    for (k=0; k < sizeof(unsigned long)*PR_BITS_PER_BYTE; k++) {
   415 		if (H & 1) {
   416 		    GCM_XOR(ghash->X, C_i, arraysize);
   417 		}
   418 		if (gcm_shift_one(C_i, arraysize)) {
   419 		    C_i[0] = C_i[0] ^ ghash->R;
   420 		}
   421 		H = H >> 1;
   422 	    }
   423 	}
   424 	GCM_TRACE_X(ghash, "X%d = ")
   425     }
   426     return SECSuccess;
   427 }
   430 static void
   431 gcm_zeroX(gcmHashContext *ghash)
   432 {
   433     PORT_Memset(ghash->X, 0, sizeof(ghash->X));
   434     ghash->m = 0;
   435 }
   436 #endif
   438 /*
   439  * implement GCM GHASH using the freebl GHASH function. The gcm_HashMult
   440  * function always takes blocksize lengths of data. gcmHash_Update will
   441  * format the data properly.
   442  */
   443 static SECStatus
   444 gcmHash_Update(gcmHashContext *ghash, const unsigned char *buf,
   445 	       unsigned int len, unsigned int blocksize)
   446 {
   447     unsigned int blocks;
   448     SECStatus rv;
   450     ghash->cLen += (len*PR_BITS_PER_BYTE);
   452     /* first deal with the current buffer of data. Try to fill it out so
   453      * we can hash it */
   454     if (ghash->bufLen) {
   455 	unsigned int needed = PR_MIN(len, blocksize - ghash->bufLen);
   456 	if (needed != 0) {
   457 	    PORT_Memcpy(ghash->buffer+ghash->bufLen, buf, needed);
   458 	}
   459 	buf += needed;
   460 	len -= needed;
   461 	ghash->bufLen += needed;
   462 	if (len == 0) {
   463 	    /* didn't add enough to hash the data, nothing more do do */
   464 	    return SECSuccess;
   465 	}
   466 	PORT_Assert(ghash->bufLen == blocksize);
   467 	/* hash the buffer and clear it */
   468 	rv = gcm_HashMult(ghash, ghash->buffer, 1, blocksize);
   469 	PORT_Memset(ghash->buffer, 0, blocksize);
   470 	ghash->bufLen = 0;
   471 	if (rv != SECSuccess) {
   472 	    return SECFailure;
   473 	}
   474     }
   475     /* now hash any full blocks remaining in the data stream */
   476     blocks = len/blocksize;
   477     if (blocks) {
   478 	rv = gcm_HashMult(ghash, buf, blocks, blocksize);
   479 	if (rv != SECSuccess) {
   480 	    return SECFailure;
   481 	}
   482 	buf += blocks*blocksize;
   483 	len -= blocks*blocksize;
   484     }
   486     /* save any remainder in the buffer to be hashed with the next call */
   487     if (len != 0) {
   488 	PORT_Memcpy(ghash->buffer, buf, len);
   489 	ghash->bufLen = len;
   490     }
   491     return SECSuccess;
   492 }
   494 /*
   495  * write out any partial blocks zero padded through the GHASH engine,
   496  * save the lengths for the final completion of the hash
   497  */
   498 static SECStatus
   499 gcmHash_Sync(gcmHashContext *ghash, unsigned int blocksize)
   500 {
   501     int i;
   502     SECStatus rv;
   504     /* copy the previous counter to the upper block */
   505     PORT_Memcpy(ghash->counterBuf, &ghash->counterBuf[GCM_HASH_LEN_LEN],
   506 							GCM_HASH_LEN_LEN);
   507     /* copy the current counter in the lower block */
   508     for (i=0; i < GCM_HASH_LEN_LEN; i++) {
   509 	ghash->counterBuf[GCM_HASH_LEN_LEN+i] =
   510 	    (ghash->cLen >> ((GCM_HASH_LEN_LEN-1-i)*PR_BITS_PER_BYTE)) & 0xff;
   511     }
   512     ghash->cLen = 0;
   514     /* now zero fill the buffer and hash the last block */
   515     if (ghash->bufLen) {
   516 	PORT_Memset(ghash->buffer+ghash->bufLen, 0, blocksize - ghash->bufLen);
   517 	rv = gcm_HashMult(ghash, ghash->buffer, 1, blocksize);
   518 	PORT_Memset(ghash->buffer, 0, blocksize);
   519 	ghash->bufLen = 0;
   520 	if (rv != SECSuccess) {
   521 	    return SECFailure;
   522 	}
   523     }
   524     return SECSuccess;
   525 }
   527 /*
   528  * This does the final sync, hashes the lengths, then returns
   529  * "T", the hashed output.
   530  */
   531 static SECStatus
   532 gcmHash_Final(gcmHashContext *ghash, unsigned char *outbuf,
   533 		unsigned int *outlen, unsigned int maxout,
   534 		unsigned int blocksize)
   535 {
   536     unsigned char T[MAX_BLOCK_SIZE];
   537     SECStatus rv;
   539     rv = gcmHash_Sync(ghash, blocksize);
   540     if (rv != SECSuccess) {
   541 	return SECFailure;
   542     }
   544     rv = gcm_HashMult(ghash, ghash->counterBuf, (GCM_HASH_LEN_LEN*2)/blocksize,
   545 								blocksize);
   546     if (rv != SECSuccess) {
   547 	return SECFailure;
   548     }
   550     GCM_TRACE_X(ghash, "GHASH(H,A,C) = ")
   552     rv = gcm_getX(ghash, T, blocksize);
   553     if (rv != SECSuccess) {
   554 	return SECFailure;
   555     }
   557     if (maxout > blocksize) maxout = blocksize;
   558     PORT_Memcpy(outbuf, T, maxout);
   559     *outlen = maxout;
   560     return SECSuccess;
   561 }
   563 SECStatus
   564 gcmHash_Reset(gcmHashContext *ghash, const unsigned char *AAD,
   565 	      unsigned int AADLen, unsigned int blocksize)
   566 {
   567     SECStatus rv;
   569     ghash->cLen = 0;
   570     PORT_Memset(ghash->counterBuf, 0, GCM_HASH_LEN_LEN*2);
   571     ghash->bufLen = 0;
   572     gcm_zeroX(ghash);
   574     /* now kick things off by hashing the Additional Authenticated Data */
   575     if (AADLen != 0) {
   576 	rv = gcmHash_Update(ghash, AAD, AADLen, blocksize);
   577 	if (rv != SECSuccess) {
   578 	    return SECFailure;
   579 	}
   580 	rv = gcmHash_Sync(ghash, blocksize);
   581 	if (rv != SECSuccess) {
   582 	    return SECFailure;
   583 	}
   584     }
   585     return SECSuccess;
   586 }
   588 /**************************************************************************
   589  *           Now implement the GCM using gcmHash and CTR                  *
   590  **************************************************************************/
   592 /* state to handle the full GCM operation (hash and counter) */
   593 struct GCMContextStr {
   594     gcmHashContext ghash_context;
   595     CTRContext ctr_context;
   596     unsigned long tagBits;
   597     unsigned char tagKey[MAX_BLOCK_SIZE];
   598 };
   600 GCMContext *
   601 GCM_CreateContext(void *context, freeblCipherFunc cipher,
   602 		  const unsigned char *params, unsigned int blocksize)
   603 {
   604     GCMContext *gcm = NULL;
   605     gcmHashContext *ghash;
   606     unsigned char H[MAX_BLOCK_SIZE];
   607     unsigned int tmp;
   608     PRBool freeCtr = PR_FALSE;
   609     PRBool freeHash = PR_FALSE;
   610     const CK_GCM_PARAMS *gcmParams = (const CK_GCM_PARAMS *)params;
   611     CK_AES_CTR_PARAMS ctrParams;
   612     SECStatus rv;
   614     if (blocksize > MAX_BLOCK_SIZE || blocksize > sizeof(ctrParams.cb)) {
   615 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   616 	return NULL;
   617     }
   618     gcm = PORT_ZNew(GCMContext);
   619     if (gcm == NULL) {
   620 	return NULL;
   621     }
   622     /* first fill in the ghash context */
   623     ghash = &gcm->ghash_context;
   624     PORT_Memset(H, 0, blocksize);
   625     rv = (*cipher)(context, H, &tmp, blocksize, H, blocksize, blocksize);
   626     if (rv != SECSuccess) {
   627 	goto loser;
   628     }
   629     rv = gcmHash_InitContext(ghash, H, blocksize);
   630     if (rv != SECSuccess) {
   631 	goto loser;
   632     }
   633     freeHash = PR_TRUE;
   635     /* fill in the Counter context */
   636     ctrParams.ulCounterBits = 32;
   637     PORT_Memset(ctrParams.cb, 0, sizeof(ctrParams.cb));
   638     if ((blocksize == 16) && (gcmParams->ulIvLen == 12)) {
   639 	PORT_Memcpy(ctrParams.cb, gcmParams->pIv, gcmParams->ulIvLen);
   640 	ctrParams.cb[blocksize-1] = 1;
   641     } else {
   642 	rv = gcmHash_Update(ghash, gcmParams->pIv, gcmParams->ulIvLen,
   643 			    blocksize);
   644 	if (rv != SECSuccess) {
   645 	    goto loser;
   646 	}
   647 	rv = gcmHash_Final(ghash, ctrParams.cb, &tmp, blocksize, blocksize);
   648 	if (rv != SECSuccess) {
   649 	    goto loser;
   650 	}
   651     }
   652     rv = CTR_InitContext(&gcm->ctr_context, context, cipher,
   653 				(unsigned char *)&ctrParams, blocksize);
   654     if (rv != SECSuccess) {
   655 	goto loser;
   656     }
   657     freeCtr = PR_TRUE;
   659     /* fill in the gcm structure */
   660     gcm->tagBits = gcmParams->ulTagBits; /* save for final step */
   661     /* calculate the final tag key. NOTE: gcm->tagKey is zero to start with.
   662      * if this assumption changes, we would need to explicitly clear it here */
   663     rv = CTR_Update(&gcm->ctr_context, gcm->tagKey, &tmp, blocksize,
   664 		    gcm->tagKey, blocksize, blocksize);
   665     if (rv != SECSuccess) {
   666 	goto loser;
   667     }
   669     /* finally mix in the AAD data */
   670     rv = gcmHash_Reset(ghash, gcmParams->pAAD, gcmParams->ulAADLen, blocksize);
   671     if (rv != SECSuccess) {
   672 	goto loser;
   673     }
   675     return gcm;
   677 loser:
   678     if (freeCtr) {
   679 	CTR_DestroyContext(&gcm->ctr_context, PR_FALSE);
   680     }
   681     if (freeHash) {
   682 	gcmHash_DestroyContext(&gcm->ghash_context, PR_FALSE);
   683     }
   684     if (gcm) {
   685 	PORT_Free(gcm);
   686     }
   687     return NULL;
   688 }
   690 void
   691 GCM_DestroyContext(GCMContext *gcm, PRBool freeit)
   692 {
   693     /* these two are statically allocated and will be freed when we free
   694      * gcm. call their destroy functions to free up any locally
   695      * allocated data (like mp_int's) */
   696     CTR_DestroyContext(&gcm->ctr_context, PR_FALSE);
   697     gcmHash_DestroyContext(&gcm->ghash_context, PR_FALSE);
   698     if (freeit) {
   699 	PORT_Free(gcm);
   700     }
   701 }
   703 static SECStatus
   704 gcm_GetTag(GCMContext *gcm, unsigned char *outbuf,
   705 	unsigned int *outlen, unsigned int maxout,
   706 	unsigned int blocksize)
   707 {
   708     unsigned int tagBytes;
   709     unsigned int extra;
   710     unsigned int i;
   711     SECStatus rv;
   713     tagBytes = (gcm->tagBits + (PR_BITS_PER_BYTE-1)) / PR_BITS_PER_BYTE;
   714     extra = tagBytes*PR_BITS_PER_BYTE - gcm->tagBits;
   716     if (outbuf == NULL) {
   717 	*outlen = tagBytes;
   718 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   719 	return SECFailure;
   720     }
   722     if (maxout < tagBytes) {
   723 	*outlen = tagBytes;
   724 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   725 	return SECFailure;
   726     }
   727     maxout = tagBytes;
   728     rv = gcmHash_Final(&gcm->ghash_context, outbuf, outlen, maxout, blocksize);
   729     if (rv != SECSuccess) {
   730 	return SECFailure;
   731     }
   733     GCM_TRACE_BLOCK("GHASH=", outbuf, blocksize);
   734     GCM_TRACE_BLOCK("Y0=", gcm->tagKey, blocksize);
   735     for (i=0; i < *outlen; i++) {
   736 	outbuf[i] ^= gcm->tagKey[i];
   737     }
   738     GCM_TRACE_BLOCK("Y0=", gcm->tagKey, blocksize);
   739     GCM_TRACE_BLOCK("T=", outbuf, blocksize);
   740     /* mask off any extra bits we got */
   741     if (extra) {
   742 	outbuf[tagBytes-1] &= ~((1 << extra)-1);
   743     }
   744     return SECSuccess;
   745 }
   748 /*
   749  * See The Galois/Counter Mode of Operation, McGrew and Viega.
   750  *  GCM is basically counter mode with a specific initialization and
   751  *  built in macing operation.
   752  */
   753 SECStatus
   754 GCM_EncryptUpdate(GCMContext *gcm, unsigned char *outbuf,
   755 		unsigned int *outlen, unsigned int maxout,
   756 		const unsigned char *inbuf, unsigned int inlen,
   757 		unsigned int blocksize)
   758 {
   759     SECStatus rv;
   760     unsigned int tagBytes;
   761     unsigned int len;
   763     tagBytes = (gcm->tagBits + (PR_BITS_PER_BYTE-1)) / PR_BITS_PER_BYTE;
   764     if (UINT_MAX - inlen < tagBytes) {
   765 	PORT_SetError(SEC_ERROR_INPUT_LEN);
   766 	return SECFailure;
   767     }
   768     if (maxout < inlen + tagBytes) {
   769 	*outlen = inlen + tagBytes;
   770 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   771 	return SECFailure;
   772     }
   774     rv = CTR_Update(&gcm->ctr_context, outbuf, outlen, maxout,
   775 			inbuf, inlen, blocksize);
   776     if (rv != SECSuccess) {
   777 	return SECFailure;
   778     }
   779     rv = gcmHash_Update(&gcm->ghash_context, outbuf, *outlen, blocksize);
   780     if (rv != SECSuccess) {
   781 	PORT_Memset(outbuf, 0, *outlen); /* clear the output buffer */
   782 	*outlen = 0;
   783 	return SECFailure;
   784     }
   785     rv = gcm_GetTag(gcm, outbuf + *outlen, &len, maxout - *outlen, blocksize);
   786     if (rv != SECSuccess) {
   787 	PORT_Memset(outbuf, 0, *outlen); /* clear the output buffer */
   788 	*outlen = 0;
   789 	return SECFailure;
   790     };
   791     *outlen += len;
   792     return SECSuccess;
   793 }
   795 /*
   796  * See The Galois/Counter Mode of Operation, McGrew and Viega.
   797  *  GCM is basically counter mode with a specific initialization and
   798  *  built in macing operation. NOTE: the only difference between Encrypt
   799  *  and Decrypt is when we calculate the mac. That is because the mac must
   800  *  always be calculated on the cipher text, not the plain text, so for
   801  *  encrypt, we do the CTR update first and for decrypt we do the mac first.
   802  */
   803 SECStatus
   804 GCM_DecryptUpdate(GCMContext *gcm, unsigned char *outbuf,
   805 		unsigned int *outlen, unsigned  int maxout,
   806 		const unsigned char *inbuf, unsigned int inlen,
   807 		unsigned int blocksize)
   808 {
   809     SECStatus rv;
   810     unsigned int tagBytes;
   811     unsigned char tag[MAX_BLOCK_SIZE];
   812     const unsigned char *intag;
   813     unsigned int len;
   815     tagBytes = (gcm->tagBits + (PR_BITS_PER_BYTE-1)) / PR_BITS_PER_BYTE;
   817     /* get the authentication block */
   818     if (inlen < tagBytes) {
   819 	PORT_SetError(SEC_ERROR_INPUT_LEN);
   820 	return SECFailure;
   821     }
   823     inlen -= tagBytes;
   824     intag = inbuf + inlen;
   826     /* verify the block */
   827     rv = gcmHash_Update(&gcm->ghash_context, inbuf, inlen, blocksize);
   828     if (rv != SECSuccess) {
   829 	return SECFailure;
   830     }
   831     rv = gcm_GetTag(gcm, tag, &len, blocksize, blocksize);
   832     if (rv != SECSuccess) {
   833 	return SECFailure;
   834     }
   835     /* Don't decrypt if we can't authenticate the encrypted data!
   836      * This assumes that if tagBits is not a multiple of 8, intag will
   837      * preserve the masked off missing bits.  */
   838     if (NSS_SecureMemcmp(tag, intag, tagBytes) != 0) {
   839 	/* force a CKR_ENCRYPTED_DATA_INVALID error at in softoken */
   840 	PORT_SetError(SEC_ERROR_BAD_DATA);
   841 	return SECFailure;
   842     }
   843     /* finish the decryption */
   844     return CTR_Update(&gcm->ctr_context, outbuf, outlen, maxout,
   845 			  inbuf, inlen, blocksize);
   846 }

mercurial