1 /* cipher.c  -	cipher dispatcher
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3  *               2005, 2007, 2008, 2009, 2011 Free Software Foundation, Inc.
4  * Copyright (C) 2013 g10 Code GmbH
5  *
6  * This file is part of Libgcrypt.
7  *
8  * Libgcrypt is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser general Public License as
10  * published by the Free Software Foundation; either version 2.1 of
11  * the License, or (at your option) any later version.
12  *
13  * Libgcrypt is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this program; if not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 
28 #include "g10lib.h"
29 #include "../src/gcrypt-testapi.h"
30 #include "cipher.h"
31 #include "./cipher-internal.h"
32 
33 
34 /* This is the list of the default ciphers, which are included in
35    libgcrypt.  */
36 static gcry_cipher_spec_t * const cipher_list[] =
37   {
38 #if USE_BLOWFISH
39      &_gcry_cipher_spec_blowfish,
40 #endif
41 #if USE_DES
42      &_gcry_cipher_spec_des,
43      &_gcry_cipher_spec_tripledes,
44 #endif
45 #if USE_ARCFOUR
46      &_gcry_cipher_spec_arcfour,
47 #endif
48 #if USE_CAST5
49      &_gcry_cipher_spec_cast5,
50 #endif
51 #if USE_AES
52      &_gcry_cipher_spec_aes,
53      &_gcry_cipher_spec_aes192,
54      &_gcry_cipher_spec_aes256,
55 #endif
56 #if USE_TWOFISH
57      &_gcry_cipher_spec_twofish,
58      &_gcry_cipher_spec_twofish128,
59 #endif
60 #if USE_SERPENT
61      &_gcry_cipher_spec_serpent128,
62      &_gcry_cipher_spec_serpent192,
63      &_gcry_cipher_spec_serpent256,
64 #endif
65 #if USE_RFC2268
66      &_gcry_cipher_spec_rfc2268_40,
67      &_gcry_cipher_spec_rfc2268_128,
68 #endif
69 #if USE_SEED
70      &_gcry_cipher_spec_seed,
71 #endif
72 #if USE_CAMELLIA
73      &_gcry_cipher_spec_camellia128,
74      &_gcry_cipher_spec_camellia192,
75      &_gcry_cipher_spec_camellia256,
76 #endif
77 #ifdef USE_IDEA
78      &_gcry_cipher_spec_idea,
79 #endif
80 #if USE_SALSA20
81      &_gcry_cipher_spec_salsa20,
82      &_gcry_cipher_spec_salsa20r12,
83 #endif
84 #if USE_GOST28147
85      &_gcry_cipher_spec_gost28147,
86      &_gcry_cipher_spec_gost28147_mesh,
87 #endif
88 #if USE_CHACHA20
89      &_gcry_cipher_spec_chacha20,
90 #endif
91 #if USE_SM4
92      &_gcry_cipher_spec_sm4,
93 #endif
94     NULL
95   };
96 
97 /* Cipher implementations starting with index 0 (enum gcry_cipher_algos) */
98 static gcry_cipher_spec_t * const cipher_list_algo0[] =
99   {
100     NULL, /* GCRY_CIPHER_NONE */
101 #ifdef USE_IDEA
102     &_gcry_cipher_spec_idea,
103 #else
104     NULL,
105 #endif
106 #if USE_DES
107     &_gcry_cipher_spec_tripledes,
108 #else
109     NULL,
110 #endif
111 #if USE_CAST5
112     &_gcry_cipher_spec_cast5,
113 #else
114     NULL,
115 #endif
116 #if USE_BLOWFISH
117     &_gcry_cipher_spec_blowfish,
118 #else
119     NULL,
120 #endif
121     NULL, /* GCRY_CIPHER_SAFER_SK128 */
122     NULL, /* GCRY_CIPHER_DES_SK */
123 #if USE_AES
124     &_gcry_cipher_spec_aes,
125     &_gcry_cipher_spec_aes192,
126     &_gcry_cipher_spec_aes256,
127 #else
128     NULL,
129     NULL,
130     NULL,
131 #endif
132 #if USE_TWOFISH
133     &_gcry_cipher_spec_twofish
134 #else
135     NULL
136 #endif
137   };
138 
139 /* Cipher implementations starting with index 301 (enum gcry_cipher_algos) */
140 static gcry_cipher_spec_t * const cipher_list_algo301[] =
141   {
142 #if USE_ARCFOUR
143     &_gcry_cipher_spec_arcfour,
144 #else
145     NULL,
146 #endif
147 #if USE_DES
148     &_gcry_cipher_spec_des,
149 #else
150     NULL,
151 #endif
152 #if USE_TWOFISH
153     &_gcry_cipher_spec_twofish128,
154 #else
155     NULL,
156 #endif
157 #if USE_SERPENT
158     &_gcry_cipher_spec_serpent128,
159     &_gcry_cipher_spec_serpent192,
160     &_gcry_cipher_spec_serpent256,
161 #else
162     NULL,
163     NULL,
164     NULL,
165 #endif
166 #if USE_RFC2268
167     &_gcry_cipher_spec_rfc2268_40,
168     &_gcry_cipher_spec_rfc2268_128,
169 #else
170     NULL,
171     NULL,
172 #endif
173 #if USE_SEED
174     &_gcry_cipher_spec_seed,
175 #else
176     NULL,
177 #endif
178 #if USE_CAMELLIA
179     &_gcry_cipher_spec_camellia128,
180     &_gcry_cipher_spec_camellia192,
181     &_gcry_cipher_spec_camellia256,
182 #else
183     NULL,
184     NULL,
185     NULL,
186 #endif
187 #if USE_SALSA20
188     &_gcry_cipher_spec_salsa20,
189     &_gcry_cipher_spec_salsa20r12,
190 #else
191     NULL,
192     NULL,
193 #endif
194 #if USE_GOST28147
195     &_gcry_cipher_spec_gost28147,
196 #else
197     NULL,
198 #endif
199 #if USE_CHACHA20
200     &_gcry_cipher_spec_chacha20,
201 #else
202     NULL,
203 #endif
204 #if USE_GOST28147
205     &_gcry_cipher_spec_gost28147_mesh,
206 #else
207     NULL,
208 #endif
209 #if USE_SM4
210      &_gcry_cipher_spec_sm4,
211 #else
212     NULL,
213 #endif
214   };
215 
216 
217 static void _gcry_cipher_setup_mode_ops(gcry_cipher_hd_t c, int mode);
218 
219 
220 static int
map_algo(int algo)221 map_algo (int algo)
222 {
223   return algo;
224 }
225 
226 
227 /* Return the spec structure for the cipher algorithm ALGO.  For
228    an unknown algorithm NULL is returned.  */
229 static gcry_cipher_spec_t *
spec_from_algo(int algo)230 spec_from_algo (int algo)
231 {
232   gcry_cipher_spec_t *spec = NULL;
233 
234   algo = map_algo (algo);
235 
236   if (algo >= 0 && algo < DIM(cipher_list_algo0))
237     spec = cipher_list_algo0[algo];
238   else if (algo >= 301 && algo < 301 + DIM(cipher_list_algo301))
239     spec = cipher_list_algo301[algo - 301];
240 
241   if (spec)
242     gcry_assert (spec->algo == algo);
243 
244   return spec;
245 }
246 
247 
248 /* Lookup a cipher's spec by its name.  */
249 static gcry_cipher_spec_t *
spec_from_name(const char * name)250 spec_from_name (const char *name)
251 {
252   gcry_cipher_spec_t *spec;
253   int idx;
254   const char **aliases;
255 
256   for (idx=0; (spec = cipher_list[idx]); idx++)
257     {
258       if (!stricmp (name, spec->name))
259         return spec;
260       if (spec->aliases)
261         {
262           for (aliases = spec->aliases; *aliases; aliases++)
263             if (!stricmp (name, *aliases))
264               return spec;
265         }
266     }
267 
268   return NULL;
269 }
270 
271 
272 /* Lookup a cipher's spec by its OID.  */
273 static gcry_cipher_spec_t *
spec_from_oid(const char * oid)274 spec_from_oid (const char *oid)
275 {
276   gcry_cipher_spec_t *spec;
277   gcry_cipher_oid_spec_t *oid_specs;
278   int idx, j;
279 
280   for (idx=0; (spec = cipher_list[idx]); idx++)
281     {
282       oid_specs = spec->oids;
283       if (oid_specs)
284         {
285           for (j = 0; oid_specs[j].oid; j++)
286             if (!stricmp (oid, oid_specs[j].oid))
287               return spec;
288         }
289     }
290 
291   return NULL;
292 }
293 
294 
295 /* Locate the OID in the oid table and return the spec or NULL if not
296    found.  An optional "oid." or "OID." prefix in OID is ignored, the
297    OID is expected to be in standard IETF dotted notation.  A pointer
298    to the OID specification of the module implementing this algorithm
299    is return in OID_SPEC unless passed as NULL.*/
300 static gcry_cipher_spec_t *
search_oid(const char * oid,gcry_cipher_oid_spec_t * oid_spec)301 search_oid (const char *oid, gcry_cipher_oid_spec_t *oid_spec)
302 {
303   gcry_cipher_spec_t *spec;
304   int i;
305 
306   if (!oid)
307     return NULL;
308 
309   if (!strncmp (oid, "oid.", 4) || !strncmp (oid, "OID.", 4))
310     oid += 4;
311 
312   spec = spec_from_oid (oid);
313   if (spec && spec->oids)
314     {
315       for (i = 0; spec->oids[i].oid; i++)
316 	if (!stricmp (oid, spec->oids[i].oid))
317 	  {
318 	    if (oid_spec)
319 	      *oid_spec = spec->oids[i];
320             return spec;
321 	  }
322     }
323 
324   return NULL;
325 }
326 
327 
328 /* Map STRING to the cipher algorithm identifier.  Returns the
329    algorithm ID of the cipher for the given name or 0 if the name is
330    not known.  It is valid to pass NULL for STRING which results in a
331    return value of 0. */
332 int
_gcry_cipher_map_name(const char * string)333 _gcry_cipher_map_name (const char *string)
334 {
335   gcry_cipher_spec_t *spec;
336 
337   if (!string)
338     return 0;
339 
340   /* If the string starts with a digit (optionally prefixed with
341      either "OID." or "oid."), we first look into our table of ASN.1
342      object identifiers to figure out the algorithm */
343 
344   spec = search_oid (string, NULL);
345   if (spec)
346     return spec->algo;
347 
348   spec = spec_from_name (string);
349   if (spec)
350     return spec->algo;
351 
352   return 0;
353 }
354 
355 
356 /* Given a STRING with an OID in dotted decimal notation, this
357    function returns the cipher mode (GCRY_CIPHER_MODE_*) associated
358    with that OID or 0 if no mode is known.  Passing NULL for string
359    yields a return value of 0. */
360 int
_gcry_cipher_mode_from_oid(const char * string)361 _gcry_cipher_mode_from_oid (const char *string)
362 {
363   gcry_cipher_spec_t *spec;
364   gcry_cipher_oid_spec_t oid_spec;
365 
366   if (!string)
367     return 0;
368 
369   spec = search_oid (string, &oid_spec);
370   if (spec)
371     return oid_spec.mode;
372 
373   return 0;
374 }
375 
376 
377 /* Map the cipher algorithm identifier ALGORITHM to a string
378    representing this algorithm.  This string is the default name as
379    used by Libgcrypt.  A "?" is returned for an unknown algorithm.
380    NULL is never returned. */
381 const char *
_gcry_cipher_algo_name(int algorithm)382 _gcry_cipher_algo_name (int algorithm)
383 {
384   gcry_cipher_spec_t *spec;
385 
386   spec = spec_from_algo (algorithm);
387   return spec? spec->name : "?";
388 }
389 
390 
391 /* Flag the cipher algorithm with the identifier ALGORITHM as
392    disabled.  There is no error return, the function does nothing for
393    unknown algorithms.  Disabled algorithms are virtually not
394    available in Libgcrypt.  This is not thread safe and should thus be
395    called early. */
396 static void
disable_cipher_algo(int algo)397 disable_cipher_algo (int algo)
398 {
399   gcry_cipher_spec_t *spec = spec_from_algo (algo);
400 
401   if (spec)
402     spec->flags.disabled = 1;
403 }
404 
405 
406 /* Return 0 if the cipher algorithm with identifier ALGORITHM is
407    available. Returns a basic error code value if it is not
408    available.  */
409 static gcry_err_code_t
check_cipher_algo(int algorithm)410 check_cipher_algo (int algorithm)
411 {
412   gcry_cipher_spec_t *spec;
413 
414   spec = spec_from_algo (algorithm);
415   if (spec && !spec->flags.disabled)
416     return 0;
417 
418   return GPG_ERR_CIPHER_ALGO;
419 }
420 
421 
422 /* Return the standard length in bits of the key for the cipher
423    algorithm with the identifier ALGORITHM.  */
424 static unsigned int
cipher_get_keylen(int algorithm)425 cipher_get_keylen (int algorithm)
426 {
427   gcry_cipher_spec_t *spec;
428   unsigned len = 0;
429 
430   spec = spec_from_algo (algorithm);
431   if (spec)
432     {
433       len = spec->keylen;
434       if (!len)
435 	log_bug ("cipher %d w/o key length\n", algorithm);
436     }
437 
438   return len;
439 }
440 
441 
442 /* Return the block length of the cipher algorithm with the identifier
443    ALGORITHM.  This function return 0 for an invalid algorithm.  */
444 static unsigned int
cipher_get_blocksize(int algorithm)445 cipher_get_blocksize (int algorithm)
446 {
447   gcry_cipher_spec_t *spec;
448   unsigned len = 0;
449 
450   spec = spec_from_algo (algorithm);
451   if (spec)
452     {
453       len = spec->blocksize;
454       if (!len)
455         log_bug ("cipher %d w/o blocksize\n", algorithm);
456     }
457 
458   return len;
459 }
460 
461 
462 /*
463    Open a cipher handle for use with cipher algorithm ALGORITHM, using
464    the cipher mode MODE (one of the GCRY_CIPHER_MODE_*) and return a
465    handle in HANDLE.  Put NULL into HANDLE and return an error code if
466    something goes wrong.  FLAGS may be used to modify the
467    operation.  The defined flags are:
468 
469    GCRY_CIPHER_SECURE:  allocate all internal buffers in secure memory.
470    GCRY_CIPHER_ENABLE_SYNC:  Enable the sync operation as used in OpenPGP.
471    GCRY_CIPHER_CBC_CTS:  Enable CTS mode.
472    GCRY_CIPHER_CBC_MAC:  Enable MAC mode.
473 
474    Values for these flags may be combined using OR.
475  */
476 gcry_err_code_t
_gcry_cipher_open(gcry_cipher_hd_t * handle,int algo,int mode,unsigned int flags)477 _gcry_cipher_open (gcry_cipher_hd_t *handle,
478                    int algo, int mode, unsigned int flags)
479 {
480   gcry_err_code_t rc;
481   gcry_cipher_hd_t h = NULL;
482 
483   if (mode >= GCRY_CIPHER_MODE_INTERNAL)
484     rc = GPG_ERR_INV_CIPHER_MODE;
485   else
486     rc = _gcry_cipher_open_internal (&h, algo, mode, flags);
487 
488   *handle = rc ? NULL : h;
489 
490   return rc;
491 }
492 
493 
494 gcry_err_code_t
_gcry_cipher_open_internal(gcry_cipher_hd_t * handle,int algo,int mode,unsigned int flags)495 _gcry_cipher_open_internal (gcry_cipher_hd_t *handle,
496 			    int algo, int mode, unsigned int flags)
497 {
498   int secure = (flags & GCRY_CIPHER_SECURE);
499   gcry_cipher_spec_t *spec;
500   gcry_cipher_hd_t h = NULL;
501   gcry_err_code_t err;
502 
503   /* If the application missed to call the random poll function, we do
504      it here to ensure that it is used once in a while. */
505   _gcry_fast_random_poll ();
506 
507   spec = spec_from_algo (algo);
508   if (!spec)
509     err = GPG_ERR_CIPHER_ALGO;
510   else if (spec->flags.disabled)
511     err = GPG_ERR_CIPHER_ALGO;
512   else
513     err = 0;
514 
515   /* check flags */
516   if ((! err)
517       && ((flags & ~(0
518 		     | GCRY_CIPHER_SECURE
519 		     | GCRY_CIPHER_ENABLE_SYNC
520 		     | GCRY_CIPHER_CBC_CTS
521 		     | GCRY_CIPHER_CBC_MAC))
522 	  || ((flags & GCRY_CIPHER_CBC_CTS) && (flags & GCRY_CIPHER_CBC_MAC))))
523     err = GPG_ERR_CIPHER_ALGO;
524 
525   /* check that a valid mode has been requested */
526   if (! err)
527     switch (mode)
528       {
529       case GCRY_CIPHER_MODE_CCM:
530 	if (spec->blocksize != GCRY_CCM_BLOCK_LEN)
531 	  err = GPG_ERR_INV_CIPHER_MODE;
532 	if (!spec->encrypt || !spec->decrypt)
533 	  err = GPG_ERR_INV_CIPHER_MODE;
534 	break;
535 
536       case GCRY_CIPHER_MODE_XTS:
537 	if (spec->blocksize != GCRY_XTS_BLOCK_LEN)
538 	  err = GPG_ERR_INV_CIPHER_MODE;
539 	if (!spec->encrypt || !spec->decrypt)
540 	  err = GPG_ERR_INV_CIPHER_MODE;
541 	break;
542 
543       case GCRY_CIPHER_MODE_ECB:
544       case GCRY_CIPHER_MODE_CBC:
545       case GCRY_CIPHER_MODE_CFB:
546       case GCRY_CIPHER_MODE_CFB8:
547       case GCRY_CIPHER_MODE_OFB:
548       case GCRY_CIPHER_MODE_CTR:
549       case GCRY_CIPHER_MODE_AESWRAP:
550       case GCRY_CIPHER_MODE_CMAC:
551       case GCRY_CIPHER_MODE_EAX:
552       case GCRY_CIPHER_MODE_GCM:
553 	if (!spec->encrypt || !spec->decrypt)
554 	  err = GPG_ERR_INV_CIPHER_MODE;
555 	break;
556 
557       case GCRY_CIPHER_MODE_POLY1305:
558 	if (!spec->stencrypt || !spec->stdecrypt || !spec->setiv)
559 	  err = GPG_ERR_INV_CIPHER_MODE;
560 	else if (spec->algo != GCRY_CIPHER_CHACHA20)
561 	  err = GPG_ERR_INV_CIPHER_MODE;
562 	break;
563 
564       case GCRY_CIPHER_MODE_OCB:
565         /* Note that our implementation allows only for 128 bit block
566            length algorithms.  Lower block lengths would be possible
567            but we do not implement them because they limit the
568            security too much.  */
569 	if (!spec->encrypt || !spec->decrypt)
570 	  err = GPG_ERR_INV_CIPHER_MODE;
571 	else if (spec->blocksize != (128/8))
572 	  err = GPG_ERR_INV_CIPHER_MODE;
573 	break;
574 
575       case GCRY_CIPHER_MODE_STREAM:
576 	if (!spec->stencrypt || !spec->stdecrypt)
577 	  err = GPG_ERR_INV_CIPHER_MODE;
578 	break;
579 
580       case GCRY_CIPHER_MODE_NONE:
581         /* This mode may be used for debugging.  It copies the main
582            text verbatim to the ciphertext.  We do not allow this in
583            fips mode or if no debug flag has been set.  */
584 	if (fips_mode () || !_gcry_get_debug_flag (0))
585           err = GPG_ERR_INV_CIPHER_MODE;
586 	break;
587 
588       default:
589 	err = GPG_ERR_INV_CIPHER_MODE;
590       }
591 
592   /* Perform selftest here and mark this with a flag in cipher_table?
593      No, we should not do this as it takes too long.  Further it does
594      not make sense to exclude algorithms with failing selftests at
595      runtime: If a selftest fails there is something seriously wrong
596      with the system and thus we better die immediately. */
597 
598   if (! err)
599     {
600       size_t size = (sizeof (*h)
601                      + 2 * spec->contextsize
602                      - sizeof (cipher_context_alignment_t)
603 #ifdef NEED_16BYTE_ALIGNED_CONTEXT
604                      + 15  /* Space for leading alignment gap.  */
605 #endif /*NEED_16BYTE_ALIGNED_CONTEXT*/
606                      );
607 
608       /* Space needed per mode.  */
609       switch (mode)
610 	{
611 	case GCRY_CIPHER_MODE_XTS:
612 	  /* Additional cipher context for tweak. */
613 	  size += 2 * spec->contextsize + 15;
614 	  break;
615 
616 	default:
617 	  break;
618 	}
619 
620       if (secure)
621 	h = xtrycalloc_secure (1, size);
622       else
623 	h = xtrycalloc (1, size);
624 
625       if (! h)
626 	err = gpg_err_code_from_syserror ();
627       else
628 	{
629           size_t off = 0;
630 	  char *tc;
631 
632 #ifdef NEED_16BYTE_ALIGNED_CONTEXT
633           if ( ((uintptr_t)h & 0x0f) )
634             {
635               /* The malloced block is not aligned on a 16 byte
636                  boundary.  Correct for this.  */
637               off = 16 - ((uintptr_t)h & 0x0f);
638               h = (void*)((char*)h + off);
639             }
640 #endif /*NEED_16BYTE_ALIGNED_CONTEXT*/
641 
642 	  h->magic = secure ? CTX_MAGIC_SECURE : CTX_MAGIC_NORMAL;
643           h->actual_handle_size = size - off;
644           h->handle_offset = off;
645 	  h->spec = spec;
646           h->algo = algo;
647 	  h->mode = mode;
648 	  h->flags = flags;
649 
650           /* Setup mode routines. */
651           _gcry_cipher_setup_mode_ops(h, mode);
652 
653           /* Setup defaults depending on the mode.  */
654           switch (mode)
655             {
656             case GCRY_CIPHER_MODE_OCB:
657               h->u_mode.ocb.taglen = 16; /* Bytes.  */
658               break;
659 
660 	    case GCRY_CIPHER_MODE_XTS:
661 	      tc = h->context.c + spec->contextsize * 2;
662 	      tc += (16 - (uintptr_t)tc % 16) % 16;
663 	      h->u_mode.xts.tweak_context = tc;
664 
665 	      break;
666 
667             default:
668               break;
669             }
670         }
671     }
672 
673   /* Done.  */
674 
675   *handle = err ? NULL : h;
676 
677   return err;
678 }
679 
680 
681 /* Release all resources associated with the cipher handle H. H may be
682    NULL in which case this is a no-operation. */
683 void
_gcry_cipher_close(gcry_cipher_hd_t h)684 _gcry_cipher_close (gcry_cipher_hd_t h)
685 {
686   size_t off;
687 
688   if (!h)
689     return;
690 
691   if ((h->magic != CTX_MAGIC_SECURE)
692       && (h->magic != CTX_MAGIC_NORMAL))
693     _gcry_fatal_error(GPG_ERR_INTERNAL,
694 		      "gcry_cipher_close: already closed/invalid handle");
695   else
696     h->magic = 0;
697 
698   /* We always want to wipe out the memory even when the context has
699      been allocated in secure memory.  The user might have disabled
700      secure memory or is using his own implementation which does not
701      do the wiping.  To accomplish this we need to keep track of the
702      actual size of this structure because we have no way to known
703      how large the allocated area was when using a standard malloc. */
704   off = h->handle_offset;
705   wipememory (h, h->actual_handle_size);
706 
707   xfree ((char*)h - off);
708 }
709 
710 
711 /* Set the key to be used for the encryption context C to KEY with
712    length KEYLEN.  The length should match the required length. */
713 static gcry_err_code_t
cipher_setkey(gcry_cipher_hd_t c,byte * key,size_t keylen)714 cipher_setkey (gcry_cipher_hd_t c, byte *key, size_t keylen)
715 {
716   gcry_err_code_t rc;
717 
718   if (c->mode == GCRY_CIPHER_MODE_XTS)
719     {
720       /* XTS uses two keys. */
721       if (keylen % 2)
722 	return GPG_ERR_INV_KEYLEN;
723       keylen /= 2;
724 
725       if (fips_mode ())
726 	{
727 	  /* Reject key if subkeys Key_1 and Key_2 are equal.
728 	     See "Implementation Guidance for FIPS 140-2, A.9 XTS-AES
729 	     Key Generation Requirements" for details.  */
730 	  if (buf_eq_const (key, key + keylen, keylen))
731 	    return GPG_ERR_WEAK_KEY;
732 	}
733     }
734 
735   rc = c->spec->setkey (&c->context.c, key, keylen, &c->bulk);
736   if (!rc || (c->marks.allow_weak_key && rc == GPG_ERR_WEAK_KEY))
737     {
738       /* Duplicate initial context.  */
739       memcpy ((void *) ((char *) &c->context.c + c->spec->contextsize),
740               (void *) &c->context.c,
741               c->spec->contextsize);
742       c->marks.key = 1;
743 
744       switch (c->mode)
745         {
746         case GCRY_CIPHER_MODE_CMAC:
747           rc = _gcry_cipher_cmac_set_subkeys (c);
748           break;
749 
750         case GCRY_CIPHER_MODE_EAX:
751           rc = _gcry_cipher_eax_setkey (c);
752           break;
753 
754         case GCRY_CIPHER_MODE_GCM:
755           _gcry_cipher_gcm_setkey (c);
756           break;
757 
758         case GCRY_CIPHER_MODE_OCB:
759           _gcry_cipher_ocb_setkey (c);
760           break;
761 
762         case GCRY_CIPHER_MODE_POLY1305:
763           _gcry_cipher_poly1305_setkey (c);
764           break;
765 
766 	case GCRY_CIPHER_MODE_XTS:
767 	  /* Setup tweak cipher with second part of XTS key. */
768 	  rc = c->spec->setkey (c->u_mode.xts.tweak_context, key + keylen,
769 				keylen, &c->bulk);
770 	  if (!rc || (c->marks.allow_weak_key && rc == GPG_ERR_WEAK_KEY))
771 	    {
772 	      /* Duplicate initial tweak context.  */
773 	      memcpy (c->u_mode.xts.tweak_context + c->spec->contextsize,
774 		      c->u_mode.xts.tweak_context, c->spec->contextsize);
775 	    }
776 	  else
777 	    c->marks.key = 0;
778 	  break;
779 
780         default:
781           break;
782         };
783     }
784   else
785     c->marks.key = 0;
786 
787   return rc;
788 }
789 
790 
791 /* Set the IV to be used for the encryption context C to IV with
792    length IVLEN.  The length should match the required length. */
793 static gcry_err_code_t
cipher_setiv(gcry_cipher_hd_t c,const byte * iv,size_t ivlen)794 cipher_setiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen)
795 {
796   /* If the cipher has its own IV handler, we use only this one.  This
797      is currently used for stream ciphers requiring a nonce.  */
798   if (c->spec->setiv)
799     {
800       c->spec->setiv (&c->context.c, iv, ivlen);
801       return 0;
802     }
803 
804   memset (c->u_iv.iv, 0, c->spec->blocksize);
805   if (iv)
806     {
807       if (ivlen != c->spec->blocksize)
808         {
809           log_info ("WARNING: cipher_setiv: ivlen=%u blklen=%u\n",
810                     (unsigned int)ivlen, (unsigned int)c->spec->blocksize);
811           fips_signal_error ("IV length does not match blocklength");
812         }
813       if (ivlen > c->spec->blocksize)
814         ivlen = c->spec->blocksize;
815       memcpy (c->u_iv.iv, iv, ivlen);
816       c->marks.iv = 1;
817     }
818   else
819       c->marks.iv = 0;
820   c->unused = 0;
821 
822   return 0;
823 }
824 
825 
826 /* Reset the cipher context to the initial context.  This is basically
827    the same as an release followed by a new. */
828 static void
cipher_reset(gcry_cipher_hd_t c)829 cipher_reset (gcry_cipher_hd_t c)
830 {
831   unsigned int marks_key, marks_allow_weak_key;
832 
833   marks_key = c->marks.key;
834   marks_allow_weak_key = c->marks.allow_weak_key;
835 
836   memcpy (&c->context.c,
837 	  (char *) &c->context.c + c->spec->contextsize,
838 	  c->spec->contextsize);
839   memset (&c->marks, 0, sizeof c->marks);
840   memset (c->u_iv.iv, 0, c->spec->blocksize);
841   memset (c->lastiv, 0, c->spec->blocksize);
842   memset (c->u_ctr.ctr, 0, c->spec->blocksize);
843   c->unused = 0;
844 
845   c->marks.key = marks_key;
846   c->marks.allow_weak_key = marks_allow_weak_key;
847 
848   switch (c->mode)
849     {
850     case GCRY_CIPHER_MODE_CMAC:
851       _gcry_cmac_reset(&c->u_mode.cmac);
852       break;
853 
854     case GCRY_CIPHER_MODE_EAX:
855       _gcry_cmac_reset(&c->u_mode.eax.cmac_header);
856       _gcry_cmac_reset(&c->u_mode.eax.cmac_ciphertext);
857       break;
858 
859     case GCRY_CIPHER_MODE_GCM:
860       /* Only clear head of u_mode, keep ghash_key and gcm_table. */
861       {
862         byte *u_mode_pos = (void *)&c->u_mode;
863         byte *ghash_key_pos = c->u_mode.gcm.u_ghash_key.key;
864         size_t u_mode_head_length = ghash_key_pos - u_mode_pos;
865 
866         memset (&c->u_mode, 0, u_mode_head_length);
867       }
868       break;
869 
870     case GCRY_CIPHER_MODE_POLY1305:
871       memset (&c->u_mode.poly1305, 0, sizeof c->u_mode.poly1305);
872       break;
873 
874     case GCRY_CIPHER_MODE_CCM:
875       memset (&c->u_mode.ccm, 0, sizeof c->u_mode.ccm);
876       break;
877 
878     case GCRY_CIPHER_MODE_OCB:
879       /* Do not clear precalculated L-values */
880       {
881 	byte *u_mode_head_pos = (void *)&c->u_mode.ocb;
882 	byte *u_mode_tail_pos = (void *)&c->u_mode.ocb.tag;
883 	size_t u_mode_head_length = u_mode_tail_pos - u_mode_head_pos;
884 	size_t u_mode_tail_length = sizeof(c->u_mode.ocb) - u_mode_head_length;
885 
886 	memset (u_mode_tail_pos, 0, u_mode_tail_length);
887 
888 	/* Setup default taglen.  */
889 	c->u_mode.ocb.taglen = 16;
890       }
891       break;
892 
893     case GCRY_CIPHER_MODE_XTS:
894       memcpy (c->u_mode.xts.tweak_context,
895 	      c->u_mode.xts.tweak_context + c->spec->contextsize,
896 	      c->spec->contextsize);
897       break;
898 
899     default:
900       break; /* u_mode unused by other modes. */
901     }
902 }
903 
904 
905 
906 static gcry_err_code_t
do_ecb_crypt(gcry_cipher_hd_t c,unsigned char * outbuf,size_t outbuflen,const unsigned char * inbuf,size_t inbuflen,gcry_cipher_encrypt_t crypt_fn)907 do_ecb_crypt (gcry_cipher_hd_t c,
908               unsigned char *outbuf, size_t outbuflen,
909               const unsigned char *inbuf, size_t inbuflen,
910               gcry_cipher_encrypt_t crypt_fn)
911 {
912   unsigned int blocksize = c->spec->blocksize;
913   size_t n, nblocks;
914   unsigned int burn, nburn;
915 
916   if (outbuflen < inbuflen)
917     return GPG_ERR_BUFFER_TOO_SHORT;
918   if ((inbuflen % blocksize))
919     return GPG_ERR_INV_LENGTH;
920 
921   nblocks = inbuflen / blocksize;
922   burn = 0;
923 
924   for (n=0; n < nblocks; n++ )
925     {
926       nburn = crypt_fn (&c->context.c, outbuf, inbuf);
927       burn = nburn > burn ? nburn : burn;
928       inbuf  += blocksize;
929       outbuf += blocksize;
930     }
931 
932   if (burn > 0)
933     _gcry_burn_stack (burn + 4 * sizeof(void *));
934 
935   return 0;
936 }
937 
938 static gcry_err_code_t
do_ecb_encrypt(gcry_cipher_hd_t c,unsigned char * outbuf,size_t outbuflen,const unsigned char * inbuf,size_t inbuflen)939 do_ecb_encrypt (gcry_cipher_hd_t c,
940                 unsigned char *outbuf, size_t outbuflen,
941                 const unsigned char *inbuf, size_t inbuflen)
942 {
943   return do_ecb_crypt (c, outbuf, outbuflen, inbuf, inbuflen, c->spec->encrypt);
944 }
945 
946 static gcry_err_code_t
do_ecb_decrypt(gcry_cipher_hd_t c,unsigned char * outbuf,size_t outbuflen,const unsigned char * inbuf,size_t inbuflen)947 do_ecb_decrypt (gcry_cipher_hd_t c,
948                 unsigned char *outbuf, size_t outbuflen,
949                 const unsigned char *inbuf, size_t inbuflen)
950 {
951   return do_ecb_crypt (c, outbuf, outbuflen, inbuf, inbuflen, c->spec->decrypt);
952 }
953 
954 
955 static gcry_err_code_t
do_stream_encrypt(gcry_cipher_hd_t c,unsigned char * outbuf,size_t outbuflen,const unsigned char * inbuf,size_t inbuflen)956 do_stream_encrypt (gcry_cipher_hd_t c,
957                 unsigned char *outbuf, size_t outbuflen,
958                 const unsigned char *inbuf, size_t inbuflen)
959 {
960   (void)outbuflen;
961   c->spec->stencrypt (&c->context.c, outbuf, (void *)inbuf, inbuflen);
962   return 0;
963 }
964 
965 static gcry_err_code_t
do_stream_decrypt(gcry_cipher_hd_t c,unsigned char * outbuf,size_t outbuflen,const unsigned char * inbuf,size_t inbuflen)966 do_stream_decrypt (gcry_cipher_hd_t c,
967                 unsigned char *outbuf, size_t outbuflen,
968                 const unsigned char *inbuf, size_t inbuflen)
969 {
970   (void)outbuflen;
971   c->spec->stdecrypt (&c->context.c, outbuf, (void *)inbuf, inbuflen);
972   return 0;
973 }
974 
975 
976 static gcry_err_code_t
do_encrypt_none_unknown(gcry_cipher_hd_t c,byte * outbuf,size_t outbuflen,const byte * inbuf,size_t inbuflen)977 do_encrypt_none_unknown (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen,
978                          const byte *inbuf, size_t inbuflen)
979 {
980   gcry_err_code_t rc;
981 
982   (void)outbuflen;
983 
984   switch (c->mode)
985     {
986     case GCRY_CIPHER_MODE_CMAC:
987       rc = GPG_ERR_INV_CIPHER_MODE;
988       break;
989 
990     case GCRY_CIPHER_MODE_NONE:
991       if (fips_mode () || !_gcry_get_debug_flag (0))
992         {
993           fips_signal_error ("cipher mode NONE used");
994           rc = GPG_ERR_INV_CIPHER_MODE;
995         }
996       else
997         {
998           if (inbuf != outbuf)
999             memmove (outbuf, inbuf, inbuflen);
1000           rc = 0;
1001         }
1002       break;
1003 
1004     default:
1005       log_fatal ("cipher_encrypt: invalid mode %d\n", c->mode );
1006       rc = GPG_ERR_INV_CIPHER_MODE;
1007       break;
1008     }
1009 
1010   return rc;
1011 }
1012 
1013 static gcry_err_code_t
do_decrypt_none_unknown(gcry_cipher_hd_t c,byte * outbuf,size_t outbuflen,const byte * inbuf,size_t inbuflen)1014 do_decrypt_none_unknown (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen,
1015                          const byte *inbuf, size_t inbuflen)
1016 {
1017   gcry_err_code_t rc;
1018 
1019   (void)outbuflen;
1020 
1021   switch (c->mode)
1022     {
1023     case GCRY_CIPHER_MODE_CMAC:
1024       rc = GPG_ERR_INV_CIPHER_MODE;
1025       break;
1026 
1027     case GCRY_CIPHER_MODE_NONE:
1028       if (fips_mode () || !_gcry_get_debug_flag (0))
1029         {
1030           fips_signal_error ("cipher mode NONE used");
1031           rc = GPG_ERR_INV_CIPHER_MODE;
1032         }
1033       else
1034         {
1035           if (inbuf != outbuf)
1036             memmove (outbuf, inbuf, inbuflen);
1037           rc = 0;
1038         }
1039       break;
1040 
1041     default:
1042       log_fatal ("cipher_decrypt: invalid mode %d\n", c->mode );
1043       rc = GPG_ERR_INV_CIPHER_MODE;
1044       break;
1045     }
1046 
1047   return rc;
1048 }
1049 
1050 
1051 /****************
1052  * Encrypt IN and write it to OUT.  If IN is NULL, in-place encryption has
1053  * been requested.
1054  */
1055 gcry_err_code_t
_gcry_cipher_encrypt(gcry_cipher_hd_t h,void * out,size_t outsize,const void * in,size_t inlen)1056 _gcry_cipher_encrypt (gcry_cipher_hd_t h, void *out, size_t outsize,
1057                       const void *in, size_t inlen)
1058 {
1059   gcry_err_code_t rc;
1060 
1061   if (!in)  /* Caller requested in-place encryption.  */
1062     {
1063       in = out;
1064       inlen = outsize;
1065     }
1066 
1067   if (h->mode != GCRY_CIPHER_MODE_NONE && !h->marks.key)
1068     {
1069       log_error ("cipher_encrypt: key not set\n");
1070       return GPG_ERR_MISSING_KEY;
1071     }
1072 
1073   rc = h->mode_ops.encrypt (h, out, outsize, in, inlen);
1074 
1075   /* Failsafe: Make sure that the plaintext will never make it into
1076      OUT if the encryption returned an error.  */
1077   if (rc && out)
1078     memset (out, 0x42, outsize);
1079 
1080   return rc;
1081 }
1082 
1083 
1084 /****************
1085  * Decrypt IN and write it to OUT.  If IN is NULL, in-place encryption has
1086  * been requested.
1087  */
1088 gcry_err_code_t
_gcry_cipher_decrypt(gcry_cipher_hd_t h,void * out,size_t outsize,const void * in,size_t inlen)1089 _gcry_cipher_decrypt (gcry_cipher_hd_t h, void *out, size_t outsize,
1090                       const void *in, size_t inlen)
1091 {
1092   if (!in) /* Caller requested in-place encryption. */
1093     {
1094       in = out;
1095       inlen = outsize;
1096     }
1097 
1098   if (h->mode != GCRY_CIPHER_MODE_NONE && !h->marks.key)
1099     {
1100       log_error ("cipher_decrypt: key not set\n");
1101       return GPG_ERR_MISSING_KEY;
1102     }
1103 
1104   return h->mode_ops.decrypt (h, out, outsize, in, inlen);
1105 }
1106 
1107 
1108 /****************
1109  * Used for PGP's somewhat strange CFB mode. Only works if
1110  * the corresponding flag is set.
1111  */
1112 static void
cipher_sync(gcry_cipher_hd_t c)1113 cipher_sync (gcry_cipher_hd_t c)
1114 {
1115   if ((c->flags & GCRY_CIPHER_ENABLE_SYNC) && c->unused)
1116     {
1117       memmove (c->u_iv.iv + c->unused,
1118                c->u_iv.iv, c->spec->blocksize - c->unused);
1119       memcpy (c->u_iv.iv,
1120               c->lastiv + c->spec->blocksize - c->unused, c->unused);
1121       c->unused = 0;
1122     }
1123 }
1124 
1125 
1126 gcry_err_code_t
_gcry_cipher_setkey(gcry_cipher_hd_t hd,const void * key,size_t keylen)1127 _gcry_cipher_setkey (gcry_cipher_hd_t hd, const void *key, size_t keylen)
1128 {
1129   return cipher_setkey (hd, (void*)key, keylen);
1130 }
1131 
1132 
1133 gcry_err_code_t
_gcry_cipher_setiv(gcry_cipher_hd_t hd,const void * iv,size_t ivlen)1134 _gcry_cipher_setiv (gcry_cipher_hd_t hd, const void *iv, size_t ivlen)
1135 {
1136   return hd->mode_ops.setiv (hd, iv, ivlen);
1137 }
1138 
1139 
1140 /* Set counter for CTR mode.  (CTR,CTRLEN) must denote a buffer of
1141    block size length, or (NULL,0) to set the CTR to the all-zero
1142    block. */
1143 gpg_err_code_t
_gcry_cipher_setctr(gcry_cipher_hd_t hd,const void * ctr,size_t ctrlen)1144 _gcry_cipher_setctr (gcry_cipher_hd_t hd, const void *ctr, size_t ctrlen)
1145 {
1146   if (ctr && ctrlen == hd->spec->blocksize)
1147     {
1148       memcpy (hd->u_ctr.ctr, ctr, hd->spec->blocksize);
1149       hd->unused = 0;
1150     }
1151   else if (!ctr || !ctrlen)
1152     {
1153       memset (hd->u_ctr.ctr, 0, hd->spec->blocksize);
1154       hd->unused = 0;
1155     }
1156   else
1157     return GPG_ERR_INV_ARG;
1158 
1159   return 0;
1160 }
1161 
1162 gpg_err_code_t
_gcry_cipher_getctr(gcry_cipher_hd_t hd,void * ctr,size_t ctrlen)1163 _gcry_cipher_getctr (gcry_cipher_hd_t hd, void *ctr, size_t ctrlen)
1164 {
1165   if (ctr && ctrlen == hd->spec->blocksize)
1166     memcpy (ctr, hd->u_ctr.ctr, hd->spec->blocksize);
1167   else
1168     return GPG_ERR_INV_ARG;
1169 
1170   return 0;
1171 }
1172 
1173 
1174 gcry_err_code_t
_gcry_cipher_authenticate(gcry_cipher_hd_t hd,const void * abuf,size_t abuflen)1175 _gcry_cipher_authenticate (gcry_cipher_hd_t hd, const void *abuf,
1176                            size_t abuflen)
1177 {
1178   gcry_err_code_t rc;
1179 
1180   if (hd->mode_ops.authenticate)
1181     {
1182       rc = hd->mode_ops.authenticate (hd, abuf, abuflen);
1183     }
1184   else
1185     {
1186       log_error ("gcry_cipher_authenticate: invalid mode %d\n", hd->mode);
1187       rc = GPG_ERR_INV_CIPHER_MODE;
1188     }
1189 
1190   return rc;
1191 }
1192 
1193 
1194 gcry_err_code_t
_gcry_cipher_gettag(gcry_cipher_hd_t hd,void * outtag,size_t taglen)1195 _gcry_cipher_gettag (gcry_cipher_hd_t hd, void *outtag, size_t taglen)
1196 {
1197   gcry_err_code_t rc;
1198 
1199   if (hd->mode_ops.get_tag)
1200     {
1201       rc = hd->mode_ops.get_tag (hd, outtag, taglen);
1202     }
1203   else
1204     {
1205       log_error ("gcry_cipher_gettag: invalid mode %d\n", hd->mode);
1206       rc = GPG_ERR_INV_CIPHER_MODE;
1207     }
1208 
1209   return rc;
1210 }
1211 
1212 
1213 gcry_err_code_t
_gcry_cipher_checktag(gcry_cipher_hd_t hd,const void * intag,size_t taglen)1214 _gcry_cipher_checktag (gcry_cipher_hd_t hd, const void *intag, size_t taglen)
1215 {
1216   gcry_err_code_t rc;
1217 
1218   if (hd->mode_ops.check_tag)
1219     {
1220       rc = hd->mode_ops.check_tag (hd, intag, taglen);
1221     }
1222   else
1223     {
1224       log_error ("gcry_cipher_checktag: invalid mode %d\n", hd->mode);
1225       rc = GPG_ERR_INV_CIPHER_MODE;
1226     }
1227 
1228   return rc;
1229 }
1230 
1231 
1232 
1233 static void
_gcry_cipher_setup_mode_ops(gcry_cipher_hd_t c,int mode)1234 _gcry_cipher_setup_mode_ops(gcry_cipher_hd_t c, int mode)
1235 {
1236   /* Setup encryption and decryption routines. */
1237   switch (mode)
1238     {
1239     case GCRY_CIPHER_MODE_STREAM:
1240       c->mode_ops.encrypt = do_stream_encrypt;
1241       c->mode_ops.decrypt = do_stream_decrypt;
1242       break;
1243 
1244     case GCRY_CIPHER_MODE_ECB:
1245       c->mode_ops.encrypt = do_ecb_encrypt;
1246       c->mode_ops.decrypt = do_ecb_decrypt;
1247       break;
1248 
1249     case GCRY_CIPHER_MODE_CBC:
1250       if (!(c->flags & GCRY_CIPHER_CBC_CTS))
1251         {
1252           c->mode_ops.encrypt = _gcry_cipher_cbc_encrypt;
1253           c->mode_ops.decrypt = _gcry_cipher_cbc_decrypt;
1254         }
1255       else
1256         {
1257           c->mode_ops.encrypt = _gcry_cipher_cbc_cts_encrypt;
1258           c->mode_ops.decrypt = _gcry_cipher_cbc_cts_decrypt;
1259         }
1260       break;
1261 
1262     case GCRY_CIPHER_MODE_CFB:
1263       c->mode_ops.encrypt = _gcry_cipher_cfb_encrypt;
1264       c->mode_ops.decrypt = _gcry_cipher_cfb_decrypt;
1265       break;
1266 
1267     case GCRY_CIPHER_MODE_CFB8:
1268       c->mode_ops.encrypt = _gcry_cipher_cfb8_encrypt;
1269       c->mode_ops.decrypt = _gcry_cipher_cfb8_decrypt;
1270       break;
1271 
1272     case GCRY_CIPHER_MODE_OFB:
1273       c->mode_ops.encrypt = _gcry_cipher_ofb_encrypt;
1274       c->mode_ops.decrypt = _gcry_cipher_ofb_encrypt;
1275       break;
1276 
1277     case GCRY_CIPHER_MODE_CTR:
1278       c->mode_ops.encrypt = _gcry_cipher_ctr_encrypt;
1279       c->mode_ops.decrypt = _gcry_cipher_ctr_encrypt;
1280       break;
1281 
1282     case GCRY_CIPHER_MODE_AESWRAP:
1283       c->mode_ops.encrypt = _gcry_cipher_aeswrap_encrypt;
1284       c->mode_ops.decrypt = _gcry_cipher_aeswrap_decrypt;
1285       break;
1286 
1287     case GCRY_CIPHER_MODE_CCM:
1288       c->mode_ops.encrypt = _gcry_cipher_ccm_encrypt;
1289       c->mode_ops.decrypt = _gcry_cipher_ccm_decrypt;
1290       break;
1291 
1292     case GCRY_CIPHER_MODE_EAX:
1293       c->mode_ops.encrypt = _gcry_cipher_eax_encrypt;
1294       c->mode_ops.decrypt = _gcry_cipher_eax_decrypt;
1295       break;
1296 
1297     case GCRY_CIPHER_MODE_GCM:
1298       c->mode_ops.encrypt = _gcry_cipher_gcm_encrypt;
1299       c->mode_ops.decrypt = _gcry_cipher_gcm_decrypt;
1300       break;
1301 
1302     case GCRY_CIPHER_MODE_POLY1305:
1303       c->mode_ops.encrypt = _gcry_cipher_poly1305_encrypt;
1304       c->mode_ops.decrypt = _gcry_cipher_poly1305_decrypt;
1305       break;
1306 
1307     case GCRY_CIPHER_MODE_OCB:
1308       c->mode_ops.encrypt = _gcry_cipher_ocb_encrypt;
1309       c->mode_ops.decrypt = _gcry_cipher_ocb_decrypt;
1310       break;
1311 
1312     case GCRY_CIPHER_MODE_XTS:
1313       c->mode_ops.encrypt = _gcry_cipher_xts_encrypt;
1314       c->mode_ops.decrypt = _gcry_cipher_xts_decrypt;
1315       break;
1316 
1317     default:
1318       c->mode_ops.encrypt = do_encrypt_none_unknown;
1319       c->mode_ops.decrypt = do_decrypt_none_unknown;
1320       break;
1321     }
1322 
1323   /* Setup IV setting routine. */
1324   switch (mode)
1325     {
1326     case GCRY_CIPHER_MODE_CCM:
1327       c->mode_ops.setiv = _gcry_cipher_ccm_set_nonce;
1328       break;
1329 
1330     case GCRY_CIPHER_MODE_EAX:
1331       c->mode_ops.setiv = _gcry_cipher_eax_set_nonce;
1332       break;
1333 
1334     case GCRY_CIPHER_MODE_GCM:
1335       c->mode_ops.setiv =  _gcry_cipher_gcm_setiv;
1336       break;
1337 
1338     case GCRY_CIPHER_MODE_POLY1305:
1339       c->mode_ops.setiv = _gcry_cipher_poly1305_setiv;
1340       break;
1341 
1342     case GCRY_CIPHER_MODE_OCB:
1343       c->mode_ops.setiv = _gcry_cipher_ocb_set_nonce;
1344       break;
1345 
1346     default:
1347       c->mode_ops.setiv = cipher_setiv;
1348       break;
1349     }
1350 
1351 
1352   /* Setup authentication routines for AEAD modes. */
1353   switch (mode)
1354     {
1355     case GCRY_CIPHER_MODE_CCM:
1356       c->mode_ops.authenticate = _gcry_cipher_ccm_authenticate;
1357       c->mode_ops.get_tag      = _gcry_cipher_ccm_get_tag;
1358       c->mode_ops.check_tag    = _gcry_cipher_ccm_check_tag;
1359       break;
1360 
1361     case GCRY_CIPHER_MODE_CMAC:
1362       c->mode_ops.authenticate = _gcry_cipher_cmac_authenticate;
1363       c->mode_ops.get_tag      = _gcry_cipher_cmac_get_tag;
1364       c->mode_ops.check_tag    = _gcry_cipher_cmac_check_tag;
1365       break;
1366 
1367     case GCRY_CIPHER_MODE_EAX:
1368       c->mode_ops.authenticate = _gcry_cipher_eax_authenticate;
1369       c->mode_ops.get_tag      = _gcry_cipher_eax_get_tag;
1370       c->mode_ops.check_tag    = _gcry_cipher_eax_check_tag;
1371       break;
1372 
1373     case GCRY_CIPHER_MODE_GCM:
1374       c->mode_ops.authenticate = _gcry_cipher_gcm_authenticate;
1375       c->mode_ops.get_tag      = _gcry_cipher_gcm_get_tag;
1376       c->mode_ops.check_tag    = _gcry_cipher_gcm_check_tag;
1377       break;
1378 
1379     case GCRY_CIPHER_MODE_POLY1305:
1380       c->mode_ops.authenticate = _gcry_cipher_poly1305_authenticate;
1381       c->mode_ops.get_tag      = _gcry_cipher_poly1305_get_tag;
1382       c->mode_ops.check_tag    = _gcry_cipher_poly1305_check_tag;
1383       break;
1384 
1385     case GCRY_CIPHER_MODE_OCB:
1386       c->mode_ops.authenticate = _gcry_cipher_ocb_authenticate;
1387       c->mode_ops.get_tag      = _gcry_cipher_ocb_get_tag;
1388       c->mode_ops.check_tag    = _gcry_cipher_ocb_check_tag;
1389       break;
1390 
1391     default:
1392       c->mode_ops.authenticate = NULL;
1393       c->mode_ops.get_tag      = NULL;
1394       c->mode_ops.check_tag    = NULL;
1395       break;
1396     }
1397 }
1398 
1399 
1400 gcry_err_code_t
_gcry_cipher_ctl(gcry_cipher_hd_t h,int cmd,void * buffer,size_t buflen)1401 _gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer, size_t buflen)
1402 {
1403   gcry_err_code_t rc = 0;
1404 
1405   switch (cmd)
1406     {
1407     case GCRYCTL_RESET:
1408       cipher_reset (h);
1409       break;
1410 
1411     case GCRYCTL_FINALIZE:
1412       if (!h || buffer || buflen)
1413 	return GPG_ERR_INV_ARG;
1414       h->marks.finalize = 1;
1415       break;
1416 
1417     case GCRYCTL_CFB_SYNC:
1418       cipher_sync( h );
1419       break;
1420 
1421     case GCRYCTL_SET_CBC_CTS:
1422       if (buflen)
1423 	if (h->flags & GCRY_CIPHER_CBC_MAC)
1424 	  rc = GPG_ERR_INV_FLAG;
1425 	else
1426 	  h->flags |= GCRY_CIPHER_CBC_CTS;
1427       else
1428 	h->flags &= ~GCRY_CIPHER_CBC_CTS;
1429       break;
1430 
1431     case GCRYCTL_SET_CBC_MAC:
1432       if (buflen)
1433 	if (h->flags & GCRY_CIPHER_CBC_CTS)
1434 	  rc = GPG_ERR_INV_FLAG;
1435 	else
1436 	  h->flags |= GCRY_CIPHER_CBC_MAC;
1437       else
1438 	h->flags &= ~GCRY_CIPHER_CBC_MAC;
1439       break;
1440 
1441     case GCRYCTL_SET_CCM_LENGTHS:
1442       {
1443         u64 params[3];
1444         size_t encryptedlen;
1445         size_t aadlen;
1446         size_t authtaglen;
1447 
1448         if (h->mode != GCRY_CIPHER_MODE_CCM)
1449           return GPG_ERR_INV_CIPHER_MODE;
1450 
1451         if (!buffer || buflen != 3 * sizeof(u64))
1452           return GPG_ERR_INV_ARG;
1453 
1454         /* This command is used to pass additional length parameters needed
1455            by CCM mode to initialize CBC-MAC.  */
1456         memcpy (params, buffer, sizeof(params));
1457         encryptedlen = params[0];
1458         aadlen = params[1];
1459         authtaglen = params[2];
1460 
1461         rc = _gcry_cipher_ccm_set_lengths (h, encryptedlen, aadlen, authtaglen);
1462       }
1463       break;
1464 
1465     case GCRYCTL_SET_TAGLEN:
1466       if (!h || !buffer || buflen != sizeof(int) )
1467 	return GPG_ERR_INV_ARG;
1468       switch (h->mode)
1469         {
1470         case GCRY_CIPHER_MODE_OCB:
1471           switch (*(int*)buffer)
1472             {
1473             case 8: case 12: case 16:
1474               h->u_mode.ocb.taglen = *(int*)buffer;
1475               break;
1476             default:
1477               rc = GPG_ERR_INV_LENGTH; /* Invalid tag length. */
1478               break;
1479             }
1480           break;
1481 
1482         default:
1483           rc =GPG_ERR_INV_CIPHER_MODE;
1484           break;
1485         }
1486       break;
1487 
1488     case GCRYCTL_DISABLE_ALGO:
1489       /* This command expects NULL for H and BUFFER to point to an
1490          integer with the algo number.  */
1491       if( h || !buffer || buflen != sizeof(int) )
1492 	return GPG_ERR_CIPHER_ALGO;
1493       disable_cipher_algo( *(int*)buffer );
1494       break;
1495 
1496     case PRIV_CIPHERCTL_DISABLE_WEAK_KEY:  /* (private)  */
1497       if (h->spec->set_extra_info)
1498         rc = h->spec->set_extra_info
1499           (&h->context.c, CIPHER_INFO_NO_WEAK_KEY, NULL, 0);
1500       else
1501         rc = GPG_ERR_NOT_SUPPORTED;
1502       break;
1503 
1504     case PRIV_CIPHERCTL_GET_INPUT_VECTOR: /* (private)  */
1505       /* This is the input block as used in CFB and OFB mode which has
1506          initially been set as IV.  The returned format is:
1507            1 byte  Actual length of the block in bytes.
1508            n byte  The block.
1509          If the provided buffer is too short, an error is returned. */
1510       if (buflen < (1 + h->spec->blocksize))
1511         rc = GPG_ERR_TOO_SHORT;
1512       else
1513         {
1514           unsigned char *ivp;
1515           unsigned char *dst = buffer;
1516           int n = h->unused;
1517 
1518           if (!n)
1519             n = h->spec->blocksize;
1520           gcry_assert (n <= h->spec->blocksize);
1521           *dst++ = n;
1522           ivp = h->u_iv.iv + h->spec->blocksize - n;
1523           while (n--)
1524             *dst++ = *ivp++;
1525         }
1526       break;
1527 
1528     case GCRYCTL_SET_SBOX:
1529       if (h->spec->set_extra_info)
1530         rc = h->spec->set_extra_info
1531           (&h->context.c, GCRYCTL_SET_SBOX, buffer, buflen);
1532       else
1533         rc = GPG_ERR_NOT_SUPPORTED;
1534       break;
1535 
1536     case GCRYCTL_SET_ALLOW_WEAK_KEY:
1537       /* Expecting BUFFER to be NULL and buflen to be on/off flag (0 or 1). */
1538       if (!h || buffer || buflen > 1)
1539 	return GPG_ERR_CIPHER_ALGO;
1540       h->marks.allow_weak_key = buflen ? 1 : 0;
1541       break;
1542 
1543     default:
1544       rc = GPG_ERR_INV_OP;
1545     }
1546 
1547   return rc;
1548 }
1549 
1550 
1551 /* Return information about the cipher handle H.  CMD is the kind of
1552  * information requested.
1553  *
1554  * CMD may be one of:
1555  *
1556  *  GCRYCTL_GET_TAGLEN:
1557  *      Return the length of the tag for an AE algorithm mode.  An
1558  *      error is returned for modes which do not support a tag.
1559  *      BUFFER must be given as NULL.  On success the result is stored
1560  *      at NBYTES.  The taglen is returned in bytes.
1561  *
1562  * The function returns 0 on success or an error code.
1563  */
1564 gcry_err_code_t
_gcry_cipher_info(gcry_cipher_hd_t h,int cmd,void * buffer,size_t * nbytes)1565 _gcry_cipher_info (gcry_cipher_hd_t h, int cmd, void *buffer, size_t *nbytes)
1566 {
1567   gcry_err_code_t rc = 0;
1568 
1569   switch (cmd)
1570     {
1571     case GCRYCTL_GET_TAGLEN:
1572       if (!h || buffer || !nbytes)
1573 	rc = GPG_ERR_INV_ARG;
1574       else
1575 	{
1576           switch (h->mode)
1577             {
1578             case GCRY_CIPHER_MODE_OCB:
1579               *nbytes = h->u_mode.ocb.taglen;
1580               break;
1581 
1582             case GCRY_CIPHER_MODE_CCM:
1583               *nbytes = h->u_mode.ccm.authlen;
1584               break;
1585 
1586             case GCRY_CIPHER_MODE_EAX:
1587               *nbytes = h->spec->blocksize;
1588               break;
1589 
1590             case GCRY_CIPHER_MODE_GCM:
1591               *nbytes = GCRY_GCM_BLOCK_LEN;
1592               break;
1593 
1594             case GCRY_CIPHER_MODE_POLY1305:
1595               *nbytes = POLY1305_TAGLEN;
1596               break;
1597 
1598             default:
1599               rc = GPG_ERR_INV_CIPHER_MODE;
1600               break;
1601             }
1602         }
1603       break;
1604 
1605     default:
1606       rc = GPG_ERR_INV_OP;
1607     }
1608 
1609   return rc;
1610 }
1611 
1612 /* Return information about the given cipher algorithm ALGO.
1613 
1614    WHAT select the kind of information returned:
1615 
1616     GCRYCTL_GET_KEYLEN:
1617   	Return the length of the key.  If the algorithm ALGO
1618   	supports multiple key lengths, the maximum supported key length
1619   	is returned.  The key length is returned as number of octets.
1620   	BUFFER and NBYTES must be zero.
1621 
1622     GCRYCTL_GET_BLKLEN:
1623   	Return the blocklength of the algorithm ALGO counted in octets.
1624   	BUFFER and NBYTES must be zero.
1625 
1626     GCRYCTL_TEST_ALGO:
1627   	Returns 0 if the specified algorithm ALGO is available for use.
1628   	BUFFER and NBYTES must be zero.
1629 
1630    Note: Because this function is in most cases used to return an
1631    integer value, we can make it easier for the caller to just look at
1632    the return value.  The caller will in all cases consult the value
1633    and thereby detecting whether a error occurred or not (i.e. while
1634    checking the block size)
1635  */
1636 gcry_err_code_t
_gcry_cipher_algo_info(int algo,int what,void * buffer,size_t * nbytes)1637 _gcry_cipher_algo_info (int algo, int what, void *buffer, size_t *nbytes)
1638 {
1639   gcry_err_code_t rc = 0;
1640   unsigned int ui;
1641 
1642   switch (what)
1643     {
1644     case GCRYCTL_GET_KEYLEN:
1645       if (buffer || (! nbytes))
1646 	rc = GPG_ERR_CIPHER_ALGO;
1647       else
1648 	{
1649 	  ui = cipher_get_keylen (algo);
1650 	  if ((ui > 0) && (ui <= 512))
1651 	    *nbytes = (size_t) ui / 8;
1652 	  else
1653 	    /* The only reason for an error is an invalid algo.  */
1654 	    rc = GPG_ERR_CIPHER_ALGO;
1655 	}
1656       break;
1657 
1658     case GCRYCTL_GET_BLKLEN:
1659       if (buffer || (! nbytes))
1660 	rc = GPG_ERR_CIPHER_ALGO;
1661       else
1662 	{
1663 	  ui = cipher_get_blocksize (algo);
1664 	  if ((ui > 0) && (ui < 10000))
1665 	    *nbytes = ui;
1666 	  else
1667             {
1668               /* The only reason is an invalid algo or a strange
1669                  blocksize.  */
1670               rc = GPG_ERR_CIPHER_ALGO;
1671             }
1672 	}
1673       break;
1674 
1675     case GCRYCTL_TEST_ALGO:
1676       if (buffer || nbytes)
1677 	rc = GPG_ERR_INV_ARG;
1678       else
1679 	rc = check_cipher_algo (algo);
1680       break;
1681 
1682       default:
1683 	rc = GPG_ERR_INV_OP;
1684     }
1685 
1686   return rc;
1687 }
1688 
1689 
1690 /* This function returns length of the key for algorithm ALGO.  If the
1691    algorithm supports multiple key lengths, the maximum supported key
1692    length is returned.  On error 0 is returned.  The key length is
1693    returned as number of octets.
1694 
1695    This is a convenience functions which should be preferred over
1696    gcry_cipher_algo_info because it allows for proper type
1697    checking.  */
1698 size_t
_gcry_cipher_get_algo_keylen(int algo)1699 _gcry_cipher_get_algo_keylen (int algo)
1700 {
1701   size_t n;
1702 
1703   if (_gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &n))
1704     n = 0;
1705   return n;
1706 }
1707 
1708 
1709 /* This functions returns the blocklength of the algorithm ALGO
1710    counted in octets.  On error 0 is returned.
1711 
1712    This is a convenience functions which should be preferred over
1713    gcry_cipher_algo_info because it allows for proper type
1714    checking.  */
1715 size_t
_gcry_cipher_get_algo_blklen(int algo)1716 _gcry_cipher_get_algo_blklen (int algo)
1717 {
1718   size_t n;
1719 
1720   if (_gcry_cipher_algo_info( algo, GCRYCTL_GET_BLKLEN, NULL, &n))
1721     n = 0;
1722   return n;
1723 }
1724 
1725 
1726 /* Explicitly initialize this module.  */
1727 gcry_err_code_t
_gcry_cipher_init(void)1728 _gcry_cipher_init (void)
1729 {
1730   if (fips_mode())
1731     {
1732       /* disable algorithms that are disallowed in fips */
1733       int idx;
1734       gcry_cipher_spec_t *spec;
1735 
1736       for (idx = 0; (spec = cipher_list[idx]); idx++)
1737         if (!spec->flags.fips)
1738           spec->flags.disabled = 1;
1739     }
1740 
1741   return 0;
1742 }
1743 
1744 
1745 /* Run the selftests for cipher algorithm ALGO with optional reporting
1746    function REPORT.  */
1747 gpg_error_t
_gcry_cipher_selftest(int algo,int extended,selftest_report_func_t report)1748 _gcry_cipher_selftest (int algo, int extended, selftest_report_func_t report)
1749 {
1750   gcry_err_code_t ec = 0;
1751   gcry_cipher_spec_t *spec;
1752 
1753   spec = spec_from_algo (algo);
1754   if (spec && !spec->flags.disabled && spec->selftest)
1755     ec = spec->selftest (algo, extended, report);
1756   else
1757     {
1758       ec = GPG_ERR_CIPHER_ALGO;
1759       if (report)
1760         report ("cipher", algo, "module",
1761                 (spec && !spec->flags.disabled)?
1762                 "no selftest available" :
1763                 spec? "algorithm disabled" : "algorithm not found");
1764     }
1765 
1766   return gpg_error (ec);
1767 }
1768