/* cipher.c - cipher dispatcher
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
* 2005, 2007, 2008 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* it under the terms of the GNU Lesser general Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "g10lib.h"
#include "cipher.h"
#include "ath.h"
#endif
/* A dummy extraspec so that we do not need to tests the extraspec
field from the module specification against NULL and instead
directly test the respective fields of extraspecs. */
/* This is the list of the default ciphers, which are included in
libgcrypt. */
static struct cipher_table_entry
{
unsigned int algorithm;
int fips_allowed;
} cipher_table[] =
{
#if USE_BLOWFISH
#endif
#if USE_DES
#endif
#if USE_ARCFOUR
#endif
#if USE_CAST5
#endif
#if USE_AES
#endif
#if USE_TWOFISH
#endif
#if USE_SERPENT
#endif
#if USE_RFC2268
#endif
#if USE_SEED
#endif
#if USE_CAMELLIA
#endif
{ NULL }
};
/* List of registered ciphers. */
/* This is the lock protecting CIPHERS_REGISTERED. */
/* Flag to check wether the default ciphers have already been
registered. */
static int default_ciphers_registered;
/* Convenient macro for registering the default ciphers. */
#define REGISTER_DEFAULT_CIPHERS \
do \
{ \
if (! default_ciphers_registered) \
{ \
cipher_register_default (); \
default_ciphers_registered = 1; \
} \
} \
while (0)
/* A VIA processor with the Padlock engine requires an alignment of
most data on a 16 byte boundary. Because we trick out the compiler
while allocating the context, the align attribute as used in
rijndael.c does not work on its own. Thus we need to make sure
that the entire context structure is a aligned on that boundary.
We achieve this by defining a new type and use that instead of our
usual alignment type. */
typedef union
{
#ifdef NEED_16BYTE_ALIGNED_CONTEXT
#endif
char c[1];
/* The handle structure. */
struct gcry_cipher_handle
{
int magic;
/* The algorithm id. This is a hack required because the module
interface does not easily allow to retrieve this value. */
int algo;
/* A structure with function pointers for bulk operations. Due to
limitations of the module system (we don't want to change the
API) we need to keep these function pointers here. The cipher
open function intializes them and the actual encryption routines
use them if they are not NULL. */
struct {
void *outbuf_arg, const void *inbuf_arg,
unsigned int nblocks);
void *outbuf_arg, const void *inbuf_arg,
unsigned int nblocks);
void *outbuf_arg, const void *inbuf_arg,
void *outbuf_arg, const void *inbuf_arg,
unsigned int nblocks);
} bulk;
int mode;
unsigned int flags;
/* The initialization vector. To help code optimization we make
sure that it is aligned on an unsigned long and u32 boundary. */
union {
unsigned long dummy_iv;
} u_iv;
/* What follows are two contexts of the cipher in use. The first
one needs to be aligned well enough for the cipher operation
whereas the second one is a copy created by cipher_setkey and
used by cipher_reset. That second copy has no need for proper
aligment because it is only accessed by memcpy. */
};
/* These dummy functions are used in case a cipher implementation
refuses to provide it's own functions. */
static gcry_err_code_t
{
(void)c;
(void)key;
(void)keylen;
return GPG_ERR_NO_ERROR;
}
static void
dummy_encrypt_block (void *c,
{
(void)c;
(void)outbuf;
(void)inbuf;
BUG();
}
static void
dummy_decrypt_block (void *c,
{
(void)c;
(void)outbuf;
(void)inbuf;
BUG();
}
static void
dummy_encrypt_stream (void *c,
unsigned int n)
{
(void)c;
(void)outbuf;
(void)inbuf;
(void)n;
BUG();
}
static void
dummy_decrypt_stream (void *c,
unsigned int n)
{
(void)c;
(void)outbuf;
(void)inbuf;
(void)n;
BUG();
}
/* Internal function. Register all the ciphers included in
CIPHER_TABLE. Note, that this function gets only used by the macro
REGISTER_DEFAULT_CIPHERS which protects it using a mutex. */
static void
cipher_register_default (void)
{
int i;
{
continue;
(void *) cipher_table[i].cipher,
(void *) cipher_table[i].extraspec,
NULL);
}
if (err)
BUG ();
}
/* Internal callback function. Used via _gcry_module_lookup. */
static int
{
if (aliases)
return ret;
}
/* Internal callback function. Used via _gcry_module_lookup. */
static int
{
int ret = 0, i;
if (oid_specs)
ret = 1;
return ret;
}
/* Internal function. Lookup a cipher entry by it's name. */
static gcry_module_t
{
return cipher;
}
/* Internal function. Lookup a cipher entry by it's oid. */
static gcry_module_t
{
return cipher;
}
/* Register a new cipher module whose specification can be found in
CIPHER. On success, a new algorithm ID is stored in ALGORITHM_ID
and a pointer representhing this module is stored in MODULE. */
int *algorithm_id,
{
/* We do not support module loading in fips mode. */
if (fips_mode ())
return gpg_error (GPG_ERR_NOT_SUPPORTED);
(void *)cipher,
&mod);
if (! err)
{
}
return gcry_error (err);
}
/* Unregister the cipher identified by MODULE, which must have been
registered with gcry_cipher_register. */
void
{
}
/* Locate the OID in the oid table and return the index or -1 when not
found. An opitonal "oid." or "OID." prefix in OID is ignored, the
OID is expected to be in standard IETF dotted notation. The
internal algorithm number is returned in ALGORITHM unless it
ispassed as NULL. A pointer to the specification of the module
implementing this algorithm is return in OID_SPEC unless passed as
NULL.*/
static int
{
int ret = 0;
oid += 4;
if (module)
{
int i;
{
if (algorithm)
if (oid_spec)
ret = 1;
}
}
return ret;
}
/* Map STRING to the cipher algorithm identifier. Returns the
algorithm ID of the cipher for the given name or 0 if the name is
not known. It is valid to pass NULL for STRING which results in a
return value of 0. */
int
{
if (! string)
return 0;
/* If the string starts with a digit (optionally prefixed with
either "OID." or "oid."), we first look into our table of ASN.1
object identifiers to figure out the algorithm */
if (! ret)
{
if (cipher)
{
}
}
return algorithm;
}
/* Given a STRING with an OID in dotted decimal notation, this
function returns the cipher mode (GCRY_CIPHER_MODE_*) associated
with that OID or 0 if no mode is known. Passing NULL for string
yields a return value of 0. */
int
{
if (!string)
return 0;
if (ret)
return mode;
}
/* Map the cipher algorithm whose ID is contained in ALGORITHM to a
string representation of the algorithm name. For unknown algorithm
IDs this function returns "?". */
static const char *
{
const char *name;
if (cipher)
{
}
else
name = "?";
return name;
}
/* Map the cipher algorithm identifier ALGORITHM to a string
representing this algorithm. This string is the default name as
used by Libgcrypt. An pointer to an empty string is returned for
an unknown algorithm. NULL is never returned. */
const char *
{
return cipher_algo_to_string (algorithm);
}
/* Flag the cipher algorithm with the identifier ALGORITHM as
disabled. There is no error return, the function does nothing for
unknown algorithms. Disabled algorithms are vitually not available
in Libgcrypt. */
static void
{
if (cipher)
{
}
}
/* Return 0 if the cipher algorithm with identifier ALGORITHM is
available. Returns a basic error code value if it is not
available. */
static gcry_err_code_t
{
if (cipher)
{
}
else
return err;
}
/* Return the standard length of the key for the cipher algorithm with
the identifier ALGORITHM. This function expects a valid algorithm
and will abort if the algorithm is not available or the length of
the key is not known. */
static unsigned int
{
unsigned len = 0;
if (cipher)
{
if (!len)
}
else
return len;
}
/* Return the block length of the cipher algorithm with the identifier
ALGORITHM. This function expects a valid algorithm and will abort
if the algorithm is not available or the length of the key is not
known. */
static unsigned int
{
unsigned len = 0;
if (cipher)
{
if (! len)
}
else
return len;
}
/*
Open a cipher handle for use with cipher algorithm ALGORITHM, using
the cipher mode MODE (one of the GCRY_CIPHER_MODE_*) and return a
handle in HANDLE. Put NULL into HANDLE and return an error code if
something goes wrong. FLAGS may be used to modify the
operation. The defined flags are:
GCRY_CIPHER_SECURE: allocate all internal buffers in secure memory.
GCRY_CIPHER_ENABLE_SYNC: Enable the sync operation as used in OpenPGP.
GCRY_CIPHER_CBC_CTS: Enable CTS mode.
GCRY_CIPHER_CBC_MAC: Enable MAC mode.
Values for these flags may be combined using OR.
*/
{
gcry_cipher_hd_t h = NULL;
/* If the application missed to call the random poll function, we do
it here to ensure that it is used once in a while. */
/* Fetch the according module and check wether the cipher is marked
available for use. */
if (module)
{
/* Found module. */
{
/* Not available for use. */
}
else
{
}
}
else
/* check flags */
if ((! err)
&& ((flags & ~(0
/* check that a valid mode has been requested */
if (! err)
switch (mode)
{
case GCRY_CIPHER_MODE_ECB:
case GCRY_CIPHER_MODE_CBC:
case GCRY_CIPHER_MODE_CFB:
case GCRY_CIPHER_MODE_OFB:
case GCRY_CIPHER_MODE_CTR:
break;
case GCRY_CIPHER_MODE_STREAM:
break;
case GCRY_CIPHER_MODE_NONE:
/* This mode may be used for debugging. It copies the main
text verbatim to the ciphertext. We do not allow this in
fips mode or if no debug flag has been set. */
if (fips_mode () || !_gcry_get_debug_flag (0))
break;
default:
}
/* Perform selftest here and mark this with a flag in cipher_table?
No, we should not do this as it takes too long. Further it does
not make sense to exclude algorithms with failing selftests at
runtime: If a selftest fails there is something seriously wrong
with the system and thus we better die immediately. */
if (! err)
{
- sizeof (cipher_context_alignment_t)
#ifdef NEED_16BYTE_ALIGNED_CONTEXT
+ 15 /* Space for leading alignment gap. */
#endif /*NEED_16BYTE_ALIGNED_CONTEXT*/
);
if (secure)
else
if (! h)
else
{
#ifdef NEED_16BYTE_ALIGNED_CONTEXT
if ( ((unsigned long)h & 0x0f) )
{
/* The malloced block is not aligned on a 16 byte
boundary. Correct for this. */
h = (void*)((char*)h + off);
}
#endif /*NEED_16BYTE_ALIGNED_CONTEXT*/
h->handle_offset = off;
/* Setup bulk encryption routines. */
switch (algo)
{
#ifdef USE_AES
case GCRY_CIPHER_AES128:
case GCRY_CIPHER_AES192:
case GCRY_CIPHER_AES256:
break;
#endif /*USE_AES*/
default:
break;
}
}
}
/* Done. */
if (err)
{
if (module)
{
/* Release module. */
}
}
return gcry_error (err);
}
/* Release all resources associated with the cipher handle H. H may be
NULL in which case this is a no-operation. */
void
{
if (!h)
return;
if ((h->magic != CTX_MAGIC_SECURE)
&& (h->magic != CTX_MAGIC_NORMAL))
else
h->magic = 0;
/* Release module. */
_gcry_module_release (h->module);
/* We always want to wipe out the memory even when the context has
been allocated in secure memory. The user might have disabled
secure memory or is using his own implementation which does not
do the wiping. To accomplish this we need to keep track of the
actual size of this structure because we have no way to known
how large the allocated area was when using a standard malloc. */
off = h->handle_offset;
wipememory (h, h->actual_handle_size);
}
/* Set the key to be used for the encryption context C to KEY with
length KEYLEN. The length should match the required length. */
static gcry_error_t
{
if (!ret)
{
/* Duplicate initial context. */
(void *) &c->context.c,
c->cipher->contextsize);
}
return gcry_error (ret);
}
/* Set the IV to be used for the encryption context C to IV with
length IVLEN. The length should match the required length. */
static void
{
if (iv)
{
{
log_info ("WARNING: cipher_setiv: ivlen=%u blklen=%u\n",
fips_signal_error ("IV length does not match blocklength");
}
}
c->unused = 0;
}
/* Reset the cipher context to the initial context. This is basically
the same as an release followed by a new. */
static void
{
c->cipher->contextsize);
}
static void
unsigned int nblocks )
{
unsigned int n;
for (n=0; n < nblocks; n++ )
{
}
}
static void
unsigned int nblocks )
{
unsigned int n;
for (n=0; n < nblocks; n++ )
{
}
}
static void
{
unsigned int n;
unsigned char *ivp;
int i;
{
nblocks--;
}
{
(c->flags & GCRY_CIPHER_CBC_MAC));
if (!(c->flags & GCRY_CIPHER_CBC_MAC))
}
else
{
for (n=0; n < nblocks; n++ )
{
if (!(c->flags & GCRY_CIPHER_CBC_MAC))
}
}
{
/* We have to be careful here, since outbuf might be equal to
inbuf. */
int restbytes;
unsigned char b;
else
{
b = inbuf[i];
}
for (; i < blocksize; i++)
}
}
static void
{
unsigned int n;
unsigned char *ivp;
int i;
{
nblocks--;
nblocks--;
}
{
}
else
{
for (n=0; n < nblocks; n++ )
{
/* Because outbuf and inbuf might be the same, we have to
* save the original ciphertext block. We use LASTIV for
* this here because it is not used otherwise. */
}
}
{
int restbytes;
else
/* c->lastiv is now really lastlastiv, does this matter? */
}
}
static void
{
unsigned char *ivp;
{
/* Short enough to be encoded by the remaining XOR mask. */
/* XOR the input with the IV and store input into IV. */
return;
}
if ( c->unused )
{
/* XOR the input with the IV and store input into IV */
}
/* Now we can process complete blocks. We use a loop as long as we
have at least 2 blocks and use conditions for the rest. This
also allows to use a bulk encryption function if available. */
{
}
else
{
while ( nbytes >= blocksize_x_2 )
{
int i;
/* Encrypt the IV. */
/* XOR the input with the IV and store input into IV. */
}
}
{
int i;
/* Save the current IV and then encrypt the IV. */
/* XOR the input with the IV and store input into IV */
}
if ( nbytes )
{
/* Save the current IV and then encrypt the IV. */
/* Apply the XOR. */
}
}
static void
{
unsigned char *ivp;
unsigned long temp;
int i;
{
/* Short enough to be encoded by the remaining XOR mask. */
/* XOR the input with the IV and store input into IV. */
{
}
return;
}
if (c->unused)
{
/* XOR the input with the IV and store input into IV. */
{
}
}
/* Now we can process complete blocks. We use a loop as long as we
have at least 2 blocks and use conditions for the rest. This
also allows to use a bulk encryption function if available. */
{
}
else
{
while (nbytes >= blocksize_x_2 )
{
/* Encrypt the IV. */
/* XOR the input with the IV and store input into IV. */
{
}
}
}
{
/* Save the current IV and then encrypt the IV. */
/* XOR the input with the IV and store input into IV */
{
}
}
if (nbytes)
{
/* Save the current IV and then encrypt the IV. */
/* Apply the XOR. */
{
}
}
}
static void
{
{
/* Short enough to be encoded by the remaining XOR mask. */
/* XOR the input with the IV */
return;
}
if( c->unused )
{
}
/* Now we can process complete blocks. */
{
int i;
/* Encrypt the IV (and save the current one). */
}
if ( nbytes )
{ /* process the remaining bytes */
}
}
static void
{
{
/* Short enough to be encoded by the remaining XOR mask. */
return;
}
if ( c->unused )
{
}
/* Now we can process complete blocks. */
{
int i;
/* Encrypt the IV (and save the current one). */
}
if ( nbytes )
{ /* Process the remaining bytes. */
/* Encrypt the IV (and save the current one). */
}
}
static void
unsigned int nbytes )
{
unsigned int n;
int i;
for(n=0; n < nbytes; n++)
{
{
{
c->ctr[i-1]++;
if (c->ctr[i-1] != 0)
break;
}
}
/* XOR input with encrypted counter and store in output. */
}
}
static void
unsigned int nbytes )
{
}
/****************
* Encrypt INBUF to OUTBUF with the mode selected at open.
* inbuf and outbuf may overlap or be the same.
* Depending on the mode some contraints apply to NBYTES.
*/
static gcry_err_code_t
{
switch( c->mode ) {
case GCRY_CIPHER_MODE_ECB:
else
break;
case GCRY_CIPHER_MODE_CBC:
&& (c->flags & GCRY_CIPHER_CBC_CTS)))
else
break;
case GCRY_CIPHER_MODE_CFB:
break;
case GCRY_CIPHER_MODE_OFB:
break;
case GCRY_CIPHER_MODE_CTR:
break;
case GCRY_CIPHER_MODE_STREAM:
break;
case GCRY_CIPHER_MODE_NONE:
if (fips_mode () || !_gcry_get_debug_flag (0))
{
fips_signal_error ("cipher mode NONE used");
}
else
{
}
break;
default:
break;
}
return rc;
}
/****************
* Encrypt IN and write it to OUT. If IN is NULL, in-place encryption has
* been requested.
*/
{
if (!in)
{
/* Caller requested in-place encryption. */
/* Actually cipher_encrypt() does not need to know about it, but
* we may change it in the future to get better performance. */
}
else if ((h->mode == GCRY_CIPHER_MODE_ECB
|| (h->mode == GCRY_CIPHER_MODE_CBC
&& (! ((h->flags & GCRY_CIPHER_CBC_CTS)
else
plaintext will never make it into
OUT. */
return gcry_error (err);
}
/****************
* Decrypt INBUF to OUTBUF with the mode selected at open.
* inbuf and outbuf may overlap or be the same.
* Depending on the mode some some contraints apply to NBYTES.
*/
static gcry_err_code_t
unsigned int nbytes)
{
switch( c->mode ) {
case GCRY_CIPHER_MODE_ECB:
else
break;
case GCRY_CIPHER_MODE_CBC:
&& (c->flags & GCRY_CIPHER_CBC_CTS)))
else
break;
case GCRY_CIPHER_MODE_CFB:
break;
case GCRY_CIPHER_MODE_OFB:
break;
case GCRY_CIPHER_MODE_CTR:
break;
case GCRY_CIPHER_MODE_STREAM:
break;
case GCRY_CIPHER_MODE_NONE:
if (fips_mode () || !_gcry_get_debug_flag (0))
{
fips_signal_error ("cipher mode NONE used");
}
else
{
}
break;
default:
break;
}
return rc;
}
{
if (!in)
{
/* Caller requested in-place encryption. */
/* Actually cipher_encrypt() does not need to know about it, but
* we may change it in the future to get better performance. */
}
else if (((h->mode == GCRY_CIPHER_MODE_ECB)
|| ((h->mode == GCRY_CIPHER_MODE_CBC)
&& (! ((h->flags & GCRY_CIPHER_CBC_CTS)
else
return gcry_error (err);
}
/****************
* Used for PGP's somewhat strange CFB mode. Only works if
* the corresponding flag is set.
*/
static void
{
{
c->unused = 0;
}
}
{
}
{
return 0;
}
/* Set counter for CTR mode. (CTR,CTRLEN) must denote a buffer of
block size length, or (NULL,0) to set the CTR to the all-zero
block. */
{
else
return gpg_error (GPG_ERR_INV_ARG);
return 0;
}
{
switch (cmd)
{
case GCRYCTL_SET_KEY: /* Deprecated; use gcry_cipher_setkey. */
break;
case GCRYCTL_SET_IV: /* Deprecated; use gcry_cipher_setiv. */
break;
case GCRYCTL_RESET:
cipher_reset (h);
break;
case GCRYCTL_CFB_SYNC:
cipher_sync( h );
break;
case GCRYCTL_SET_CBC_CTS:
if (buflen)
if (h->flags & GCRY_CIPHER_CBC_MAC)
else
h->flags |= GCRY_CIPHER_CBC_CTS;
else
h->flags &= ~GCRY_CIPHER_CBC_CTS;
break;
case GCRYCTL_SET_CBC_MAC:
if (buflen)
if (h->flags & GCRY_CIPHER_CBC_CTS)
else
h->flags |= GCRY_CIPHER_CBC_MAC;
else
h->flags &= ~GCRY_CIPHER_CBC_MAC;
break;
case GCRYCTL_DISABLE_ALGO:
/* This command expects NULL for H and BUFFER to point to an
integer with the algo number. */
return gcry_error (GPG_ERR_CIPHER_ALGO);
disable_cipher_algo( *(int*)buffer );
break;
case GCRYCTL_SET_CTR: /* Deprecated; use gcry_cipher_setctr. */
else
break;
case 61: /* Disable weak key detection (private). */
if (h->extraspec->set_extra_info)
else
break;
case 62: /* Return current input vector (private). */
/* This is the input block as used in CFB and OFB mode which has
initially been set as IV. The returned format is:
1 byte Actual length of the block in bytes.
n byte The block.
If the provided buffer is too short, an error is returned. */
else
{
unsigned char *ivp;
int n = h->unused;
if (!n)
*dst++ = n;
while (n--)
}
break;
default:
rc = GPG_ERR_INV_OP;
}
return gcry_error (rc);
}
/* Return information about the cipher handle H. CMD is the kind of
information requested. BUFFER and NBYTES are reserved for now.
There are no values for CMD yet defined.
The fucntion always returns GPG_ERR_INV_OP.
*/
{
(void)h;
(void)buffer;
(void)nbytes;
switch (cmd)
{
default:
}
return gcry_error (err);
}
/* Return information about the given cipher algorithm ALGO.
WHAT select the kind of information returned:
GCRYCTL_GET_KEYLEN:
Return the length of the key. If the algorithm ALGO
supports multiple key lengths, the maximum supported key length
is returned. The key length is returned as number of octets.
BUFFER and NBYTES must be zero.
GCRYCTL_GET_BLKLEN:
Return the blocklength of the algorithm ALGO counted in octets.
BUFFER and NBYTES must be zero.
GCRYCTL_TEST_ALGO:
Returns 0 if the specified algorithm ALGO is available for use.
BUFFER and NBYTES must be zero.
Note: Because this function is in most cases used to return an
integer value, we can make it easier for the caller to just look at
the return value. The caller will in all cases consult the value
and thereby detecting whether a error occured or not (i.e. while
checking the block size)
*/
{
unsigned int ui;
switch (what)
{
case GCRYCTL_GET_KEYLEN:
else
{
else
/* The only reason is an invalid algo or a strange
blocksize. */
}
break;
case GCRYCTL_GET_BLKLEN:
else
{
else
/* The only reason is an invalid algo or a strange
blocksize. */
}
break;
case GCRYCTL_TEST_ALGO:
else
break;
default:
}
return gcry_error (err);
}
/* This function returns length of the key for algorithm ALGO. If the
algorithm supports multiple key lengths, the maximum supported key
length is returned. On error 0 is returned. The key length is
returned as number of octets.
This is a convenience functions which should be preferred over
gcry_cipher_algo_info because it allows for proper type
checking. */
{
size_t n;
n = 0;
return n;
}
/* This functions returns the blocklength of the algorithm ALGO
counted in octets. On error 0 is returned.
This is a convenience functions which should be preferred over
gcry_cipher_algo_info because it allows for proper type
checking. */
{
size_t n;
n = 0;
return n;
}
/* Explicitly initialize this module. */
_gcry_cipher_init (void)
{
return err;
}
/* Get a list consisting of the IDs of the loaded cipher modules. If
LIST is zero, write the number of loaded cipher modules to
LIST_LENGTH and return. If LIST is non-zero, the first
*LIST_LENGTH algorithm IDs are stored in LIST, which must be of
according size. In case there are less cipher modules than
*LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */
{
return err;
}
/* Run the selftests for cipher algorithm ALGO with optional reporting
function REPORT. */
{
else
{
if (report)
"no selftest available" :
}
if (module)
{
}
}