~hamo/ubuntu/precise/grub2/grub2.hi_res

« back to all changes in this revision

Viewing changes to grub-core/lib/libgcrypt/cipher/cipher.c

  • Committer: Bazaar Package Importer
  • Author(s): Colin Watson, Colin Watson, Robert Millan, Updated translations
  • Date: 2010-11-22 12:24:56 UTC
  • mfrom: (1.26.4 upstream) (17.3.36 sid)
  • mto: (17.3.43 sid)
  • mto: This revision was merged to the branch mainline in revision 89.
  • Revision ID: james.westby@ubuntu.com-20101122122456-y82z3sfb7k4zfdcc
Tags: 1.99~20101122-1
[ Colin Watson ]
* New Bazaar snapshot.  Too many changes to list in full, but some of the
  more user-visible ones are as follows:
  - GRUB script:
    + Function parameters, "break", "continue", "shift", "setparams",
      "return", and "!".
    + "export" command supports multiple variable names.
    + Multi-line quoted strings support.
    + Wildcard expansion.
  - sendkey support.
  - USB hotunplugging and USB serial support.
  - Rename CD-ROM to cd on BIOS.
  - Add new --boot-directory option to grub-install, grub-reboot, and
    grub-set-default; the old --root-directory option is still accepted
    but was often confusing.
  - Basic btrfs detection/UUID support (but no file reading yet).
  - bash-completion for utilities.
  - If a device is listed in device.map, always assume that it is
    BIOS-visible rather than using extra layers such as LVM or RAID.
  - Add grub-mknetdir script (closes: #550658).
  - Remove deprecated "root" command.
  - Handle RAID devices containing virtio components.
  - GRUB Legacy configuration file support (via grub-menulst2cfg).
  - Keyboard layout support (via grub-mklayout and grub-kbdcomp).
  - Check generated grub.cfg for syntax errors before saving.
  - Pause execution for at most ten seconds if any errors are displayed,
    so that the user has a chance to see them.
  - Support submenus.
  - Write embedding zone using Reed-Solomon, so that it's robust against
    being partially overwritten (closes: #550702, #591416, #593347).
  - GRUB_DISABLE_LINUX_RECOVERY and GRUB_DISABLE_NETBSD_RECOVERY merged
    into a single GRUB_DISABLE_RECOVERY variable.
  - Fix loader memory allocation failure (closes: #551627).
  - Don't call savedefault on recovery entries (closes: #589325).
  - Support triple-indirect blocks on ext2 (closes: #543924).
  - Recognise DDF1 fake RAID (closes: #603354).

[ Robert Millan ]
* Use dpkg architecture wildcards.

[ Updated translations ]
* Slovenian (Vanja Cvelbar).  Closes: #604003
* Dzongkha (dawa pemo via Tenzin Dendup).  Closes: #604102

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* cipher.c  -  cipher dispatcher
 
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
 
3
 *               2005, 2007, 2008 Free Software Foundation, Inc.
 
4
 *
 
5
 * This file is part of Libgcrypt.
 
6
 *
 
7
 * Libgcrypt is free software; you can redistribute it and/or modify
 
8
 * it under the terms of the GNU Lesser general Public License as
 
9
 * published by the Free Software Foundation; either version 2.1 of
 
10
 * the License, or (at your option) any later version.
 
11
 *
 
12
 * Libgcrypt is distributed in the hope that it will be useful,
 
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
 * GNU Lesser General Public License for more details.
 
16
 *
 
17
 * You should have received a copy of the GNU Lesser General Public
 
18
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 
19
 */
 
20
 
 
21
#include <config.h>
 
22
#include <stdio.h>
 
23
#include <stdlib.h>
 
24
#include <string.h>
 
25
#include <errno.h>
 
26
 
 
27
#include "g10lib.h"
 
28
#include "cipher.h"
 
29
#include "ath.h"
 
30
 
 
31
#define MAX_BLOCKSIZE 16
 
32
#define TABLE_SIZE 14
 
33
#define CTX_MAGIC_NORMAL 0x24091964
 
34
#define CTX_MAGIC_SECURE 0x46919042
 
35
 
 
36
#undef NEED_16BYTE_ALIGNED_CONTEXT
 
37
#if defined (__i386__) && SIZEOF_UNSIGNED_LONG == 4 && defined (__GNUC__)
 
38
#define NEED_16BYTE_ALIGNED_CONTEXT 1
 
39
#endif
 
40
 
 
41
/* A dummy extraspec so that we do not need to tests the extraspec
 
42
   field from the module specification against NULL and instead
 
43
   directly test the respective fields of extraspecs.  */
 
44
static cipher_extra_spec_t dummy_extra_spec;
 
45
 
 
46
/* This is the list of the default ciphers, which are included in
 
47
   libgcrypt.  */
 
48
static struct cipher_table_entry
 
49
{
 
50
  gcry_cipher_spec_t *cipher;
 
51
  cipher_extra_spec_t *extraspec;
 
52
  unsigned int algorithm;
 
53
  int fips_allowed;
 
54
} cipher_table[] =
 
55
  {
 
56
#if USE_BLOWFISH
 
57
    { &_gcry_cipher_spec_blowfish,
 
58
      &dummy_extra_spec,                  GCRY_CIPHER_BLOWFISH },
 
59
#endif
 
60
#if USE_DES
 
61
    { &_gcry_cipher_spec_des,       
 
62
      &dummy_extra_spec,                  GCRY_CIPHER_DES },
 
63
    { &_gcry_cipher_spec_tripledes,
 
64
      &_gcry_cipher_extraspec_tripledes,  GCRY_CIPHER_3DES, 1 },
 
65
#endif
 
66
#if USE_ARCFOUR
 
67
    { &_gcry_cipher_spec_arcfour,    
 
68
      &dummy_extra_spec,                  GCRY_CIPHER_ARCFOUR },
 
69
#endif
 
70
#if USE_CAST5
 
71
    { &_gcry_cipher_spec_cast5,      
 
72
      &dummy_extra_spec,                  GCRY_CIPHER_CAST5 },
 
73
#endif
 
74
#if USE_AES
 
75
    { &_gcry_cipher_spec_aes,        
 
76
      &_gcry_cipher_extraspec_aes,        GCRY_CIPHER_AES,    1 },
 
77
    { &_gcry_cipher_spec_aes192,     
 
78
      &_gcry_cipher_extraspec_aes192,     GCRY_CIPHER_AES192, 1 },
 
79
    { &_gcry_cipher_spec_aes256,     
 
80
      &_gcry_cipher_extraspec_aes256,     GCRY_CIPHER_AES256, 1 },
 
81
#endif
 
82
#if USE_TWOFISH
 
83
    { &_gcry_cipher_spec_twofish,
 
84
      &dummy_extra_spec,                  GCRY_CIPHER_TWOFISH },
 
85
    { &_gcry_cipher_spec_twofish128,     
 
86
      &dummy_extra_spec,                  GCRY_CIPHER_TWOFISH128 },
 
87
#endif
 
88
#if USE_SERPENT
 
89
    { &_gcry_cipher_spec_serpent128, 
 
90
      &dummy_extra_spec,                  GCRY_CIPHER_SERPENT128 },
 
91
    { &_gcry_cipher_spec_serpent192,
 
92
      &dummy_extra_spec,                  GCRY_CIPHER_SERPENT192 },
 
93
    { &_gcry_cipher_spec_serpent256, 
 
94
      &dummy_extra_spec,                  GCRY_CIPHER_SERPENT256 },
 
95
#endif
 
96
#if USE_RFC2268
 
97
    { &_gcry_cipher_spec_rfc2268_40,
 
98
      &dummy_extra_spec,                  GCRY_CIPHER_RFC2268_40 },
 
99
#endif
 
100
#if USE_SEED
 
101
    { &_gcry_cipher_spec_seed, 
 
102
      &dummy_extra_spec,                  GCRY_CIPHER_SEED },
 
103
#endif
 
104
#if USE_CAMELLIA
 
105
    { &_gcry_cipher_spec_camellia128,
 
106
      &dummy_extra_spec,                  GCRY_CIPHER_CAMELLIA128 },
 
107
    { &_gcry_cipher_spec_camellia192, 
 
108
      &dummy_extra_spec,                  GCRY_CIPHER_CAMELLIA192 },
 
109
    { &_gcry_cipher_spec_camellia256,
 
110
      &dummy_extra_spec,                  GCRY_CIPHER_CAMELLIA256 },
 
111
#endif
 
112
    { NULL                    }
 
113
  };
 
114
 
 
115
/* List of registered ciphers.  */
 
116
static gcry_module_t ciphers_registered;
 
117
 
 
118
/* This is the lock protecting CIPHERS_REGISTERED.  */
 
119
static ath_mutex_t ciphers_registered_lock = ATH_MUTEX_INITIALIZER;
 
120
 
 
121
/* Flag to check wether the default ciphers have already been
 
122
   registered.  */
 
123
static int default_ciphers_registered;
 
124
 
 
125
/* Convenient macro for registering the default ciphers.  */
 
126
#define REGISTER_DEFAULT_CIPHERS                   \
 
127
  do                                               \
 
128
    {                                              \
 
129
      ath_mutex_lock (&ciphers_registered_lock);   \
 
130
      if (! default_ciphers_registered)            \
 
131
        {                                          \
 
132
          cipher_register_default ();              \
 
133
          default_ciphers_registered = 1;          \
 
134
        }                                          \
 
135
      ath_mutex_unlock (&ciphers_registered_lock); \
 
136
    }                                              \
 
137
  while (0)
 
138
 
 
139
 
 
140
/* A VIA processor with the Padlock engine requires an alignment of
 
141
   most data on a 16 byte boundary.  Because we trick out the compiler
 
142
   while allocating the context, the align attribute as used in
 
143
   rijndael.c does not work on its own.  Thus we need to make sure
 
144
   that the entire context structure is a aligned on that boundary.
 
145
   We achieve this by defining a new type and use that instead of our
 
146
   usual alignment type.  */
 
147
typedef union 
 
148
{
 
149
  PROPERLY_ALIGNED_TYPE foo;
 
150
#ifdef NEED_16BYTE_ALIGNED_CONTEXT
 
151
  char bar[16] __attribute__ ((aligned (16)));
 
152
#endif  
 
153
  char c[1];
 
154
} cipher_context_alignment_t;
 
155
 
 
156
 
 
157
/* The handle structure.  */
 
158
struct gcry_cipher_handle
 
159
{
 
160
  int magic;
 
161
  size_t actual_handle_size;     /* Allocated size of this handle. */
 
162
  size_t handle_offset;          /* Offset to the malloced block.  */
 
163
  gcry_cipher_spec_t *cipher;
 
164
  cipher_extra_spec_t *extraspec;
 
165
  gcry_module_t module;
 
166
 
 
167
  /* The algorithm id.  This is a hack required because the module
 
168
     interface does not easily allow to retrieve this value. */
 
169
  int algo;  
 
170
 
 
171
  /* A structure with function pointers for bulk operations.  Due to
 
172
     limitations of the module system (we don't want to change the
 
173
     API) we need to keep these function pointers here.  The cipher
 
174
     open function intializes them and the actual encryption routines
 
175
     use them if they are not NULL.  */
 
176
  struct {
 
177
    void (*cfb_enc)(void *context, unsigned char *iv, 
 
178
                    void *outbuf_arg, const void *inbuf_arg,
 
179
                    unsigned int nblocks);
 
180
    void (*cfb_dec)(void *context, unsigned char *iv, 
 
181
                    void *outbuf_arg, const void *inbuf_arg,
 
182
                    unsigned int nblocks);
 
183
    void (*cbc_enc)(void *context, unsigned char *iv, 
 
184
                    void *outbuf_arg, const void *inbuf_arg,
 
185
                    unsigned int nblocks, int cbc_mac);
 
186
    void (*cbc_dec)(void *context, unsigned char *iv, 
 
187
                    void *outbuf_arg, const void *inbuf_arg,
 
188
                    unsigned int nblocks);
 
189
  } bulk;
 
190
 
 
191
 
 
192
  int mode;
 
193
  unsigned int flags;
 
194
 
 
195
  /* The initialization vector.  To help code optimization we make
 
196
     sure that it is aligned on an unsigned long and u32 boundary.  */
 
197
  union {
 
198
    unsigned long dummy_iv;         
 
199
    u32 dummy_u32_iv;
 
200
    unsigned char iv[MAX_BLOCKSIZE];    
 
201
  } u_iv;
 
202
 
 
203
  unsigned char lastiv[MAX_BLOCKSIZE];
 
204
  int unused;  /* Number of unused bytes in the IV. */
 
205
 
 
206
  unsigned char ctr[MAX_BLOCKSIZE];     /* For Counter (CTR) mode. */
 
207
 
 
208
 
 
209
  /* What follows are two contexts of the cipher in use.  The first
 
210
     one needs to be aligned well enough for the cipher operation
 
211
     whereas the second one is a copy created by cipher_setkey and
 
212
     used by cipher_reset.  That second copy has no need for proper
 
213
     aligment because it is only accessed by memcpy.  */
 
214
  cipher_context_alignment_t context;
 
215
};
 
216
 
 
217
 
 
218
 
 
219
/* These dummy functions are used in case a cipher implementation
 
220
   refuses to provide it's own functions.  */
 
221
 
 
222
static gcry_err_code_t
 
223
dummy_setkey (void *c, const unsigned char *key, unsigned int keylen)
 
224
{
 
225
  (void)c; 
 
226
  (void)key;
 
227
  (void)keylen;
 
228
  return GPG_ERR_NO_ERROR;
 
229
}
 
230
 
 
231
static void
 
232
dummy_encrypt_block (void *c,
 
233
                     unsigned char *outbuf, const unsigned char *inbuf)
 
234
{
 
235
  (void)c;
 
236
  (void)outbuf;
 
237
  (void)inbuf;
 
238
  BUG();
 
239
}
 
240
 
 
241
static void
 
242
dummy_decrypt_block (void *c,
 
243
                     unsigned char *outbuf, const unsigned char *inbuf)
 
244
{
 
245
  (void)c;
 
246
  (void)outbuf;
 
247
  (void)inbuf;
 
248
  BUG();
 
249
}
 
250
 
 
251
static void
 
252
dummy_encrypt_stream (void *c,
 
253
                      unsigned char *outbuf, const unsigned char *inbuf,
 
254
                      unsigned int n)
 
255
{
 
256
  (void)c;
 
257
  (void)outbuf;
 
258
  (void)inbuf;
 
259
  (void)n;
 
260
  BUG();
 
261
}
 
262
 
 
263
static void
 
264
dummy_decrypt_stream (void *c,
 
265
                      unsigned char *outbuf, const unsigned char *inbuf,
 
266
                      unsigned int n)
 
267
{
 
268
  (void)c;
 
269
  (void)outbuf;
 
270
  (void)inbuf;
 
271
  (void)n;
 
272
  BUG();
 
273
}
 
274
 
 
275
 
 
276
/* Internal function.  Register all the ciphers included in
 
277
   CIPHER_TABLE.  Note, that this function gets only used by the macro
 
278
   REGISTER_DEFAULT_CIPHERS which protects it using a mutex. */
 
279
static void
 
280
cipher_register_default (void)
 
281
{
 
282
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
283
  int i;
 
284
  
 
285
  for (i = 0; !err && cipher_table[i].cipher; i++)
 
286
    {
 
287
      if (! cipher_table[i].cipher->setkey)
 
288
        cipher_table[i].cipher->setkey = dummy_setkey;
 
289
      if (! cipher_table[i].cipher->encrypt)
 
290
        cipher_table[i].cipher->encrypt = dummy_encrypt_block;
 
291
      if (! cipher_table[i].cipher->decrypt)
 
292
        cipher_table[i].cipher->decrypt = dummy_decrypt_block;
 
293
      if (! cipher_table[i].cipher->stencrypt)
 
294
        cipher_table[i].cipher->stencrypt = dummy_encrypt_stream;
 
295
      if (! cipher_table[i].cipher->stdecrypt)
 
296
        cipher_table[i].cipher->stdecrypt = dummy_decrypt_stream;
 
297
 
 
298
      if ( fips_mode () && !cipher_table[i].fips_allowed )
 
299
        continue;
 
300
 
 
301
      err = _gcry_module_add (&ciphers_registered,
 
302
                              cipher_table[i].algorithm,
 
303
                              (void *) cipher_table[i].cipher,
 
304
                              (void *) cipher_table[i].extraspec,
 
305
                              NULL);
 
306
    }
 
307
 
 
308
  if (err)
 
309
    BUG ();
 
310
}
 
311
 
 
312
/* Internal callback function.  Used via _gcry_module_lookup.  */
 
313
static int
 
314
gcry_cipher_lookup_func_name (void *spec, void *data)
 
315
{
 
316
  gcry_cipher_spec_t *cipher = (gcry_cipher_spec_t *) spec;
 
317
  char *name = (char *) data;
 
318
  const char **aliases = cipher->aliases;
 
319
  int i, ret = ! stricmp (name, cipher->name);
 
320
 
 
321
  if (aliases)
 
322
    for (i = 0; aliases[i] && (! ret); i++)
 
323
      ret = ! stricmp (name, aliases[i]);
 
324
 
 
325
  return ret;
 
326
}
 
327
 
 
328
/* Internal callback function.  Used via _gcry_module_lookup.  */
 
329
static int
 
330
gcry_cipher_lookup_func_oid (void *spec, void *data)
 
331
{
 
332
  gcry_cipher_spec_t *cipher = (gcry_cipher_spec_t *) spec;
 
333
  char *oid = (char *) data;
 
334
  gcry_cipher_oid_spec_t *oid_specs = cipher->oids;
 
335
  int ret = 0, i;
 
336
 
 
337
  if (oid_specs)
 
338
    for (i = 0; oid_specs[i].oid && (! ret); i++)
 
339
      if (! stricmp (oid, oid_specs[i].oid))
 
340
        ret = 1;
 
341
 
 
342
  return ret;
 
343
}
 
344
 
 
345
/* Internal function.  Lookup a cipher entry by it's name.  */
 
346
static gcry_module_t
 
347
gcry_cipher_lookup_name (const char *name)
 
348
{
 
349
  gcry_module_t cipher;
 
350
 
 
351
  cipher = _gcry_module_lookup (ciphers_registered, (void *) name,
 
352
                                gcry_cipher_lookup_func_name);
 
353
 
 
354
  return cipher;
 
355
}
 
356
 
 
357
/* Internal function.  Lookup a cipher entry by it's oid.  */
 
358
static gcry_module_t
 
359
gcry_cipher_lookup_oid (const char *oid)
 
360
{
 
361
  gcry_module_t cipher;
 
362
 
 
363
  cipher = _gcry_module_lookup (ciphers_registered, (void *) oid,
 
364
                                gcry_cipher_lookup_func_oid);
 
365
 
 
366
  return cipher;
 
367
}
 
368
 
 
369
/* Register a new cipher module whose specification can be found in
 
370
   CIPHER.  On success, a new algorithm ID is stored in ALGORITHM_ID
 
371
   and a pointer representhing this module is stored in MODULE.  */
 
372
gcry_error_t
 
373
_gcry_cipher_register (gcry_cipher_spec_t *cipher,
 
374
                       cipher_extra_spec_t *extraspec,
 
375
                       int *algorithm_id,
 
376
                       gcry_module_t *module)
 
377
{
 
378
  gcry_err_code_t err = 0;
 
379
  gcry_module_t mod;
 
380
 
 
381
  /* We do not support module loading in fips mode.  */
 
382
  if (fips_mode ())
 
383
    return gpg_error (GPG_ERR_NOT_SUPPORTED);
 
384
 
 
385
  ath_mutex_lock (&ciphers_registered_lock);
 
386
  err = _gcry_module_add (&ciphers_registered, 0,
 
387
                          (void *)cipher, 
 
388
                          (void *)(extraspec? extraspec : &dummy_extra_spec), 
 
389
                          &mod);
 
390
  ath_mutex_unlock (&ciphers_registered_lock);
 
391
 
 
392
  if (! err)
 
393
    {
 
394
      *module = mod;
 
395
      *algorithm_id = mod->mod_id;
 
396
    }
 
397
 
 
398
  return gcry_error (err);
 
399
}
 
400
 
 
401
/* Unregister the cipher identified by MODULE, which must have been
 
402
   registered with gcry_cipher_register.  */
 
403
void
 
404
gcry_cipher_unregister (gcry_module_t module)
 
405
{
 
406
  ath_mutex_lock (&ciphers_registered_lock);
 
407
  _gcry_module_release (module);
 
408
  ath_mutex_unlock (&ciphers_registered_lock);
 
409
}
 
410
 
 
411
/* Locate the OID in the oid table and return the index or -1 when not
 
412
   found.  An opitonal "oid." or "OID." prefix in OID is ignored, the
 
413
   OID is expected to be in standard IETF dotted notation.  The
 
414
   internal algorithm number is returned in ALGORITHM unless it
 
415
   ispassed as NULL.  A pointer to the specification of the module
 
416
   implementing this algorithm is return in OID_SPEC unless passed as
 
417
   NULL.*/
 
418
static int 
 
419
search_oid (const char *oid, int *algorithm, gcry_cipher_oid_spec_t *oid_spec)
 
420
{
 
421
  gcry_module_t module;
 
422
  int ret = 0;
 
423
 
 
424
  if (oid && ((! strncmp (oid, "oid.", 4))
 
425
              || (! strncmp (oid, "OID.", 4))))
 
426
    oid += 4;
 
427
 
 
428
  module = gcry_cipher_lookup_oid (oid);
 
429
  if (module)
 
430
    {
 
431
      gcry_cipher_spec_t *cipher = module->spec;
 
432
      int i;
 
433
 
 
434
      for (i = 0; cipher->oids[i].oid && !ret; i++)
 
435
        if (! stricmp (oid, cipher->oids[i].oid))
 
436
          {
 
437
            if (algorithm)
 
438
              *algorithm = module->mod_id;
 
439
            if (oid_spec)
 
440
              *oid_spec = cipher->oids[i];
 
441
            ret = 1;
 
442
          }
 
443
      _gcry_module_release (module);
 
444
    }
 
445
 
 
446
  return ret;
 
447
}
 
448
 
 
449
/* Map STRING to the cipher algorithm identifier.  Returns the
 
450
   algorithm ID of the cipher for the given name or 0 if the name is
 
451
   not known.  It is valid to pass NULL for STRING which results in a
 
452
   return value of 0. */
 
453
int
 
454
gcry_cipher_map_name (const char *string)
 
455
{
 
456
  gcry_module_t cipher;
 
457
  int ret, algorithm = 0;
 
458
 
 
459
  if (! string)
 
460
    return 0;
 
461
 
 
462
  REGISTER_DEFAULT_CIPHERS;
 
463
 
 
464
  /* If the string starts with a digit (optionally prefixed with
 
465
     either "OID." or "oid."), we first look into our table of ASN.1
 
466
     object identifiers to figure out the algorithm */
 
467
 
 
468
  ath_mutex_lock (&ciphers_registered_lock);
 
469
 
 
470
  ret = search_oid (string, &algorithm, NULL);
 
471
  if (! ret)
 
472
    {
 
473
      cipher = gcry_cipher_lookup_name (string);
 
474
      if (cipher)
 
475
        {
 
476
          algorithm = cipher->mod_id;
 
477
          _gcry_module_release (cipher);
 
478
        }
 
479
    }
 
480
 
 
481
  ath_mutex_unlock (&ciphers_registered_lock);
 
482
  
 
483
  return algorithm;
 
484
}
 
485
 
 
486
 
 
487
/* Given a STRING with an OID in dotted decimal notation, this
 
488
   function returns the cipher mode (GCRY_CIPHER_MODE_*) associated
 
489
   with that OID or 0 if no mode is known.  Passing NULL for string
 
490
   yields a return value of 0. */
 
491
int
 
492
gcry_cipher_mode_from_oid (const char *string)
 
493
{
 
494
  gcry_cipher_oid_spec_t oid_spec;
 
495
  int ret = 0, mode = 0;
 
496
 
 
497
  if (!string)
 
498
    return 0;
 
499
 
 
500
  ath_mutex_lock (&ciphers_registered_lock);
 
501
  ret = search_oid (string, NULL, &oid_spec);
 
502
  if (ret)
 
503
    mode = oid_spec.mode;
 
504
  ath_mutex_unlock (&ciphers_registered_lock);
 
505
 
 
506
  return mode;
 
507
}
 
508
 
 
509
 
 
510
/* Map the cipher algorithm whose ID is contained in ALGORITHM to a
 
511
   string representation of the algorithm name.  For unknown algorithm
 
512
   IDs this function returns "?".  */
 
513
static const char *
 
514
cipher_algo_to_string (int algorithm)
 
515
{
 
516
  gcry_module_t cipher;
 
517
  const char *name;
 
518
 
 
519
  REGISTER_DEFAULT_CIPHERS;
 
520
 
 
521
  ath_mutex_lock (&ciphers_registered_lock);
 
522
  cipher = _gcry_module_lookup_id (ciphers_registered, algorithm);
 
523
  if (cipher)
 
524
    {
 
525
      name = ((gcry_cipher_spec_t *) cipher->spec)->name;
 
526
      _gcry_module_release (cipher);
 
527
    }
 
528
  else
 
529
    name = "?";
 
530
  ath_mutex_unlock (&ciphers_registered_lock);
 
531
 
 
532
  return name;
 
533
}
 
534
 
 
535
/* Map the cipher algorithm identifier ALGORITHM to a string
 
536
   representing this algorithm.  This string is the default name as
 
537
   used by Libgcrypt.  An pointer to an empty string is returned for
 
538
   an unknown algorithm.  NULL is never returned. */
 
539
const char *
 
540
gcry_cipher_algo_name (int algorithm)
 
541
{
 
542
  return cipher_algo_to_string (algorithm);
 
543
}
 
544
 
 
545
 
 
546
/* Flag the cipher algorithm with the identifier ALGORITHM as
 
547
   disabled.  There is no error return, the function does nothing for
 
548
   unknown algorithms.  Disabled algorithms are vitually not available
 
549
   in Libgcrypt. */
 
550
static void
 
551
disable_cipher_algo (int algorithm)
 
552
{
 
553
  gcry_module_t cipher;
 
554
 
 
555
  REGISTER_DEFAULT_CIPHERS;
 
556
 
 
557
  ath_mutex_lock (&ciphers_registered_lock);
 
558
  cipher = _gcry_module_lookup_id (ciphers_registered, algorithm);
 
559
  if (cipher)
 
560
    {
 
561
      if (! (cipher->flags & FLAG_MODULE_DISABLED))
 
562
        cipher->flags |= FLAG_MODULE_DISABLED;
 
563
      _gcry_module_release (cipher);
 
564
    }
 
565
  ath_mutex_unlock (&ciphers_registered_lock);
 
566
}
 
567
 
 
568
 
 
569
/* Return 0 if the cipher algorithm with identifier ALGORITHM is
 
570
   available. Returns a basic error code value if it is not
 
571
   available.  */
 
572
static gcry_err_code_t
 
573
check_cipher_algo (int algorithm)
 
574
{
 
575
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
576
  gcry_module_t cipher;
 
577
 
 
578
  REGISTER_DEFAULT_CIPHERS;
 
579
 
 
580
  ath_mutex_lock (&ciphers_registered_lock);
 
581
  cipher = _gcry_module_lookup_id (ciphers_registered, algorithm);
 
582
  if (cipher)
 
583
    {
 
584
      if (cipher->flags & FLAG_MODULE_DISABLED)
 
585
        err = GPG_ERR_CIPHER_ALGO;
 
586
      _gcry_module_release (cipher);
 
587
    }
 
588
  else
 
589
    err = GPG_ERR_CIPHER_ALGO;
 
590
  ath_mutex_unlock (&ciphers_registered_lock);
 
591
  
 
592
  return err;
 
593
}
 
594
 
 
595
 
 
596
/* Return the standard length of the key for the cipher algorithm with
 
597
   the identifier ALGORITHM.  This function expects a valid algorithm
 
598
   and will abort if the algorithm is not available or the length of
 
599
   the key is not known. */
 
600
static unsigned int
 
601
cipher_get_keylen (int algorithm)
 
602
{
 
603
  gcry_module_t cipher;
 
604
  unsigned len = 0;
 
605
 
 
606
  REGISTER_DEFAULT_CIPHERS;
 
607
 
 
608
  ath_mutex_lock (&ciphers_registered_lock);
 
609
  cipher = _gcry_module_lookup_id (ciphers_registered, algorithm);
 
610
  if (cipher)
 
611
    {
 
612
      len = ((gcry_cipher_spec_t *) cipher->spec)->keylen;
 
613
      if (!len)
 
614
        log_bug ("cipher %d w/o key length\n", algorithm);
 
615
      _gcry_module_release (cipher);
 
616
    }
 
617
  else
 
618
    log_bug ("cipher %d not found\n", algorithm);
 
619
  ath_mutex_unlock (&ciphers_registered_lock);
 
620
 
 
621
  return len;
 
622
}
 
623
 
 
624
/* Return the block length of the cipher algorithm with the identifier
 
625
   ALGORITHM.  This function expects a valid algorithm and will abort
 
626
   if the algorithm is not available or the length of the key is not
 
627
   known. */
 
628
static unsigned int
 
629
cipher_get_blocksize (int algorithm)
 
630
{
 
631
  gcry_module_t cipher;
 
632
  unsigned len = 0;
 
633
 
 
634
  REGISTER_DEFAULT_CIPHERS;
 
635
 
 
636
  ath_mutex_lock (&ciphers_registered_lock);
 
637
  cipher = _gcry_module_lookup_id (ciphers_registered, algorithm);
 
638
  if (cipher)
 
639
    {
 
640
      len = ((gcry_cipher_spec_t *) cipher->spec)->blocksize;
 
641
      if (! len)
 
642
          log_bug ("cipher %d w/o blocksize\n", algorithm);
 
643
      _gcry_module_release (cipher);
 
644
    }
 
645
  else
 
646
    log_bug ("cipher %d not found\n", algorithm);
 
647
  ath_mutex_unlock (&ciphers_registered_lock);
 
648
 
 
649
  return len;
 
650
}
 
651
 
 
652
 
 
653
/*
 
654
   Open a cipher handle for use with cipher algorithm ALGORITHM, using
 
655
   the cipher mode MODE (one of the GCRY_CIPHER_MODE_*) and return a
 
656
   handle in HANDLE.  Put NULL into HANDLE and return an error code if
 
657
   something goes wrong.  FLAGS may be used to modify the
 
658
   operation.  The defined flags are:
 
659
 
 
660
   GCRY_CIPHER_SECURE:  allocate all internal buffers in secure memory.
 
661
   GCRY_CIPHER_ENABLE_SYNC:  Enable the sync operation as used in OpenPGP.
 
662
   GCRY_CIPHER_CBC_CTS:  Enable CTS mode.
 
663
   GCRY_CIPHER_CBC_MAC:  Enable MAC mode.
 
664
 
 
665
   Values for these flags may be combined using OR.
 
666
 */
 
667
gcry_error_t
 
668
gcry_cipher_open (gcry_cipher_hd_t *handle,
 
669
                  int algo, int mode, unsigned int flags)
 
670
{
 
671
  int secure = (flags & GCRY_CIPHER_SECURE);
 
672
  gcry_cipher_spec_t *cipher = NULL;
 
673
  cipher_extra_spec_t *extraspec = NULL;
 
674
  gcry_module_t module = NULL;
 
675
  gcry_cipher_hd_t h = NULL;
 
676
  gcry_err_code_t err = 0;
 
677
 
 
678
  /* If the application missed to call the random poll function, we do
 
679
     it here to ensure that it is used once in a while. */
 
680
  _gcry_fast_random_poll ();
 
681
  
 
682
  REGISTER_DEFAULT_CIPHERS;
 
683
 
 
684
  /* Fetch the according module and check wether the cipher is marked
 
685
     available for use.  */
 
686
  ath_mutex_lock (&ciphers_registered_lock);
 
687
  module = _gcry_module_lookup_id (ciphers_registered, algo);
 
688
  if (module)
 
689
    {
 
690
      /* Found module.  */
 
691
 
 
692
      if (module->flags & FLAG_MODULE_DISABLED)
 
693
        {
 
694
          /* Not available for use.  */
 
695
          err = GPG_ERR_CIPHER_ALGO;
 
696
          _gcry_module_release (module);
 
697
        }
 
698
      else
 
699
        {
 
700
          cipher = (gcry_cipher_spec_t *) module->spec;
 
701
          extraspec = module->extraspec;
 
702
        }
 
703
    }
 
704
  else
 
705
    err = GPG_ERR_CIPHER_ALGO;
 
706
  ath_mutex_unlock (&ciphers_registered_lock);
 
707
 
 
708
  /* check flags */
 
709
  if ((! err)
 
710
      && ((flags & ~(0 
 
711
                     | GCRY_CIPHER_SECURE
 
712
                     | GCRY_CIPHER_ENABLE_SYNC
 
713
                     | GCRY_CIPHER_CBC_CTS
 
714
                     | GCRY_CIPHER_CBC_MAC))
 
715
          || (flags & GCRY_CIPHER_CBC_CTS & GCRY_CIPHER_CBC_MAC)))
 
716
    err = GPG_ERR_CIPHER_ALGO;
 
717
 
 
718
  /* check that a valid mode has been requested */
 
719
  if (! err)
 
720
    switch (mode)
 
721
      {
 
722
      case GCRY_CIPHER_MODE_ECB:
 
723
      case GCRY_CIPHER_MODE_CBC:
 
724
      case GCRY_CIPHER_MODE_CFB:
 
725
      case GCRY_CIPHER_MODE_OFB:
 
726
      case GCRY_CIPHER_MODE_CTR:
 
727
        if ((cipher->encrypt == dummy_encrypt_block)
 
728
            || (cipher->decrypt == dummy_decrypt_block))
 
729
          err = GPG_ERR_INV_CIPHER_MODE;
 
730
        break;
 
731
 
 
732
      case GCRY_CIPHER_MODE_STREAM:
 
733
        if ((cipher->stencrypt == dummy_encrypt_stream)
 
734
            || (cipher->stdecrypt == dummy_decrypt_stream))
 
735
          err = GPG_ERR_INV_CIPHER_MODE;
 
736
        break;
 
737
 
 
738
      case GCRY_CIPHER_MODE_NONE:
 
739
        /* This mode may be used for debugging.  It copies the main
 
740
           text verbatim to the ciphertext.  We do not allow this in
 
741
           fips mode or if no debug flag has been set.  */
 
742
        if (fips_mode () || !_gcry_get_debug_flag (0))
 
743
          err = GPG_ERR_INV_CIPHER_MODE;
 
744
        break;
 
745
 
 
746
      default:
 
747
        err = GPG_ERR_INV_CIPHER_MODE;
 
748
      }
 
749
 
 
750
  /* Perform selftest here and mark this with a flag in cipher_table?
 
751
     No, we should not do this as it takes too long.  Further it does
 
752
     not make sense to exclude algorithms with failing selftests at
 
753
     runtime: If a selftest fails there is something seriously wrong
 
754
     with the system and thus we better die immediately. */
 
755
 
 
756
  if (! err)
 
757
    {
 
758
      size_t size = (sizeof (*h)
 
759
                     + 2 * cipher->contextsize
 
760
                     - sizeof (cipher_context_alignment_t)
 
761
#ifdef NEED_16BYTE_ALIGNED_CONTEXT
 
762
                     + 15  /* Space for leading alignment gap.  */
 
763
#endif /*NEED_16BYTE_ALIGNED_CONTEXT*/
 
764
                     );
 
765
 
 
766
      if (secure)
 
767
        h = gcry_calloc_secure (1, size);
 
768
      else
 
769
        h = gcry_calloc (1, size);
 
770
 
 
771
      if (! h)
 
772
        err = gpg_err_code_from_errno (errno);
 
773
      else
 
774
        {
 
775
          size_t off = 0;
 
776
 
 
777
#ifdef NEED_16BYTE_ALIGNED_CONTEXT
 
778
          if ( ((unsigned long)h & 0x0f) )
 
779
            {
 
780
              /* The malloced block is not aligned on a 16 byte
 
781
                 boundary.  Correct for this.  */
 
782
              off = 16 - ((unsigned long)h & 0x0f);
 
783
              h = (void*)((char*)h + off);
 
784
            }
 
785
#endif /*NEED_16BYTE_ALIGNED_CONTEXT*/
 
786
 
 
787
          h->magic = secure ? CTX_MAGIC_SECURE : CTX_MAGIC_NORMAL;
 
788
          h->actual_handle_size = size - off;
 
789
          h->handle_offset = off;
 
790
          h->cipher = cipher;
 
791
          h->extraspec = extraspec;
 
792
          h->module = module;
 
793
          h->algo = algo;
 
794
          h->mode = mode;
 
795
          h->flags = flags;
 
796
 
 
797
          /* Setup bulk encryption routines.  */
 
798
          switch (algo)
 
799
            {
 
800
#ifdef USE_AES
 
801
            case GCRY_CIPHER_AES128:
 
802
            case GCRY_CIPHER_AES192:
 
803
            case GCRY_CIPHER_AES256:
 
804
              h->bulk.cfb_enc = _gcry_aes_cfb_enc;
 
805
              h->bulk.cfb_dec = _gcry_aes_cfb_dec;
 
806
              h->bulk.cbc_enc = _gcry_aes_cbc_enc;
 
807
              h->bulk.cbc_dec = _gcry_aes_cbc_dec;
 
808
              break;
 
809
#endif /*USE_AES*/
 
810
              
 
811
            default:
 
812
              break;
 
813
            }
 
814
        }
 
815
    }
 
816
 
 
817
  /* Done.  */
 
818
 
 
819
  if (err)
 
820
    {
 
821
      if (module)
 
822
        {
 
823
          /* Release module.  */
 
824
          ath_mutex_lock (&ciphers_registered_lock);
 
825
          _gcry_module_release (module);
 
826
          ath_mutex_unlock (&ciphers_registered_lock);
 
827
        }
 
828
    }
 
829
 
 
830
  *handle = err ? NULL : h;
 
831
 
 
832
  return gcry_error (err);
 
833
}
 
834
 
 
835
 
 
836
/* Release all resources associated with the cipher handle H. H may be
 
837
   NULL in which case this is a no-operation. */
 
838
void
 
839
gcry_cipher_close (gcry_cipher_hd_t h)
 
840
{
 
841
  size_t off;
 
842
 
 
843
  if (!h)
 
844
    return;
 
845
 
 
846
  if ((h->magic != CTX_MAGIC_SECURE)
 
847
      && (h->magic != CTX_MAGIC_NORMAL))
 
848
    _gcry_fatal_error(GPG_ERR_INTERNAL,
 
849
                      "gcry_cipher_close: already closed/invalid handle");
 
850
  else
 
851
    h->magic = 0;
 
852
 
 
853
  /* Release module.  */
 
854
  ath_mutex_lock (&ciphers_registered_lock);
 
855
  _gcry_module_release (h->module);
 
856
  ath_mutex_unlock (&ciphers_registered_lock);
 
857
 
 
858
  /* We always want to wipe out the memory even when the context has
 
859
     been allocated in secure memory.  The user might have disabled
 
860
     secure memory or is using his own implementation which does not
 
861
     do the wiping.  To accomplish this we need to keep track of the
 
862
     actual size of this structure because we have no way to known
 
863
     how large the allocated area was when using a standard malloc. */
 
864
  off = h->handle_offset;
 
865
  wipememory (h, h->actual_handle_size);
 
866
 
 
867
  gcry_free ((char*)h - off);
 
868
}
 
869
 
 
870
 
 
871
/* Set the key to be used for the encryption context C to KEY with
 
872
   length KEYLEN.  The length should match the required length. */
 
873
static gcry_error_t
 
874
cipher_setkey (gcry_cipher_hd_t c, byte *key, unsigned int keylen)
 
875
{
 
876
  gcry_err_code_t ret;
 
877
 
 
878
  ret = (*c->cipher->setkey) (&c->context.c, key, keylen);
 
879
  if (!ret)
 
880
    {
 
881
      /* Duplicate initial context.  */
 
882
      memcpy ((void *) ((char *) &c->context.c + c->cipher->contextsize),
 
883
              (void *) &c->context.c,
 
884
              c->cipher->contextsize);
 
885
    }
 
886
 
 
887
  return gcry_error (ret);
 
888
}
 
889
 
 
890
 
 
891
/* Set the IV to be used for the encryption context C to IV with
 
892
   length IVLEN.  The length should match the required length. */
 
893
static void
 
894
cipher_setiv( gcry_cipher_hd_t c, const byte *iv, unsigned ivlen )
 
895
{
 
896
  memset (c->u_iv.iv, 0, c->cipher->blocksize);
 
897
  if (iv) 
 
898
    {
 
899
      if (ivlen != c->cipher->blocksize)
 
900
        {
 
901
          log_info ("WARNING: cipher_setiv: ivlen=%u blklen=%u\n",
 
902
                    ivlen, (unsigned int)c->cipher->blocksize);
 
903
          fips_signal_error ("IV length does not match blocklength");
 
904
        }
 
905
      if (ivlen > c->cipher->blocksize)
 
906
        ivlen = c->cipher->blocksize;
 
907
      memcpy (c->u_iv.iv, iv, ivlen);
 
908
    }
 
909
  c->unused = 0;
 
910
}
 
911
 
 
912
 
 
913
/* Reset the cipher context to the initial context.  This is basically
 
914
   the same as an release followed by a new. */
 
915
static void
 
916
cipher_reset (gcry_cipher_hd_t c)
 
917
{
 
918
  memcpy (&c->context.c,
 
919
          (char *) &c->context.c + c->cipher->contextsize,
 
920
          c->cipher->contextsize);
 
921
  memset (c->u_iv.iv, 0, c->cipher->blocksize);
 
922
  memset (c->lastiv, 0, c->cipher->blocksize);
 
923
  memset (c->ctr, 0, c->cipher->blocksize);
 
924
}
 
925
 
 
926
 
 
927
static void
 
928
do_ecb_encrypt( gcry_cipher_hd_t c, byte *outbuf, const byte *inbuf,
 
929
                unsigned int nblocks )
 
930
{
 
931
  unsigned int n;
 
932
  
 
933
  for (n=0; n < nblocks; n++ )
 
934
    {
 
935
      c->cipher->encrypt ( &c->context.c, outbuf, (byte*)/*arggg*/inbuf );
 
936
      inbuf  += c->cipher->blocksize;
 
937
      outbuf += c->cipher->blocksize;
 
938
    }
 
939
}
 
940
 
 
941
static void
 
942
do_ecb_decrypt( gcry_cipher_hd_t c, byte *outbuf, const byte *inbuf,
 
943
                unsigned int nblocks )
 
944
{
 
945
  unsigned int n;
 
946
 
 
947
  for (n=0; n < nblocks; n++ ) 
 
948
    {
 
949
      c->cipher->decrypt ( &c->context.c, outbuf, (byte*)/*arggg*/inbuf );
 
950
      inbuf  += c->cipher->blocksize;
 
951
      outbuf += c->cipher->blocksize;
 
952
    }
 
953
}
 
954
 
 
955
 
 
956
static void
 
957
do_cbc_encrypt (gcry_cipher_hd_t c, unsigned char *outbuf, 
 
958
                const unsigned char *inbuf, unsigned int nbytes )
 
959
{
 
960
  unsigned int n;
 
961
  unsigned char *ivp;
 
962
  int i;
 
963
  size_t blocksize = c->cipher->blocksize;
 
964
  unsigned nblocks = nbytes / blocksize;
 
965
 
 
966
  if ((c->flags & GCRY_CIPHER_CBC_CTS) && nbytes > blocksize) 
 
967
    {
 
968
      if ((nbytes % blocksize) == 0)
 
969
        nblocks--;
 
970
    }
 
971
 
 
972
  if (c->bulk.cbc_enc)
 
973
    {
 
974
      c->bulk.cbc_enc (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks,
 
975
                       (c->flags & GCRY_CIPHER_CBC_MAC)); 
 
976
      inbuf  += nblocks * blocksize;
 
977
      if (!(c->flags & GCRY_CIPHER_CBC_MAC))
 
978
        outbuf += nblocks * blocksize;
 
979
    }
 
980
  else
 
981
    {
 
982
      for (n=0; n < nblocks; n++ )
 
983
        {
 
984
          for (ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
985
            outbuf[i] = inbuf[i] ^ *ivp++;
 
986
          c->cipher->encrypt ( &c->context.c, outbuf, outbuf );
 
987
          memcpy (c->u_iv.iv, outbuf, blocksize );
 
988
          inbuf  += blocksize;
 
989
          if (!(c->flags & GCRY_CIPHER_CBC_MAC))
 
990
            outbuf += blocksize;
 
991
        }
 
992
    }
 
993
 
 
994
  if ((c->flags & GCRY_CIPHER_CBC_CTS) && nbytes > blocksize)
 
995
    {
 
996
      /* We have to be careful here, since outbuf might be equal to
 
997
         inbuf.  */
 
998
      int restbytes;
 
999
      unsigned char b;
 
1000
 
 
1001
      if ((nbytes % blocksize) == 0)
 
1002
        restbytes = blocksize;
 
1003
      else
 
1004
        restbytes = nbytes % blocksize;
 
1005
 
 
1006
      outbuf -= blocksize;
 
1007
      for (ivp = c->u_iv.iv, i = 0; i < restbytes; i++)
 
1008
        {
 
1009
          b = inbuf[i];
 
1010
          outbuf[blocksize + i] = outbuf[i];
 
1011
          outbuf[i] = b ^ *ivp++;
 
1012
        }
 
1013
      for (; i < blocksize; i++)
 
1014
        outbuf[i] = 0 ^ *ivp++;
 
1015
      
 
1016
      c->cipher->encrypt (&c->context.c, outbuf, outbuf);
 
1017
      memcpy (c->u_iv.iv, outbuf, blocksize);
 
1018
    }
 
1019
}
 
1020
 
 
1021
 
 
1022
static void
 
1023
do_cbc_decrypt (gcry_cipher_hd_t c, unsigned char *outbuf, 
 
1024
                const unsigned char *inbuf, unsigned int nbytes)
 
1025
{
 
1026
  unsigned int n;
 
1027
  unsigned char *ivp;
 
1028
  int i;
 
1029
  size_t blocksize = c->cipher->blocksize;
 
1030
  unsigned int nblocks = nbytes / blocksize;
 
1031
 
 
1032
  if ((c->flags & GCRY_CIPHER_CBC_CTS) && nbytes > blocksize)
 
1033
    {
 
1034
      nblocks--;
 
1035
      if ((nbytes % blocksize) == 0)
 
1036
        nblocks--;
 
1037
      memcpy (c->lastiv, c->u_iv.iv, blocksize);
 
1038
    }
 
1039
 
 
1040
  if (c->bulk.cbc_dec)
 
1041
    {
 
1042
      c->bulk.cbc_dec (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks); 
 
1043
      inbuf  += nblocks * blocksize;
 
1044
      outbuf += nblocks * blocksize;
 
1045
    }
 
1046
  else
 
1047
    {
 
1048
      for (n=0; n < nblocks; n++ ) 
 
1049
        {
 
1050
          /* Because outbuf and inbuf might be the same, we have to
 
1051
           * save the original ciphertext block.  We use LASTIV for
 
1052
           * this here because it is not used otherwise. */
 
1053
          memcpy (c->lastiv, inbuf, blocksize);
 
1054
          c->cipher->decrypt ( &c->context.c, outbuf, inbuf );
 
1055
          for (ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1056
            outbuf[i] ^= *ivp++;
 
1057
          memcpy(c->u_iv.iv, c->lastiv, blocksize );
 
1058
          inbuf  += c->cipher->blocksize;
 
1059
          outbuf += c->cipher->blocksize;
 
1060
        }
 
1061
    }
 
1062
 
 
1063
  if ((c->flags & GCRY_CIPHER_CBC_CTS) && nbytes > blocksize) 
 
1064
    {
 
1065
      int restbytes;
 
1066
      
 
1067
      if ((nbytes % blocksize) == 0)
 
1068
        restbytes = blocksize;
 
1069
      else
 
1070
        restbytes = nbytes % blocksize;
 
1071
      
 
1072
      memcpy (c->lastiv, c->u_iv.iv, blocksize );         /* Save Cn-2. */
 
1073
      memcpy (c->u_iv.iv, inbuf + blocksize, restbytes ); /* Save Cn. */
 
1074
 
 
1075
      c->cipher->decrypt ( &c->context.c, outbuf, inbuf );
 
1076
      for (ivp=c->u_iv.iv,i=0; i < restbytes; i++ )
 
1077
        outbuf[i] ^= *ivp++;
 
1078
      
 
1079
      memcpy(outbuf + blocksize, outbuf, restbytes);
 
1080
      for(i=restbytes; i < blocksize; i++)
 
1081
        c->u_iv.iv[i] = outbuf[i];
 
1082
      c->cipher->decrypt (&c->context.c, outbuf, c->u_iv.iv);
 
1083
      for(ivp=c->lastiv,i=0; i < blocksize; i++ )
 
1084
        outbuf[i] ^= *ivp++;
 
1085
      /* c->lastiv is now really lastlastiv, does this matter? */
 
1086
    }
 
1087
}
 
1088
 
 
1089
 
 
1090
static void
 
1091
do_cfb_encrypt( gcry_cipher_hd_t c, unsigned char *outbuf, 
 
1092
                const unsigned char *inbuf, unsigned int nbytes )
 
1093
{
 
1094
  unsigned char *ivp;
 
1095
  size_t blocksize = c->cipher->blocksize;
 
1096
  size_t blocksize_x_2 = blocksize + blocksize;
 
1097
  
 
1098
  if ( nbytes <= c->unused )
 
1099
    {
 
1100
      /* Short enough to be encoded by the remaining XOR mask. */
 
1101
      /* XOR the input with the IV and store input into IV. */
 
1102
      for (ivp=c->u_iv.iv+c->cipher->blocksize - c->unused;
 
1103
           nbytes;
 
1104
           nbytes--, c->unused-- )
 
1105
        *outbuf++ = (*ivp++ ^= *inbuf++);
 
1106
      return;
 
1107
    }
 
1108
 
 
1109
  if ( c->unused )
 
1110
    {
 
1111
      /* XOR the input with the IV and store input into IV */
 
1112
      nbytes -= c->unused;
 
1113
      for(ivp=c->u_iv.iv+blocksize - c->unused; c->unused; c->unused-- )
 
1114
        *outbuf++ = (*ivp++ ^= *inbuf++);
 
1115
    }
 
1116
 
 
1117
  /* Now we can process complete blocks.  We use a loop as long as we
 
1118
     have at least 2 blocks and use conditions for the rest.  This
 
1119
     also allows to use a bulk encryption function if available.  */
 
1120
  if (nbytes >= blocksize_x_2 && c->bulk.cfb_enc)
 
1121
    {
 
1122
      unsigned int nblocks = nbytes / blocksize;
 
1123
      c->bulk.cfb_enc (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks); 
 
1124
      outbuf += nblocks * blocksize;
 
1125
      inbuf  += nblocks * blocksize;
 
1126
      nbytes -= nblocks * blocksize;
 
1127
    }
 
1128
  else
 
1129
    {
 
1130
      while ( nbytes >= blocksize_x_2 )
 
1131
        {
 
1132
          int i;
 
1133
          /* Encrypt the IV. */
 
1134
          c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1135
          /* XOR the input with the IV and store input into IV.  */
 
1136
          for(ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1137
            *outbuf++ = (*ivp++ ^= *inbuf++);
 
1138
          nbytes -= blocksize;
 
1139
        }
 
1140
    }
 
1141
 
 
1142
  if ( nbytes >= blocksize )
 
1143
    {
 
1144
      int i;
 
1145
      /* Save the current IV and then encrypt the IV. */
 
1146
      memcpy( c->lastiv, c->u_iv.iv, blocksize );
 
1147
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1148
      /* XOR the input with the IV and store input into IV */
 
1149
      for(ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1150
        *outbuf++ = (*ivp++ ^= *inbuf++);
 
1151
      nbytes -= blocksize;
 
1152
    }
 
1153
  if ( nbytes ) 
 
1154
    {
 
1155
      /* Save the current IV and then encrypt the IV. */
 
1156
      memcpy( c->lastiv, c->u_iv.iv, blocksize );
 
1157
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1158
      c->unused = blocksize;
 
1159
      /* Apply the XOR. */
 
1160
      c->unused -= nbytes;
 
1161
      for(ivp=c->u_iv.iv; nbytes; nbytes-- )
 
1162
        *outbuf++ = (*ivp++ ^= *inbuf++);
 
1163
    }
 
1164
}
 
1165
 
 
1166
 
 
1167
static void
 
1168
do_cfb_decrypt( gcry_cipher_hd_t c, unsigned char *outbuf, 
 
1169
                const unsigned char *inbuf, unsigned int nbytes )
 
1170
{
 
1171
  unsigned char *ivp;
 
1172
  unsigned long temp;
 
1173
  int i;
 
1174
  size_t blocksize = c->cipher->blocksize;
 
1175
  size_t blocksize_x_2 = blocksize + blocksize;
 
1176
  
 
1177
  if (nbytes <= c->unused)
 
1178
    {
 
1179
      /* Short enough to be encoded by the remaining XOR mask. */
 
1180
      /* XOR the input with the IV and store input into IV. */
 
1181
      for (ivp=c->u_iv.iv+blocksize - c->unused;
 
1182
           nbytes; 
 
1183
           nbytes--, c->unused--)
 
1184
        {
 
1185
          temp = *inbuf++;
 
1186
          *outbuf++ = *ivp ^ temp;
 
1187
          *ivp++ = temp;
 
1188
        }
 
1189
      return;
 
1190
    }
 
1191
  
 
1192
  if (c->unused)
 
1193
    {
 
1194
      /* XOR the input with the IV and store input into IV. */
 
1195
      nbytes -= c->unused;
 
1196
      for (ivp=c->u_iv.iv+blocksize - c->unused; c->unused; c->unused-- )
 
1197
        {
 
1198
          temp = *inbuf++;
 
1199
          *outbuf++ = *ivp ^ temp;
 
1200
          *ivp++ = temp;
 
1201
        }
 
1202
    }
 
1203
  
 
1204
  /* Now we can process complete blocks.  We use a loop as long as we
 
1205
     have at least 2 blocks and use conditions for the rest.  This
 
1206
     also allows to use a bulk encryption function if available.  */
 
1207
  if (nbytes >= blocksize_x_2 && c->bulk.cfb_dec)
 
1208
    {
 
1209
      unsigned int nblocks = nbytes / blocksize;
 
1210
      c->bulk.cfb_dec (&c->context.c, c->u_iv.iv, outbuf, inbuf, nblocks); 
 
1211
      outbuf += nblocks * blocksize;
 
1212
      inbuf  += nblocks * blocksize;
 
1213
      nbytes -= nblocks * blocksize;
 
1214
    }
 
1215
  else
 
1216
    {
 
1217
      while (nbytes >= blocksize_x_2 )
 
1218
        {
 
1219
          /* Encrypt the IV. */
 
1220
          c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1221
          /* XOR the input with the IV and store input into IV. */
 
1222
          for (ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1223
            {
 
1224
              temp = *inbuf++;
 
1225
              *outbuf++ = *ivp ^ temp;
 
1226
              *ivp++ = temp;
 
1227
            }
 
1228
          nbytes -= blocksize;
 
1229
        }
 
1230
    }
 
1231
 
 
1232
  if (nbytes >= blocksize )
 
1233
    {
 
1234
      /* Save the current IV and then encrypt the IV. */
 
1235
      memcpy ( c->lastiv, c->u_iv.iv, blocksize);
 
1236
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1237
      /* XOR the input with the IV and store input into IV */
 
1238
      for (ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1239
        {
 
1240
          temp = *inbuf++;
 
1241
          *outbuf++ = *ivp ^ temp;
 
1242
          *ivp++ = temp;
 
1243
        }
 
1244
      nbytes -= blocksize;
 
1245
    }
 
1246
 
 
1247
  if (nbytes)
 
1248
    { 
 
1249
      /* Save the current IV and then encrypt the IV. */
 
1250
      memcpy ( c->lastiv, c->u_iv.iv, blocksize );
 
1251
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1252
      c->unused = blocksize;
 
1253
      /* Apply the XOR. */
 
1254
      c->unused -= nbytes;
 
1255
      for (ivp=c->u_iv.iv; nbytes; nbytes-- )
 
1256
        {
 
1257
          temp = *inbuf++;
 
1258
          *outbuf++ = *ivp ^ temp;
 
1259
          *ivp++ = temp;
 
1260
        }
 
1261
    }
 
1262
}
 
1263
 
 
1264
 
 
1265
static void
 
1266
do_ofb_encrypt( gcry_cipher_hd_t c,
 
1267
                byte *outbuf, const byte *inbuf, unsigned nbytes )
 
1268
{
 
1269
  byte *ivp;
 
1270
  size_t blocksize = c->cipher->blocksize;
 
1271
 
 
1272
  if ( nbytes <= c->unused )
 
1273
    {
 
1274
      /* Short enough to be encoded by the remaining XOR mask. */
 
1275
      /* XOR the input with the IV */
 
1276
      for (ivp=c->u_iv.iv+c->cipher->blocksize - c->unused;
 
1277
           nbytes;
 
1278
           nbytes--, c->unused-- )
 
1279
        *outbuf++ = (*ivp++ ^ *inbuf++);
 
1280
      return;
 
1281
    }
 
1282
 
 
1283
  if( c->unused )
 
1284
    {
 
1285
      nbytes -= c->unused;
 
1286
      for(ivp=c->u_iv.iv+blocksize - c->unused; c->unused; c->unused-- )
 
1287
        *outbuf++ = (*ivp++ ^ *inbuf++);
 
1288
    }
 
1289
 
 
1290
  /* Now we can process complete blocks. */
 
1291
  while ( nbytes >= blocksize )
 
1292
    {
 
1293
      int i;
 
1294
      /* Encrypt the IV (and save the current one). */
 
1295
      memcpy( c->lastiv, c->u_iv.iv, blocksize );
 
1296
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1297
      
 
1298
      for (ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1299
        *outbuf++ = (*ivp++ ^ *inbuf++);
 
1300
      nbytes -= blocksize;
 
1301
    }
 
1302
  if ( nbytes )
 
1303
    { /* process the remaining bytes */
 
1304
      memcpy( c->lastiv, c->u_iv.iv, blocksize );
 
1305
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1306
      c->unused = blocksize;
 
1307
      c->unused -= nbytes;
 
1308
      for(ivp=c->u_iv.iv; nbytes; nbytes-- )
 
1309
        *outbuf++ = (*ivp++ ^ *inbuf++);
 
1310
    }
 
1311
}
 
1312
 
 
1313
static void
 
1314
do_ofb_decrypt( gcry_cipher_hd_t c,
 
1315
                byte *outbuf, const byte *inbuf, unsigned int nbytes )
 
1316
{
 
1317
  byte *ivp;
 
1318
  size_t blocksize = c->cipher->blocksize;
 
1319
  
 
1320
  if( nbytes <= c->unused )
 
1321
    {
 
1322
      /* Short enough to be encoded by the remaining XOR mask. */
 
1323
      for (ivp=c->u_iv.iv+blocksize - c->unused; nbytes; nbytes--,c->unused--)
 
1324
        *outbuf++ = *ivp++ ^ *inbuf++;
 
1325
      return;
 
1326
    }
 
1327
 
 
1328
  if ( c->unused )
 
1329
    {
 
1330
      nbytes -= c->unused;
 
1331
      for (ivp=c->u_iv.iv+blocksize - c->unused; c->unused; c->unused-- )
 
1332
        *outbuf++ = *ivp++ ^ *inbuf++;
 
1333
    }
 
1334
 
 
1335
  /* Now we can process complete blocks. */
 
1336
  while ( nbytes >= blocksize )
 
1337
    {
 
1338
      int i;
 
1339
      /* Encrypt the IV (and save the current one). */
 
1340
      memcpy( c->lastiv, c->u_iv.iv, blocksize );
 
1341
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1342
      for (ivp=c->u_iv.iv,i=0; i < blocksize; i++ )
 
1343
        *outbuf++ = *ivp++ ^ *inbuf++;
 
1344
      nbytes -= blocksize;
 
1345
    }
 
1346
  if ( nbytes ) 
 
1347
    { /* Process the remaining bytes. */
 
1348
      /* Encrypt the IV (and save the current one). */
 
1349
      memcpy( c->lastiv, c->u_iv.iv, blocksize );
 
1350
      c->cipher->encrypt ( &c->context.c, c->u_iv.iv, c->u_iv.iv );
 
1351
      c->unused = blocksize;
 
1352
      c->unused -= nbytes;
 
1353
      for (ivp=c->u_iv.iv; nbytes; nbytes-- )
 
1354
        *outbuf++ = *ivp++ ^ *inbuf++;
 
1355
    }
 
1356
}
 
1357
 
 
1358
 
 
1359
static void
 
1360
do_ctr_encrypt( gcry_cipher_hd_t c, byte *outbuf, const byte *inbuf,
 
1361
                unsigned int nbytes )
 
1362
{
 
1363
  unsigned int n;
 
1364
  byte tmp[MAX_BLOCKSIZE];
 
1365
  int i;
 
1366
 
 
1367
  for(n=0; n < nbytes; n++)
 
1368
    {
 
1369
      if ((n % c->cipher->blocksize) == 0)
 
1370
        {
 
1371
          c->cipher->encrypt (&c->context.c, tmp, c->ctr);
 
1372
 
 
1373
          for (i = c->cipher->blocksize; i > 0; i--)
 
1374
            {
 
1375
              c->ctr[i-1]++;
 
1376
              if (c->ctr[i-1] != 0)
 
1377
                break;
 
1378
            }
 
1379
        }
 
1380
 
 
1381
      /* XOR input with encrypted counter and store in output. */
 
1382
      outbuf[n] = inbuf[n] ^ tmp[n % c->cipher->blocksize];
 
1383
    }
 
1384
}
 
1385
 
 
1386
static void
 
1387
do_ctr_decrypt( gcry_cipher_hd_t c, byte *outbuf, const byte *inbuf,
 
1388
                unsigned int nbytes )
 
1389
{
 
1390
  do_ctr_encrypt (c, outbuf, inbuf, nbytes);
 
1391
}
 
1392
 
 
1393
 
 
1394
/****************
 
1395
 * Encrypt INBUF to OUTBUF with the mode selected at open.
 
1396
 * inbuf and outbuf may overlap or be the same.
 
1397
 * Depending on the mode some contraints apply to NBYTES.
 
1398
 */
 
1399
static gcry_err_code_t
 
1400
cipher_encrypt (gcry_cipher_hd_t c, byte *outbuf,
 
1401
                const byte *inbuf, unsigned int nbytes)
 
1402
{
 
1403
    gcry_err_code_t rc = GPG_ERR_NO_ERROR;
 
1404
 
 
1405
    switch( c->mode ) {
 
1406
      case GCRY_CIPHER_MODE_ECB:
 
1407
        if (!(nbytes%c->cipher->blocksize))
 
1408
            do_ecb_encrypt(c, outbuf, inbuf, nbytes/c->cipher->blocksize );
 
1409
        else 
 
1410
            rc = GPG_ERR_INV_ARG;
 
1411
        break;
 
1412
      case GCRY_CIPHER_MODE_CBC:
 
1413
        if (!(nbytes%c->cipher->blocksize)
 
1414
            || (nbytes > c->cipher->blocksize
 
1415
                && (c->flags & GCRY_CIPHER_CBC_CTS)))
 
1416
            do_cbc_encrypt(c, outbuf, inbuf, nbytes );
 
1417
        else 
 
1418
            rc = GPG_ERR_INV_ARG;
 
1419
        break;
 
1420
      case GCRY_CIPHER_MODE_CFB:
 
1421
        do_cfb_encrypt(c, outbuf, inbuf, nbytes );
 
1422
        break;
 
1423
      case GCRY_CIPHER_MODE_OFB:
 
1424
        do_ofb_encrypt(c, outbuf, inbuf, nbytes );
 
1425
        break;
 
1426
      case GCRY_CIPHER_MODE_CTR:
 
1427
        do_ctr_encrypt(c, outbuf, inbuf, nbytes );
 
1428
        break;
 
1429
      case GCRY_CIPHER_MODE_STREAM:
 
1430
        c->cipher->stencrypt ( &c->context.c,
 
1431
                               outbuf, (byte*)/*arggg*/inbuf, nbytes );
 
1432
        break;
 
1433
      case GCRY_CIPHER_MODE_NONE:
 
1434
        if (fips_mode () || !_gcry_get_debug_flag (0))
 
1435
          {
 
1436
            fips_signal_error ("cipher mode NONE used");
 
1437
            rc = GPG_ERR_INV_CIPHER_MODE;
 
1438
          }
 
1439
        else
 
1440
          {
 
1441
            if ( inbuf != outbuf )
 
1442
              memmove (outbuf, inbuf, nbytes);
 
1443
          }
 
1444
        break;
 
1445
      default:
 
1446
        log_fatal("cipher_encrypt: invalid mode %d\n", c->mode );
 
1447
        rc = GPG_ERR_INV_CIPHER_MODE;
 
1448
        break;
 
1449
    }
 
1450
    return rc;
 
1451
}
 
1452
 
 
1453
 
 
1454
/****************
 
1455
 * Encrypt IN and write it to OUT.  If IN is NULL, in-place encryption has
 
1456
 * been requested.
 
1457
 */
 
1458
gcry_error_t
 
1459
gcry_cipher_encrypt (gcry_cipher_hd_t h, void *out, size_t outsize,
 
1460
                     const void *in, size_t inlen)
 
1461
{
 
1462
  gcry_err_code_t err;
 
1463
 
 
1464
  if (!in)
 
1465
    {
 
1466
      /* Caller requested in-place encryption. */
 
1467
      /* Actually cipher_encrypt() does not need to know about it, but
 
1468
       * we may change it in the future to get better performance.  */
 
1469
      err = cipher_encrypt (h, out, out, outsize);
 
1470
    }
 
1471
  else if (outsize < ((h->flags & GCRY_CIPHER_CBC_MAC) ?
 
1472
                      h->cipher->blocksize : inlen))
 
1473
    err = GPG_ERR_TOO_SHORT;
 
1474
  else if ((h->mode == GCRY_CIPHER_MODE_ECB
 
1475
            || (h->mode == GCRY_CIPHER_MODE_CBC
 
1476
                && (! ((h->flags & GCRY_CIPHER_CBC_CTS)
 
1477
                       && (inlen > h->cipher->blocksize)))))
 
1478
           && (inlen % h->cipher->blocksize))
 
1479
    err = GPG_ERR_INV_ARG;
 
1480
  else
 
1481
    err = cipher_encrypt (h, out, in, inlen);
 
1482
 
 
1483
  if (err && out)
 
1484
    memset (out, 0x42, outsize); /* Failsafe: Make sure that the
 
1485
                                    plaintext will never make it into
 
1486
                                    OUT. */
 
1487
 
 
1488
  return gcry_error (err);
 
1489
}
 
1490
 
 
1491
 
 
1492
 
 
1493
/****************
 
1494
 * Decrypt INBUF to OUTBUF with the mode selected at open.
 
1495
 * inbuf and outbuf may overlap or be the same.
 
1496
 * Depending on the mode some some contraints apply to NBYTES.
 
1497
 */
 
1498
static gcry_err_code_t
 
1499
cipher_decrypt (gcry_cipher_hd_t c, byte *outbuf, const byte *inbuf,
 
1500
                unsigned int nbytes)
 
1501
{
 
1502
    gcry_err_code_t rc = GPG_ERR_NO_ERROR;
 
1503
 
 
1504
    switch( c->mode ) {
 
1505
      case GCRY_CIPHER_MODE_ECB:
 
1506
        if (!(nbytes%c->cipher->blocksize))
 
1507
            do_ecb_decrypt(c, outbuf, inbuf, nbytes/c->cipher->blocksize );
 
1508
        else 
 
1509
            rc = GPG_ERR_INV_ARG;
 
1510
        break;
 
1511
      case GCRY_CIPHER_MODE_CBC:
 
1512
        if (!(nbytes%c->cipher->blocksize)
 
1513
            || (nbytes > c->cipher->blocksize
 
1514
                && (c->flags & GCRY_CIPHER_CBC_CTS)))
 
1515
            do_cbc_decrypt(c, outbuf, inbuf, nbytes );
 
1516
        else 
 
1517
            rc = GPG_ERR_INV_ARG;
 
1518
        break;
 
1519
      case GCRY_CIPHER_MODE_CFB:
 
1520
        do_cfb_decrypt(c, outbuf, inbuf, nbytes );
 
1521
        break;
 
1522
      case GCRY_CIPHER_MODE_OFB:
 
1523
        do_ofb_decrypt(c, outbuf, inbuf, nbytes );
 
1524
        break;
 
1525
      case GCRY_CIPHER_MODE_CTR:
 
1526
        do_ctr_decrypt(c, outbuf, inbuf, nbytes );
 
1527
        break;
 
1528
      case GCRY_CIPHER_MODE_STREAM:
 
1529
        c->cipher->stdecrypt ( &c->context.c,
 
1530
                               outbuf, (byte*)/*arggg*/inbuf, nbytes );
 
1531
        break;
 
1532
      case GCRY_CIPHER_MODE_NONE:
 
1533
        if (fips_mode () || !_gcry_get_debug_flag (0))
 
1534
          {
 
1535
            fips_signal_error ("cipher mode NONE used");
 
1536
            rc = GPG_ERR_INV_CIPHER_MODE;
 
1537
          }
 
1538
        else
 
1539
          {
 
1540
            if (inbuf != outbuf)
 
1541
              memmove (outbuf, inbuf, nbytes);
 
1542
          }
 
1543
        break;
 
1544
      default:
 
1545
        log_fatal ("cipher_decrypt: invalid mode %d\n", c->mode );
 
1546
        rc = GPG_ERR_INV_CIPHER_MODE;
 
1547
        break;
 
1548
    }
 
1549
    return rc;
 
1550
}
 
1551
 
 
1552
 
 
1553
gcry_error_t
 
1554
gcry_cipher_decrypt (gcry_cipher_hd_t h, void *out, size_t outsize,
 
1555
                     const void *in, size_t inlen)
 
1556
{
 
1557
  gcry_err_code_t err = 0;
 
1558
 
 
1559
  if (!in)
 
1560
    {
 
1561
      /* Caller requested in-place encryption. */
 
1562
      /* Actually cipher_encrypt() does not need to know about it, but
 
1563
       * we may change it in the future to get better performance.  */
 
1564
      err = cipher_decrypt (h, out, out, outsize);
 
1565
    }
 
1566
  else if (outsize < inlen)
 
1567
    err = GPG_ERR_TOO_SHORT;
 
1568
  else if (((h->mode == GCRY_CIPHER_MODE_ECB)
 
1569
            || ((h->mode == GCRY_CIPHER_MODE_CBC)
 
1570
                && (! ((h->flags & GCRY_CIPHER_CBC_CTS)
 
1571
                       && (inlen > h->cipher->blocksize)))))
 
1572
           && (inlen % h->cipher->blocksize) != 0)
 
1573
    err = GPG_ERR_INV_ARG;
 
1574
  else
 
1575
    err = cipher_decrypt (h, out, in, inlen);
 
1576
 
 
1577
  return gcry_error (err);
 
1578
}
 
1579
 
 
1580
 
 
1581
 
 
1582
/****************
 
1583
 * Used for PGP's somewhat strange CFB mode. Only works if
 
1584
 * the corresponding flag is set.
 
1585
 */
 
1586
static void
 
1587
cipher_sync (gcry_cipher_hd_t c)
 
1588
{
 
1589
  if ((c->flags & GCRY_CIPHER_ENABLE_SYNC) && c->unused)
 
1590
    {
 
1591
      memmove (c->u_iv.iv + c->unused,
 
1592
               c->u_iv.iv, c->cipher->blocksize - c->unused);
 
1593
      memcpy (c->u_iv.iv,
 
1594
              c->lastiv + c->cipher->blocksize - c->unused, c->unused);
 
1595
      c->unused = 0;
 
1596
    }
 
1597
}
 
1598
 
 
1599
 
 
1600
gcry_error_t
 
1601
_gcry_cipher_setkey (gcry_cipher_hd_t hd, const void *key, size_t keylen)
 
1602
{
 
1603
  return cipher_setkey (hd, (void*)key, keylen);
 
1604
}
 
1605
 
 
1606
 
 
1607
gcry_error_t
 
1608
_gcry_cipher_setiv (gcry_cipher_hd_t hd, const void *iv, size_t ivlen)
 
1609
{
 
1610
  cipher_setiv (hd, iv, ivlen);
 
1611
  return 0;
 
1612
}
 
1613
 
 
1614
/* Set counter for CTR mode.  (CTR,CTRLEN) must denote a buffer of
 
1615
   block size length, or (NULL,0) to set the CTR to the all-zero
 
1616
   block. */
 
1617
gpg_error_t
 
1618
_gcry_cipher_setctr (gcry_cipher_hd_t hd, const void *ctr, size_t ctrlen)
 
1619
{
 
1620
  if (ctr && ctrlen == hd->cipher->blocksize)
 
1621
    memcpy (hd->ctr, ctr, hd->cipher->blocksize);
 
1622
  else if (!ctr || !ctrlen)
 
1623
    memset (hd->ctr, 0, hd->cipher->blocksize);
 
1624
  else
 
1625
    return gpg_error (GPG_ERR_INV_ARG);
 
1626
  return 0;
 
1627
}
 
1628
 
 
1629
 
 
1630
gcry_error_t
 
1631
gcry_cipher_ctl( gcry_cipher_hd_t h, int cmd, void *buffer, size_t buflen)
 
1632
{
 
1633
  gcry_err_code_t rc = GPG_ERR_NO_ERROR;
 
1634
 
 
1635
  switch (cmd)
 
1636
    {
 
1637
    case GCRYCTL_SET_KEY:  /* Deprecated; use gcry_cipher_setkey.  */
 
1638
      rc = cipher_setkey( h, buffer, buflen );
 
1639
      break;
 
1640
 
 
1641
    case GCRYCTL_SET_IV:   /* Deprecated; use gcry_cipher_setiv.  */
 
1642
      cipher_setiv( h, buffer, buflen );
 
1643
      break;
 
1644
 
 
1645
    case GCRYCTL_RESET:
 
1646
      cipher_reset (h);
 
1647
      break;
 
1648
 
 
1649
    case GCRYCTL_CFB_SYNC:
 
1650
      cipher_sync( h );
 
1651
      break;
 
1652
 
 
1653
    case GCRYCTL_SET_CBC_CTS:
 
1654
      if (buflen)
 
1655
        if (h->flags & GCRY_CIPHER_CBC_MAC)
 
1656
          rc = GPG_ERR_INV_FLAG;
 
1657
        else
 
1658
          h->flags |= GCRY_CIPHER_CBC_CTS;
 
1659
      else
 
1660
        h->flags &= ~GCRY_CIPHER_CBC_CTS;
 
1661
      break;
 
1662
 
 
1663
    case GCRYCTL_SET_CBC_MAC:
 
1664
      if (buflen)
 
1665
        if (h->flags & GCRY_CIPHER_CBC_CTS)
 
1666
          rc = GPG_ERR_INV_FLAG;
 
1667
        else
 
1668
          h->flags |= GCRY_CIPHER_CBC_MAC;
 
1669
      else
 
1670
        h->flags &= ~GCRY_CIPHER_CBC_MAC;
 
1671
      break;
 
1672
 
 
1673
    case GCRYCTL_DISABLE_ALGO:
 
1674
      /* This command expects NULL for H and BUFFER to point to an
 
1675
         integer with the algo number.  */
 
1676
      if( h || !buffer || buflen != sizeof(int) )
 
1677
        return gcry_error (GPG_ERR_CIPHER_ALGO);
 
1678
      disable_cipher_algo( *(int*)buffer );
 
1679
      break;
 
1680
 
 
1681
    case GCRYCTL_SET_CTR: /* Deprecated; use gcry_cipher_setctr.  */
 
1682
      if (buffer && buflen == h->cipher->blocksize)
 
1683
        memcpy (h->ctr, buffer, h->cipher->blocksize);
 
1684
      else if (buffer == NULL || buflen == 0)
 
1685
        memset (h->ctr, 0, h->cipher->blocksize);
 
1686
      else
 
1687
        rc = GPG_ERR_INV_ARG;
 
1688
      break;
 
1689
 
 
1690
    case 61:  /* Disable weak key detection (private).  */
 
1691
      if (h->extraspec->set_extra_info)
 
1692
        rc = h->extraspec->set_extra_info 
 
1693
          (&h->context.c, CIPHER_INFO_NO_WEAK_KEY, NULL, 0);
 
1694
      else
 
1695
        rc = GPG_ERR_NOT_SUPPORTED;
 
1696
      break;
 
1697
 
 
1698
    case 62: /* Return current input vector (private).  */
 
1699
      /* This is the input block as used in CFB and OFB mode which has
 
1700
         initially been set as IV.  The returned format is: 
 
1701
           1 byte  Actual length of the block in bytes.
 
1702
           n byte  The block.
 
1703
         If the provided buffer is too short, an error is returned. */
 
1704
      if (buflen < (1 + h->cipher->blocksize))
 
1705
        rc = GPG_ERR_TOO_SHORT;
 
1706
      else
 
1707
        {
 
1708
          unsigned char *ivp;
 
1709
          unsigned char *dst = buffer;
 
1710
          int n = h->unused;
 
1711
          
 
1712
          if (!n)
 
1713
            n = h->cipher->blocksize;
 
1714
          gcry_assert (n <= h->cipher->blocksize);
 
1715
          *dst++ = n;
 
1716
          ivp = h->u_iv.iv + h->cipher->blocksize - n;
 
1717
          while (n--)
 
1718
            *dst++ = *ivp++;
 
1719
        }
 
1720
      break;
 
1721
 
 
1722
    default:
 
1723
      rc = GPG_ERR_INV_OP;
 
1724
    }
 
1725
 
 
1726
  return gcry_error (rc);
 
1727
}
 
1728
 
 
1729
 
 
1730
/* Return information about the cipher handle H.  CMD is the kind of
 
1731
   information requested.  BUFFER and NBYTES are reserved for now.
 
1732
 
 
1733
   There are no values for CMD yet defined.  
 
1734
 
 
1735
   The fucntion always returns GPG_ERR_INV_OP.
 
1736
   
 
1737
 */
 
1738
gcry_error_t
 
1739
gcry_cipher_info (gcry_cipher_hd_t h, int cmd, void *buffer, size_t *nbytes)
 
1740
{
 
1741
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
1742
 
 
1743
  (void)h;
 
1744
  (void)buffer;
 
1745
  (void)nbytes;
 
1746
 
 
1747
  switch (cmd)
 
1748
    {
 
1749
    default:
 
1750
      err = GPG_ERR_INV_OP;
 
1751
    }
 
1752
 
 
1753
  return gcry_error (err);
 
1754
}
 
1755
 
 
1756
/* Return information about the given cipher algorithm ALGO.
 
1757
 
 
1758
   WHAT select the kind of information returned:
 
1759
 
 
1760
    GCRYCTL_GET_KEYLEN:
 
1761
        Return the length of the key.  If the algorithm ALGO
 
1762
        supports multiple key lengths, the maximum supported key length
 
1763
        is returned.  The key length is returned as number of octets.
 
1764
        BUFFER and NBYTES must be zero.
 
1765
 
 
1766
    GCRYCTL_GET_BLKLEN:
 
1767
        Return the blocklength of the algorithm ALGO counted in octets.
 
1768
        BUFFER and NBYTES must be zero.
 
1769
 
 
1770
    GCRYCTL_TEST_ALGO:
 
1771
        Returns 0 if the specified algorithm ALGO is available for use.
 
1772
        BUFFER and NBYTES must be zero.
 
1773
  
 
1774
   Note: Because this function is in most cases used to return an
 
1775
   integer value, we can make it easier for the caller to just look at
 
1776
   the return value.  The caller will in all cases consult the value
 
1777
   and thereby detecting whether a error occured or not (i.e. while
 
1778
   checking the block size)
 
1779
 */
 
1780
gcry_error_t
 
1781
gcry_cipher_algo_info (int algo, int what, void *buffer, size_t *nbytes)
 
1782
{
 
1783
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
1784
  unsigned int ui;
 
1785
 
 
1786
  switch (what)
 
1787
    {
 
1788
    case GCRYCTL_GET_KEYLEN:
 
1789
      if (buffer || (! nbytes))
 
1790
        err = GPG_ERR_CIPHER_ALGO;
 
1791
      else
 
1792
        {
 
1793
          ui = cipher_get_keylen (algo);
 
1794
          if ((ui > 0) && (ui <= 512))
 
1795
            *nbytes = (size_t) ui / 8;
 
1796
          else
 
1797
            /* The only reason is an invalid algo or a strange
 
1798
               blocksize.  */
 
1799
            err = GPG_ERR_CIPHER_ALGO;
 
1800
        }
 
1801
      break;
 
1802
 
 
1803
    case GCRYCTL_GET_BLKLEN:
 
1804
      if (buffer || (! nbytes))
 
1805
        err = GPG_ERR_CIPHER_ALGO;
 
1806
      else
 
1807
        {
 
1808
          ui = cipher_get_blocksize (algo);
 
1809
          if ((ui > 0) && (ui < 10000))
 
1810
            *nbytes = ui;
 
1811
          else
 
1812
            /* The only reason is an invalid algo or a strange
 
1813
               blocksize.  */
 
1814
            err = GPG_ERR_CIPHER_ALGO;
 
1815
        }
 
1816
      break;
 
1817
 
 
1818
    case GCRYCTL_TEST_ALGO:
 
1819
      if (buffer || nbytes)
 
1820
        err = GPG_ERR_INV_ARG;
 
1821
      else
 
1822
        err = check_cipher_algo (algo);
 
1823
      break;
 
1824
 
 
1825
      default:
 
1826
        err = GPG_ERR_INV_OP;
 
1827
    }
 
1828
 
 
1829
  return gcry_error (err);
 
1830
}
 
1831
 
 
1832
 
 
1833
/* This function returns length of the key for algorithm ALGO.  If the
 
1834
   algorithm supports multiple key lengths, the maximum supported key
 
1835
   length is returned.  On error 0 is returned.  The key length is
 
1836
   returned as number of octets.
 
1837
 
 
1838
   This is a convenience functions which should be preferred over
 
1839
   gcry_cipher_algo_info because it allows for proper type
 
1840
   checking.  */
 
1841
size_t
 
1842
gcry_cipher_get_algo_keylen (int algo) 
 
1843
{
 
1844
  size_t n;
 
1845
 
 
1846
  if (gcry_cipher_algo_info (algo, GCRYCTL_GET_KEYLEN, NULL, &n))
 
1847
    n = 0;
 
1848
  return n;
 
1849
}
 
1850
 
 
1851
/* This functions returns the blocklength of the algorithm ALGO
 
1852
   counted in octets.  On error 0 is returned.
 
1853
 
 
1854
   This is a convenience functions which should be preferred over
 
1855
   gcry_cipher_algo_info because it allows for proper type
 
1856
   checking.  */
 
1857
size_t
 
1858
gcry_cipher_get_algo_blklen (int algo) 
 
1859
{
 
1860
  size_t n;
 
1861
 
 
1862
  if (gcry_cipher_algo_info( algo, GCRYCTL_GET_BLKLEN, NULL, &n))
 
1863
    n = 0;
 
1864
  return n;
 
1865
}
 
1866
 
 
1867
/* Explicitly initialize this module.  */
 
1868
gcry_err_code_t
 
1869
_gcry_cipher_init (void)
 
1870
{
 
1871
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
1872
 
 
1873
  REGISTER_DEFAULT_CIPHERS;
 
1874
 
 
1875
  return err;
 
1876
}
 
1877
 
 
1878
/* Get a list consisting of the IDs of the loaded cipher modules.  If
 
1879
   LIST is zero, write the number of loaded cipher modules to
 
1880
   LIST_LENGTH and return.  If LIST is non-zero, the first
 
1881
   *LIST_LENGTH algorithm IDs are stored in LIST, which must be of
 
1882
   according size.  In case there are less cipher modules than
 
1883
   *LIST_LENGTH, *LIST_LENGTH is updated to the correct number.  */
 
1884
gcry_error_t
 
1885
gcry_cipher_list (int *list, int *list_length)
 
1886
{
 
1887
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
1888
 
 
1889
  ath_mutex_lock (&ciphers_registered_lock);
 
1890
  err = _gcry_module_list (ciphers_registered, list, list_length);
 
1891
  ath_mutex_unlock (&ciphers_registered_lock);
 
1892
 
 
1893
  return err;
 
1894
}
 
1895
 
 
1896
 
 
1897
/* Run the selftests for cipher algorithm ALGO with optional reporting
 
1898
   function REPORT.  */
 
1899
gpg_error_t
 
1900
_gcry_cipher_selftest (int algo, int extended, selftest_report_func_t report)
 
1901
{
 
1902
  gcry_module_t module = NULL;
 
1903
  cipher_extra_spec_t *extraspec = NULL;
 
1904
  gcry_err_code_t ec = 0;
 
1905
 
 
1906
  REGISTER_DEFAULT_CIPHERS;
 
1907
 
 
1908
  ath_mutex_lock (&ciphers_registered_lock);
 
1909
  module = _gcry_module_lookup_id (ciphers_registered, algo);
 
1910
  if (module && !(module->flags & FLAG_MODULE_DISABLED))
 
1911
    extraspec = module->extraspec;
 
1912
  ath_mutex_unlock (&ciphers_registered_lock);
 
1913
  if (extraspec && extraspec->selftest)
 
1914
    ec = extraspec->selftest (algo, extended, report);
 
1915
  else
 
1916
    {
 
1917
      ec = GPG_ERR_CIPHER_ALGO;
 
1918
      if (report)
 
1919
        report ("cipher", algo, "module", 
 
1920
                module && !(module->flags & FLAG_MODULE_DISABLED)?
 
1921
                "no selftest available" :
 
1922
                module? "algorithm disabled" : "algorithm not found");
 
1923
    }
 
1924
 
 
1925
  if (module)
 
1926
    {
 
1927
      ath_mutex_lock (&ciphers_registered_lock);
 
1928
      _gcry_module_release (module);
 
1929
      ath_mutex_unlock (&ciphers_registered_lock);
 
1930
    }
 
1931
  return gpg_error (ec);
 
1932
}