cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
crypt.h
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib Internal General Header File *
4 * Copyright Peter Gutmann 1992-2007 *
5 * *
6 ****************************************************************************/
7 
8 #ifndef _CRYPT_DEFINED
9 
10 #define _CRYPT_DEFINED
11 
12 /* Various compilers handle includes in subdirectories differently. Most
13  will work with paths from a root directory. Non-OS X Macintoshes don't
14  recognise '/'s as path delimiters, but work around it by scanning all
15  subdirectories and treating the files as if they were in the same
16  directory (INC_ALL). Microsoft C, in a braindamaged exception to all
17  other compilers, treats the subdirectory as the root, unless explicitly
18  told to use the project-file directory by setting Project | Settings |
19  C/C++ | Preprocessor | Additional include directories to '.\'. The
20  Tandem NSK (Guardian) filesystem doesn't have subdirectories, and the C
21  compiler zaps '.'s, truncates filenames to 7 characters, and appends a
22  'h' to the name (so that asn1misc.h becomes asn1mish). This
23  unfortunately requires a bit of renaming for header files. Tandem OSS
24  (Unix services) on the other hand is just like Unix, so we explicitly
25  distinguish between the two */
26 
27 #if defined( SYMANTEC_C ) && !defined( INC_ALL )
28  #error You need to predefine INC_ALL in your project file
29 #endif /* Checks for various compiler/OS-dependant include paths */
30 
31 /* If we're on a new enough version of VC++ or Metrowerks, set a flag to
32  only include header files once */
33 
34 #if ( defined( _MSC_VER ) && ( _MSC_VER >= 1000 ) ) || defined ( __MWERKS__ )
35  #pragma once
36 #endif /* VC++ 5.0 or higher, Metrowerks */
37 
38 /* Enable use of the TR 24731 safe stdlib extensions if they're available */
39 
40 #if !defined( __STDC_WANT_LIB_EXT1__ )
41  #define __STDC_WANT_LIB_EXT1__ 1
42 #endif /* TR 24731 safe stdlib extensions */
43 
44 /* If we're building under Win32, don't haul in the huge amount of cruft
45  that windows.h brings with it. We need to define these values before
46  we include cryptlib.h since this is where windows.h is included */
47 
48 #if ( defined( _WINDOWS ) || defined( WIN32 ) || defined( _WIN32 ) || \
49  defined( __WIN32__ ) ) && !defined( _SCCTK )
50  #define NOATOM /* Atom Manager routines */
51  #define NOMCX /* Modem Configuration Extensions */
52 /*#define NOCLIPBOARD // Clipboard routines, needed for randomness polling */
53  #define NOCOLOR /* Screen colors */
54  #define NOCOMM /* COMM driver routines */
55  #define NOCTLMGR /* Control and Dialog routines */
56  #define NODEFERWINDOWPOS /* DeferWindowPos routines */
57  #define NODRAWTEXT /* DrawText() and DT_* */
58  #define NOGDI /* All GDI defines and routines */
59  #define NOGDICAPMASKS /* CC_*, LC_*, PC_*, CP_*, TC_*, RC_ */
60  #define NOHELP /* Help engine interface */
61  #define NOICONS /* IDI_* */
62  #define NOKANJI /* Kanji support stuff */
63  #define NOKEYSTATES /* MK_* */
64  #define NOMB /* MB_* and MessageBox() */
65  #define NOMCX /* Modem Configuration Extensions */
66  #define NOMEMMGR /* GMEM_*, LMEM_*, GHND, LHND, etc */
67  #define NOMENUS /* MF_* */
68  #define NOMETAFILE /* typedef METAFILEPICT */
69  #if defined( _MSC_VER ) && ( _MSC_VER > 800 )
70  #define NOMSG /* typedef MSG and associated routines */
71  #endif /* !Win16 */
72  #define NONLS /* NLS routines */
73  #define NOPROFILER /* Profiler interface */
74  #define NORASTEROPS /* Binary and Tertiary raster ops */
75  #define NOSCROLL /* SB_* and scrolling routines */
76  #define NOSERVICE /* All Service Controller routines, SERVICE_* */
77  #define NOSHOWWINDOW /* SW_* */
78  #define NOSOUND /* Sound driver routines */
79  #define NOSYSCOMMANDS /* SC_* */
80  #define NOSYSMETRICS /* SM_* */
81  #define NOTEXTMETRIC /* typedef TEXTMETRIC and associated routines */
82  #define NOVIRTUALKEYCODES /* VK_* */
83  #define NOWH /* SetWindowsHook and WH_* */
84  #define NOWINMESSAGES /* WM_*, EM_*, LB_*, CB_* */
85  #define NOWINOFFSETS /* GWL_*, GCL_*, associated routines */
86  #define NOWINSTYLES /* WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* */
87  #define OEMRESOURCE /* OEM Resource values */
88 #endif /* Win32 */
89 
90 /* The Palm OS SDK compiler tries to make enums as small as possible (8-bit
91  unsigned chars if it can, otherwise 16-bit unsigned shorts, otherwise
92  ints) for backwards-compatibility with the old 68K-based Palm interface,
93  which causes severe problems for code that assumes that enum == int
94  (this occurs in a number of places where an integer parameter is used to
95  pass a generic value to/from a function). CodeWarrior allows this enum
96  behaviour to be turned off, but pacc doesn't.
97 
98  Similarly, the MSDOS-derived (!!) Watcom C compiler used with older
99  versions of QNX 4.x uses 16-bit enums (DOS 16-bit ints) if possible, and
100  again there's no way to disable this behaviour (there is with newer
101  versions, the pragma to fix the problem is used further down).
102 
103  To fix this, we take advantage of the fact that every typedef'd enum has
104  a _LAST member as the last entry and override it to include an additional
105  value that forces the enum range into the 32-bit int range */
106 
107 #if ( defined( __PALMSOURCE__ ) && defined( _PACC_VER ) ) || \
108  ( defined( __QNX__ ) && ( OSVERSION <= 4 ) )
109  #define NEED_ENUMFIX /* Remember to undo defines later */
110 
111  /* cryptlib.h */
112  #define CRYPT_ALGO_LAST CRYPT_ALGO_LAST, CRYPT_ALGO_ENUM = -50000
113  #define CRYPT_MODE_LAST CRYPT_MODE_LAST, CRYPT_MODE_ENUM = -50000
114  #define CRYPT_KEYSET_LAST CRYPT_KEYSET_LAST, CRYPT_KEYSET_ENUM = -50000
115  #define CRYPT_DEVICE_LAST CRYPT_DEVICE_LAST, CRYPT_DEVICE_ENUM = -50000
116  #define CRYPT_CERTTYPE_LAST CRYPT_CERTTYPE_LAST, CRYPT_CERTTYPE_ENUM = -50000
117  #define CRYPT_FORMAT_LAST CRYPT_FORMAT_LAST, CRYPT_FORMAT_ENUM = -50000
118  #define CRYPT_SESSION_LAST CRYPT_SESSION_LAST, CRYPT_SESSION_ENUM = -50000
119  #define CRYPT_USER_LAST CRYPT_USER_LAST, CRYPT_USER_ENUM = -50000
120  #define CRYPT_IATTRIBUTE_LAST CRYPT_IATTRIBUTE_LAST, CRYPT_IATTRIBUTE_ENUM = -50000
121  #define CRYPT_CRLEXTREASON_LAST CRYPT_CRLEXTREASON_LAST, CRYPT_CRLEXTREASON_ENUM = -50000
122  #define CRYPT_CONTENT_LAST CRYPT_CONTENT_LAST, CRYPT_CONTENT_ENUM = -50000
123  #define CRYPT_SIGNATURELEVEL_LAST CRYPT_SIGNATURELEVEL_LAST, CRYPT_SIGNATURELEVEL_ENUM = -50000
124  #define CRYPT_CERTFORMAT_LAST CRYPT_CERTFORMAT_LAST
125  #define CRYPT_REQUESTTYPE_LAST CRYPT_REQUESTTYPE_LAST, CRYPT_REQUESTTYPE_ENUM = -50000
126  #define CRYPT_KEYID_LAST CRYPT_KEYID_LAST, CRYPT_KEYID_ENUM = -50000
127  #define CRYPT_OBJECT_LAST CRYPT_OBJECT_LAST, CRYPT_OBJECT_ENUM = -50000
128  #define CRYPT_ERRTYPE_LAST CRYPT_ERRTYPE_LAST, CRYPT_ERRTYPE_ENUM = -50000
129  #define CRYPT_CERTACTION_LAST CRYPT_CERTACTION_LAST, CRYPT_CERTACTION_ENUM = -50000
130  #define CRYPT_KEYOPT_LAST CRYPT_KEYOPT_LAST, CRYPT_KEYOPT_ENUM = -50000
131  /* crypt.h */
132  #define KEYFORMAT_LAST KEYFORMAT_LAST, KEYFORMAT_ENUM = -50000
133  #define CERTFORMAT_LAST CERTFORMAT_LAST, CERTFORMAT_ENUM = -50000
134  #define MANAGEMENT_ACTION_LAST MANAGEMENT_ACTION_LAST, MANAGEMENT_ACTION_ENUM = -50000
135  #define HASH_LAST HASH_LAST, HASH_ENUM = -50000
136  #define ATTR_LAST ATTR_LAST, ATTR_ENUM = -50000
137  /* cryptkrn.h */
138  #define MESSAGE_COMPARE_LAST MESSAGE_COMPARE_LAST, MESSAGE_COMPARE_ENUM = -50000
139  #define MESSAGE_CHECK_LAST MESSAGE_CHECK_LAST, MESSAGE_CHECK_ENUM = -50000
140  #define MESSAGE_CHANGENOTIFY_LAST MESSAGE_CHANGENOTIFY_LAST, MESSAGE_CHANGENOTIFY_ENUM = -50000
141  #define MECHANISM_LAST MECHANISM_LAST, MECHANISM_ENUM = -50000
142  #define KEYMGMT_ITEM_LAST KEYMGMT_ITEM_LAST, KEYMGMT_ITEM_ENUM = -50000
143  #define SEMAPHORE_LAST SEMAPHORE_LAST, SEMAPHORE_ENUM = -50000
144  #define MUTEX_LAST MUTEX_LAST, MUTEX_ENUM = -50000
145  /* cert/cert.h */
146  #define RTCSRESPONSE_TYPE_LAST RTCSRESPONSE_TYPE_LAST, RTCSRESPONSE_TYPE_ENUM = -50000
147  #define ATTRIBUTE_LAST ATTRIBUTE_LAST, ATTRIBUTE_ENUM = -50000
148  #define POLICY_LAST POLICY_LAST, POLICY_ENUM = -50000
149  #define SELECTION_OPTION_LAST SELECTION_OPTION_LAST, SELECTION_OPTION_ENUM = -50000
150  /* context/context.h */
151  #define CONTEXT_LAST CONTEXT_LAST, CONTEXT_ENUM = -50000
152  /* device/capabil.h */
153  #define CAPABILITY_INFO_LAST CAPABILITY_INFO_LAST, CAPABILITY_INFO_ENUM = -50000
154  /* enc_dec/asn1.h */
155  #define BER_ID_LAST BER_ID_LAST, BER_ID_ENUM = -50000
156  /* envelope/envelope.h */
157  #define ACTION_LAST ACTION_LAST, ACTION_ENUM = -50000
158  #define ACTION_RESULT_LAST ACTION_RESULT_LAST, ACTION_RESULT_ENUM = -50000
159  #define STATE_LAST STATE_LAST, STATE_ENUM = -50000
160  #define ENVSTATE_LAST ENVSTATE_LAST, ENVSTATE_ENUM = -50000
161  #define DEENVSTATE_LAST DEENVSTATE_LAST, DEENVSTATE_ENUM = -50000
162  #define PGP_DEENVSTATE_LAST PGP_DEENVSTATE_LAST, PGP_DEENVSTATE_ENUM = -50000
163  #define SEGHDRSTATE_LAST SEGHDRSTATE_LAST, SEGHDRSTATE_ENUM = -50000
164  /* kernel/acl.h */
165  #define RANGEVAL_LAST RANGEVAL_LAST, RANGEVAL_ENUM = -50000
166  #define ATTRIBUTE_VALUE_LAST ATTRIBUTE_VALUE_LAST, ATTRIBUTE_VALUE_ENUM = -50000
167  #define PARAM_VALUE_LAST PARAM_VALUE_LAST, PARAM_VALUE_ENUM = -50000
168  /* kernel/kernel.h */
169  #define SEMAPHORE_STATE_LAST SEMAPHORE_STATE_LAST, SEMAPHORE_STATE_ENUM = -50000
170  /* keyset/dbms.h */
171  #define CERTADD_LAST CERTADD_LAST, CERTADD_ENUM = -50000
172  /* keyset/keyset.h */
173  #define KEYSET_SUBTYPE_LAST KEYSET_SUBTYPE_LAST, KEYSET_SUBTYPE_ENUM = -50000
174  #define DBMS_QUERY_LAST DBMS_QUERY_LAST, DBMS_QUERY_ENUM = -50000
175  #define DBMS_UPDATE_LAST DBMS_UPDATE_LAST, DBMS_UPDATE_ENUM = -50000
176  #define DBMS_CACHEDQUERY_LAST DBMS_CACHEDQUERY_LAST, DBMS_CACHEDQUERY_ENUM = -50000
177  /* keyset/pkcs15.h */
178  #define PKCS15_SUBTYPE_LAST PKCS15_SUBTYPE_LAST, PKCS15_SUBTYPE_ENUM = -50000
179 // #define PKCS15_OBJECT_LAST PKCS15_OBJECT_LAST, PKCS15_OBJECT_ENUM = -50000
180  #define PKCS15_KEYID_LAST PKCS15_KEYID_LAST, PKCS15_KEYID_ENUM = -50000
181  /* misc/pgp.h */
182  #define PGP_ALGOCLASS_LAST PGP_ALGOCLASS_LAST, PGP_ALGOCLASS_ENUM = -50000
183  /* misc/rpc.h */
184  #define COMMAND_LAST COMMAND_LAST, COMMAND_ENUM = -50000
185  #define DBX_COMMAND_LAST DBX_COMMAND_LAST, DBX_COMMAND_ENUM = -50000
186  /* io/stream.h */
187  #define STREAM_TYPE_LAST STREAM_TYPE_LAST, STREAM_TYPE_ENUM = -50000
188  #define BUILDPATH_LAST BUILDPATH_LAST, BUILDPATH_ENUM = -50000
189  #define STREAM_IOCTL_LAST STREAM_IOCTL_LAST, STREAM_IOCTL_ENUM = -50000
190  #define STREAM_PROTOCOL_LAST STREAM_PROTOCOL_LAST, STREAM_PROTOCOL_ENUM = -50000
191  #define URL_TYPE_LAST URL_TYPE_LAST, URL_TYPE_ENUM = -50000
192  #define NET_OPTION_LAST NET_OPTION_LAST, NET_OPTION_ENUM = -50000
193  /* session/cmp.h */
194  #define CMPBODY_LAST CMPBODY_LAST, CMPBODY_ENUM = -50000
195  /* session/session.h */
196  #define READINFO_LAST READINFO_LAST, READINFO_ENUM = -50000
197  /* session/ssh.h */
198  #define CHANNEL_LAST CHANNEL_LAST, CHANNEL_ENUM = -50000
199  #define MAC_LAST MAC_LAST, MAC_ENUM = -50000
200  #define SSH_ATRIBUTE_LAST SSH_ATRIBUTE_LAST, SSH_ATRIBUTE_ENUM = -50000
201  /* session/ssl.h */
202  #define SSL_LAST SSL_LAST, SSL_ENUM = -50000
203  #define TLS_EXT_LAST TLS_EXT_LAST, TLS_EXT_ENUM = -50000
204 #endif /* Palm SDK compiler enum fix */
205 
206 /* Global headers used in almost every module */
207 
208 #include <stdlib.h>
209 #include <string.h>
210 
211 /* If the global cryptlib header hasn't been included yet, include it now */
212 
213 #ifndef _CRYPTLIB_DEFINED
214  #include "cryptlib.h"
215 #endif /* _CRYPTLIB_DEFINED */
216 
217 /* Since some of the _LAST types are used in the code, we have to undefine
218  them again if they've been used in the enum-fix kludge */
219 
220 #ifdef NEED_ENUMFIX
221  #undef CRYPT_ALGO_LAST
222  #undef CRYPT_MODE_LAST
223  #undef CRYPT_KEYSET_LAST
224  #undef CRYPT_DEVICE_LAST
225  #undef CRYPT_CERTTYPE_LAST
226  #undef CRYPT_FORMAT_LAST
227  #undef CRYPT_SESSION_LAST
228  #undef CRYPT_USER_LAST
229  #undef CRYPT_IATTRIBUTE_LAST
230  #undef CRYPT_CRLEXTREASON_LAST
231  #undef CRYPT_CONTENT_LAST
232  #undef CRYPT_SIGNATURELEVEL_LAST
233  #undef CRYPT_CERTFORMAT_LAST
234  #undef CRYPT_REQUESTTYPE_LAST
235  #undef CRYPT_KEYID_LAST
236  #undef CRYPT_OBJECT_LAST
237  #undef CRYPT_ERRTYPE_LAST
238  #undef CRYPT_CERTACTION_LAST
239  #undef CRYPT_KEYOPT_LAST
240 #endif /* NEED_ENUMFIX */
241 
242 /****************************************************************************
243 * *
244 * System- and Compiler-Specific Defines *
245 * *
246 ****************************************************************************/
247 
248 /* Pull in the system and compiler-specific defines and values */
249 
250 #if defined( INC_ALL )
251  #include "os_spec.h"
252 #else
253  #include "misc/os_spec.h"
254 #endif /* Compiler-specific includes */
255 
256 /* Pull in the source code analysis header */
257 
258 #if defined( INC_ALL )
259  #include "analyse.h"
260 #else
261  #include "misc/analyse.h"
262 #endif /* Compiler-specific includes */
263 
264 /****************************************************************************
265 * *
266 * Config Options *
267 * *
268 ****************************************************************************/
269 
270 /* Pull in the cryptlib initialisation options file, which contains the
271  various USE_xxx defines that enable different cryptlib features. Note
272  that this *must* be included after os_spec.h, which performs OS detection
273  used by config.h to enable/disable various code features */
274 
275 #if defined( INC_ALL )
276  #include "config.h"
277 #else
278  #include "misc/config.h"
279 #endif /* Compiler-specific includes */
280 
281 /****************************************************************************
282 * *
283 * Kernel Interface *
284 * *
285 ****************************************************************************/
286 
287 /* Pull in the cryptlib kernel interface defines */
288 
289 #include "cryptkrn.h"
290 
291 /****************************************************************************
292 * *
293 * Portability Defines *
294 * *
295 ****************************************************************************/
296 
297 /* Read/write values as 16- and 32-bit big-endian data in cases where we're
298  not dealing with a stream. Usage:
299 
300  mget/putWord():
301  CMP "TCP" protocol (disabled by default).
302  SSHv1 (disabled by default).
303  SOCKS wrapper in network code (disabled by default).
304 
305  mget/putLong():
306  CMP "TCP" protocol, also used in TSP (disabled by default in both).
307  SSHv1 (disabled by default).
308  Sampling data from the crypto RNG to detect stuck-at faults.
309  Debug version of clAlloc() */
310 
311 #if defined( USE_CMP_TRANSPORT ) || defined( USE_SSH1 )
312 
313 #define mgetWord( memPtr ) \
314  ( ( ( unsigned int ) memPtr[ 0 ] << 8 ) | \
315  ( unsigned int ) memPtr[ 1 ] ); \
316  memPtr += 2
317 
318 #define mputWord( memPtr, data ) \
319  memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
320  memPtr[ 1 ] = ( BYTE ) ( ( data ) & 0xFF ); \
321  memPtr += 2
322 
323 #endif /* USE_CMP_TRANSPORT || USE_SSH1 */
324 
325 #define mgetLong( memPtr ) \
326  ( ( ( unsigned long ) memPtr[ 0 ] << 24 ) | \
327  ( ( unsigned long ) memPtr[ 1 ] << 16 ) | \
328  ( ( unsigned long ) memPtr[ 2 ] << 8 ) | \
329  ( unsigned long ) memPtr[ 3 ] ); \
330  memPtr += 4
331 
332 #define mputLong( memPtr, data ) \
333  memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 24 ) & 0xFF ); \
334  memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 16 ) & 0xFF ); \
335  memPtr[ 2 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
336  memPtr[ 3 ] = ( BYTE ) ( ( data ) & 0xFF ); \
337  memPtr += 4
338 
339 /****************************************************************************
340 * *
341 * Data Size and Crypto-related Constants *
342 * *
343 ****************************************************************************/
344 
345 /* Pull in the data-size and crypt-related constants */
346 
347 #if defined( INC_ALL )
348  #include "consts.h"
349 #else
350  #include "misc/consts.h"
351 #endif /* Compiler-specific includes */
352 
353 /****************************************************************************
354 * *
355 * Data Structures *
356 * *
357 ****************************************************************************/
358 
359 /* Information on exported key/signature data. This is an extended version
360  of the data returned by the externally-visible cryptQueryObject() routine */
361 
362 typedef struct {
363  /* Object format and status information */
364  CRYPT_FORMAT_TYPE formatType; /* Object format type */
365  CRYPT_OBJECT_TYPE type; /* Object type */
366  long size; /* Object size */
367  int version; /* Object format version */
368 
369  /* The encryption algorithm and mode */
370  CRYPT_ALGO_TYPE cryptAlgo; /* The encryption algorithm */
371  CRYPT_MODE_TYPE cryptMode; /* The encryption mode */
372 
373  /* The key ID for public key objects */
375  BYTE keyID[ CRYPT_MAX_HASHSIZE + 8 ];/* PKC key ID */
377 
378  /* The IV for conventionally encrypted data */
380  BYTE iv[ CRYPT_MAX_IVSIZE + 8 ];/* IV */
381  int ivLength;
382 
383  /* The key derivation algorithm and iteration count for conventionally
384  encrypted keys */
385  CRYPT_ALGO_TYPE keySetupAlgo; /* Key setup algorithm */
386  int keySetupIterations; /* Key setup iteration count */
387  int keySize; /* Key size (if not implicit) */
389  BYTE salt[ CRYPT_MAX_HASHSIZE + 8 ];/* Key setup salt */
391 
392  /* The hash algorithm for signatures */
393  CRYPT_ALGO_TYPE hashAlgo; /* Hash algorithm */
394  int hashParam; /* Optional algorithm parameter */
395 
396  /* The encoded parameter data for authenticated encryption, and the
397  encryption and MAC algorithm parameter data within that */
398  BUFFER( 128, authEncParamLength ) \
399  BYTE authEncParamData[ 128 + 8 ];
400  int authEncParamLength; /* AuthEnc parameter data */
401  int encParamStart, encParamLength; /* Position of enc.parameters */
402  int macParamStart, macParamLength; /* Position of MAC parameters */
403 
404  /* The start and length of the payload data, either the encrypted key or
405  the signature data */
407 
408  /* The start and length of the issuerAndSerialNumber, authenticated
409  attributes, and unauthenticated attributes for CMS objects */
410  int iAndSStart, iAndSLength;
412  int unauthAttributeStart, unauthAttributeLength;
413  } QUERY_INFO;
414 
415 /* DLP algorithms require composite parameters when en/decrypting and
416  signing/sig checking, so we can't just pass in a single buffer full of
417  data as we can with RSA. In addition the data length changes, for
418  example for a DSA sig we pass in a 20-byte hash and get back a ~50-byte
419  sig, for sig.checking we pass in a 20-byte hash and ~50-byte sig and get
420  back nothing. Because of this we have to use the following structure to
421  pass data to the DLP-based PKCs */
422 
423 typedef struct {
424  BUFFER_FIXED( inLen1 ) \
425  const BYTE *inParam1;
426  BUFFER_OPT_FIXED( inLen2 ) \
427  const BYTE *inParam2; /* Input parameters */
428  BUFFER_FIXED( outLen ) \
429  BYTE *outParam; /* Output parameter */
430  int inLen1, inLen2, outLen; /* Parameter lengths */
431  CRYPT_FORMAT_TYPE formatType; /* Paramter format type */
432  } DLP_PARAMS;
433 
434 #define setDLPParams( dlpDataPtr, dataIn, dataInLen, dataOut, dataOutLen ) \
435  { \
436  memset( ( dlpDataPtr ), 0, sizeof( DLP_PARAMS ) ); \
437  ( dlpDataPtr )->formatType = CRYPT_FORMAT_CRYPTLIB; \
438  ( dlpDataPtr )->inParam1 = ( dataIn ); \
439  ( dlpDataPtr )->inLen1 = ( dataInLen ); \
440  ( dlpDataPtr )->outParam = ( dataOut ); \
441  ( dlpDataPtr )->outLen = ( dataOutLen ); \
442  }
443 
444 /* When calling key agreement functions we have to pass a mass of cruft
445  around instead of the usual flat data (even more than the generic DLP
446  parameter information) for which we use the following structure. The
447  public value is the public key value used for the agreement process,
448  typically y = g^x mod p for DH-like mechanisms. The ukm is the user
449  keying material, typically something which is mixed into the DH process
450  to make the new key unique. The wrapped key is the output (originator)/
451  input(recipient) to the keyagreement process. The session key context
452  contains a context into which the derived key is loaded. Typical
453  examples of use are:
454 
455  PKCS #3: publicValue = y
456  S/MIME: publicValue = y, ukm = 512-bit nonce, wrappedKey = g^x mod p
457  SSH, SSL: publicValue = y, wrappedKey = x */
458 
459 typedef struct {
460  BUFFER( CRYPT_MAX_PKCSIZE, publicValueLen ) \
461  BYTE publicValue[ CRYPT_MAX_PKCSIZE + 8 ];
462  int publicValueLen; /* Public key value */
463  BUFFER( CRYPT_MAX_PKCSIZE, wrappedKeyLen ) \
464  BYTE wrappedKey[ CRYPT_MAX_PKCSIZE + 8 ];
465  int wrappedKeyLen; /* Wrapped key */
466  } KEYAGREE_PARAMS;
467 
468 /****************************************************************************
469 * *
470 * Useful General Macros *
471 * *
472 ****************************************************************************/
473 
474 /* Reasonably reliable way to get rid of unused argument warnings in a
475  compiler-independant manner */
476 
477 #define UNUSED_ARG( arg ) ( ( arg ) = ( arg ) )
478 
479 /* Although min() and max() aren't in the ANSI standard, most compilers have
480  them in one form or another, but just enough don't that we need to define
481  them ourselves in some cases */
482 
483 #if !defined( min )
484  #ifdef MIN
485  #define min MIN
486  #define max MAX
487  #else
488  #define min( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) )
489  #define max( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
490  #endif /* Various min/max macros */
491 #endif /* !min/max */
492 
493 /* Macros to convert to and from the bit counts used for some encryption
494  parameters */
495 
496 #define bitsToBytes( bits ) ( ( ( bits ) + 7 ) >> 3 )
497 #define bytesToBits( bytes ) ( ( bytes ) << 3 )
498 
499 /* When initialising a static block of bytes, it's useful to be able to
500  specify it as a character string, however this runs into problems with
501  the fact that the default char type is signed. To get around this the
502  following macro declares a byte string as a set of unsigned bytes */
503 
504 #define MKDATA( x ) ( ( unsigned char * ) ( x ) )
505 
506 /* Macro to round a value up to the nearest multiple of a second value,
507  with the second value being a power of 2 */
508 
509 #define roundUp( size, roundSize ) \
510  ( ( ( size ) + ( ( roundSize ) - 1 ) ) & ~( ( roundSize ) - 1 ) )
511 
512 /* A macro to clear sensitive data from memory. This is somewhat easier to
513  use than calling memset with the second parameter set to 0 all the time,
514  and makes it obvious where sensitive data is being erased. In addition
515  some systems, recognising the problem, have distinct memory zeroisation
516  support, so if available we use that */
517 
518 #if defined( _MSC_VER ) && VC_GE_2005( _MSC_VER )
519  /* This isn't terribly spectacular, just a mapping to
520  RtlSecureZeroMemory() which is implemented as inline code implementing
521  a loop on a pointer declared volatile, but there's an implied contract
522  that future versions will always zeroise memory even in the face of
523  compiler changes that would otherwise optimise away the access */
524  #define zeroise( memory, size ) SecureZeroMemory( memory, size )
525 #else
526  #define zeroise( memory, size ) memset( memory, 0, size )
527 #endif /* Systems with distinct zeroise functions */
528 
529 /* A macro to check that a value is a possibly valid handle. This doesn't
530  check that the handle refers to a valid object, merely that the value is
531  in the range for valid handles. The full function isValidHandle() used
532  in the kernel does check that the handle refers to a valid object, being
533  more than just a range check */
534 
535 #define isHandleRangeValid( handle ) \
536  ( ( handle ) > NO_SYSTEM_OBJECTS - 1 && ( handle ) < MAX_OBJECTS )
537 
538 /* A macro to check whether an encryption mode needs an IV or not */
539 
540 #define needsIV( mode ) ( ( mode ) == CRYPT_MODE_CBC || \
541  ( mode ) == CRYPT_MODE_CFB || \
542  ( mode ) == CRYPT_MODE_OFB || \
543  ( mode ) == CRYPT_MODE_GCM )
544 
545 /* A macro to check whether an algorithm is a pure stream cipher (that is,
546  a real stream cipher rather than just a block cipher run in a stream
547  mode) */
548 
549 #define isStreamCipher( algorithm ) ( ( algorithm ) == CRYPT_ALGO_RC4 )
550 
551 /* A macro to check whether an algorithm is regarded as being (relatively)
552  insecure or not. This is used by some of the higher-level internal
553  routines that normally use the default algorithm set in the configuration
554  database if nothing else is explicitly specified, but that specifically
555  check for the weaker algorithms and use something stronger instead if a
556  weak algorithm is specified. This is done both for luser-proofing and to
557  avoid possible problems from a trojan patching the configuration
558  database */
559 
560 #define isWeakCryptAlgo( algorithm ) ( ( algorithm ) == CRYPT_ALGO_DES || \
561  ( algorithm ) == CRYPT_ALGO_RC2 || \
562  ( algorithm ) == CRYPT_ALGO_RC4 )
563 #define isWeakHashAlgo( algorithm ) ( ( algorithm ) == CRYPT_ALGO_MD5 )
564 #define isWeakMacAlgo( algorithm ) ( ( algorithm ) == CRYPT_ALGO_HMAC_MD5 )
565  /* Technically not weak, but somewhat
566  tainted */
567 
568 /* Macros to check for membership in overall algorithm classes */
569 
570 #define isConvAlgo( algorithm ) \
571  ( ( algorithm ) >= CRYPT_ALGO_FIRST_CONVENTIONAL && \
572  ( algorithm ) <= CRYPT_ALGO_LAST_CONVENTIONAL )
573 #define isPkcAlgo( algorithm ) \
574  ( ( algorithm ) >= CRYPT_ALGO_FIRST_PKC && \
575  ( algorithm ) <= CRYPT_ALGO_LAST_PKC )
576 #define isHashAlgo( algorithm ) \
577  ( ( algorithm ) >= CRYPT_ALGO_FIRST_HASH && \
578  ( algorithm ) <= CRYPT_ALGO_LAST_HASH )
579 #define isMacAlgo( algorithm ) \
580  ( ( algorithm ) >= CRYPT_ALGO_FIRST_MAC && \
581  ( algorithm ) <= CRYPT_ALGO_LAST_MAC )
582 #define isSpecialAlgo( algorithm ) \
583  ( ( algorithm ) == CRYPT_IALGO_GENERIC_SECRET )
584 
585 /* Macros to check whether a PKC algorithm is useful for a certain purpose
586  or requires special-case handling. Note that isDlpAlgo() doesn't include
587  the ECC algorithms, which are also based on the DLP (although in this
588  case the ECDLP and not the standard DLP). This is a bit ugly but it's
589  used in various places to distinguish DLP-based PKCs from non-DLP-based
590  PKCs, while ECDLP-based-PKCs are in a separate class. This means that
591  when checking for the extended class { DLP | ECDLP } it's necessary to
592  explicitly include isEccAlgo() alongside isDlpAlgo() */
593 
594 #define isSigAlgo( algorithm ) \
595  ( ( algorithm ) == CRYPT_ALGO_RSA || ( algorithm ) == CRYPT_ALGO_DSA || \
596  ( algorithm ) == CRYPT_ALGO_ECDSA )
597 #define isCryptAlgo( algorithm ) \
598  ( ( algorithm ) == CRYPT_ALGO_RSA || ( algorithm ) == CRYPT_ALGO_ELGAMAL )
599 #define isKeyxAlgo( algorithm ) \
600  ( ( algorithm ) == CRYPT_ALGO_DH || ( algorithm ) == CRYPT_ALGO_ECDH )
601 #define isDlpAlgo( algorithm ) \
602  ( ( algorithm ) == CRYPT_ALGO_DSA || ( algorithm ) == CRYPT_ALGO_ELGAMAL || \
603  ( algorithm ) == CRYPT_ALGO_DH )
604 #define isEccAlgo( algorithm ) \
605  ( ( algorithm ) == CRYPT_ALGO_ECDSA || ( algorithm ) == CRYPT_ALGO_ECDH )
606 
607 /* Macros to check whether an algorithm has additional parameters that need
608  to be handled explicitly */
609 
610 #define isParameterisedConvAlgo( algorithm ) \
611  ( ( algorithm ) == CRYPT_ALGO_AES )
612 #define isParameterisedHashAlgo( algorithm ) \
613  ( ( algorithm ) == CRYPT_ALGO_SHA2 || ( algorithm ) == CRYPT_ALGO_SHAng )
614 #define isParameterisedMacAlgo( algorithm ) \
615  ( ( algorithm ) == CRYPT_ALGO_HMAC_SHA2 || \
616  ( algorithm ) == CRYPT_ALGO_HMAC_SHAng )
617 
618 /* A macro to check whether an error status is related to a data-formatting
619  problem or some other problem. This is used to provide extended string-
620  format error information, if it's a data error then the message being
621  processed was (probably) invalid, if it's not a data error then it may be
622  due to an invalid decryption key being used or something similar that's
623  unrelated to the message itself.
624 
625  The exact definition of what constitutes a "data error" is a bit vague
626  but since it's only used to control what additional error information is
627  returned a certain level of fuzziness is permitted */
628 
629 #define isDataError( status ) \
630  ( ( ( status ) >= CRYPT_ERROR_OVERFLOW && \
631  ( status ) <= CRYPT_ERROR_SIGNATURE ) ) || \
632  ( ( status ) == CRYPT_ERROR_NOTAVAIL || \
633  ( status ) == CRYPT_ERROR_INCOMPLETE || \
634  ( status ) == CRYPT_ERROR_COMPLETE || \
635  ( status ) == CRYPT_ERROR_INVALID )
636 
637 /* A macro to check whether a public key is too short to be secure. This
638  is a bit more complex than just a range check because any length below
639  about 512 bits is probably a bad data error, while lengths from about
640  512 bits to MIN_PKCSIZE (for standard PKCs) or 120 bits to
641  MIN_PKCSIZE_ECC are too-short key errors */
642 
643 #define isShortPKCKey( keySize ) \
644  ( ( keySize ) >= MIN_PKCSIZE_THRESHOLD && \
645  ( keySize ) < MIN_PKCSIZE )
646 #define isShortECCKey( keySize ) \
647  ( ( keySize ) >= MIN_PKCSIZE_ECC_THRESHOLD && \
648  ( keySize ) < MIN_PKCSIZE_ECC )
649 
650 /* Perform a range check on a block of memory, checking that
651  { start, length } falls within { 0, totalLength }. There are two
652  versions of this, the default which requires a nonzero start offset and
653  the special-case variant which allows a zero start offset, which is used
654  for situations like optionally MIME-wrapped data which have a nonzero
655  offset if there's a MIME header to be skipped but a zero offset if it's
656  unencapsulated data */
657 
658 #define rangeCheck( start, length, totalLength ) \
659  ( ( start ) <= 0 || ( length ) < 1 || \
660  ( start ) + ( length ) > ( totalLength ) ) ? FALSE : TRUE
661 #define rangeCheckZ( start, length, totalLength ) \
662  ( ( start ) < 0 || ( length ) < 1 || \
663  ( start ) + ( length ) > ( totalLength ) ) ? FALSE : TRUE
664 
665 /* Check the validity of a pointer passed to a cryptlib function. Usually
666  the best that we can do is check that it's not null, but some OSes allow
667  for better checking than this, for example that it points to a block of
668  readable or writeable memory. Under Windows IsBadReadPtr() will always
669  succeed if the size is 0, so we have to add a separate check to make sure
670  that it's non-NULL.
671 
672  There are additional caveats with the use of the Windows memory-checking
673  functions. In theory these would be implemented via VirtualQuery(),
674  however this is quite slow, requiring a kernel transition and poking
675  around with the page protection mechanisms. Instead, they try and read
676  or write the memory, with an exception handler wrapped around the access.
677  If the exception is thrown, they fail. The problem with this way of
678  doing things is that if the memory address is a stack guard page used to
679  grow the stack (when the system-level exception handler sees an access to
680  the bottom-of-stack guard page, it knows that it has to grow the stack)
681  *and* the guard page is owned by another thread, IsBadXxxPtr() will catch
682  the exception and the system will never see it, so it can't grow the
683  stack past the current limit (note that this only occurs if the guard
684  page that we hit is owned by a different thread; if we own in then the
685  kernel will catch the STATUS_GUARD_PAGE_VIOLATION exception and grow the
686  stack as required). In addition if it's the last guard page then instead
687  of getting an "out of stack" exception, it's turned into a no-op. The
688  second time the last guard page is hit, the application is terminated by
689  the system, since it's passed its first-chance exception.
690 
691  A variation of this is that the calling app could be deliberately passing
692  a pointer to a guard page and catching the guard page exception in order
693  to dynamically generate the data that would fill the page (this can
694  happen for example when simulating a large address space with pointer
695  swizzling), but this is a pretty weird programming technique that's
696  unlikely to be used with a crypto library.
697 
698  A lesser problem is that there's a race condition in the checking, since
699  the memory can be unmapped between the IsBadXxxPtr() check and the actual
700  access, but you'd pretty much have to be trying to actively subvert the
701  checks to do something like this.
702 
703  For these reasons we use these functions mostly for debugging, wrapping
704  them up in assert()s in most cases where they're used. Under Windows
705  Vista they've actually been turned into no-ops because of the above
706  problems, although it's probable that they'll be replaced by code to
707  check for NULL pointers, since Microsoft's docs indicate that this much
708  checking will still be done. If necessary we could also replace the
709  no-op'd out versions with the equivalent code:
710 
711  inline BOOL IsBadReadPtr( const VOID *lp, UINT_PTR ucb )
712  {
713  __try { memcmp( p, p, cb ); }
714  __except( EXCEPTION_EXECUTE_HANDLER ) { return( FALSE ); }
715  return( TRUE );
716  }
717 
718  inline BOOL IsBadWritePtr( LPVOID lp, UINT_PTR ucb )
719  {
720  __try { memset( p, 0, cb ); }
721  __except( EXCEPTION_EXECUTE_HANDLER ) { return( FALSE ); }
722  return( TRUE );
723  }
724 
725  In a number of cases the code is called as
726  isXXXPtr( ptr, sizeof( ptrObject ) ), which causes warnings about
727  constant expressions, to avoid this we define a separate version
728  that avoids the size check.
729 
730  Under Unix we could in theory check against _etext but this is too
731  unreliable to use, with shared libraries the single shared image can be
732  mapped pretty much anywhere into the process' address space and there can
733  be multiple _etext's present, one per shared library, it fails with
734  SELinux (which is something you'd expect to see used in combination with
735  code that's been carefully written to do things like perform pointer
736  checking), and who knows what it'll do in combination with different
737  approaches to ASLR. Because of its high level of nonportability (even on
738  the same system it can break depending on whether something like SELinux
739  is enabled or not) it's too dangerous to enable its use */
740 
741 #if defined( __WIN32__ ) || defined( __WINCE__ )
742  #define isReadPtr( ptr, size ) ( ( ptr ) != NULL && ( size ) > 0 && \
743  !IsBadReadPtr( ( ptr ), ( size ) ) )
744  #define isWritePtr( ptr, size ) ( ( ptr ) != NULL && ( size ) > 0 && \
745  !IsBadWritePtr( ( ptr ), ( size ) ) )
746  #define isReadPtrConst( ptr, size ) \
747  ( ( ptr ) != NULL && \
748  !IsBadReadPtr( ( ptr ), ( size ) ) )
749  #define isWritePtrConst( ptr, size ) \
750  ( ( ptr ) != NULL && \
751  !IsBadWritePtr( ( ptr ), ( size ) ) )
752 #elif defined( __UNIX__ ) && 0 /* See comment above */
753  extern int _etext;
754 
755  #define isReadPtr( ptr, size ) ( ( ptr ) != NULL && \
756  ( void * ) ( ptr ) > ( void * ) &_etext && \
757  ( size ) > 0 )
758  #define isWritePtr( ptr, size ) ( ( ptr ) != NULL && \
759  ( void * ) ( ptr ) > ( void * ) &_etext && \
760  ( size ) > 0 )
761  #define isReadPtrConst( ptr, size ) \
762  ( ( ptr ) != NULL && \
763  ( void * ) ( ptr ) > ( void * ) &_etext )
764  #define isWritePtrConst( ptr, size ) \
765  ( ( ptr ) != NULL && \
766  ( void * ) ( ptr ) > ( void * ) &_etext )
767 #else
768  #define isReadPtr( ptr, size ) ( ( ptr ) != NULL && ( size ) > 0 )
769  #define isWritePtr( ptr, size ) ( ( ptr ) != NULL && ( size ) > 0 )
770  #define isReadPtrConst( ptr, type ) \
771  ( ( ptr ) != NULL )
772  #define isWritePtrConst( ptr, type ) \
773  ( ( ptr ) != NULL )
774 #endif /* Pointer check macros */
775 
776 /* To avoid problems with signs, for example due to (signed) characters
777  being potentially converted to large signed integer values we perform a
778  safe conversion by going via an intermediate unsigned value, which in
779  the case of char -> int results in 0xFF turning into 0x000000FF rather
780  than 0xFFFFFFFF */
781 
782 #define byteToInt( x ) ( ( unsigned char ) ( x ) )
783 #define intToLong( x ) ( ( unsigned int ) ( x ) )
784 
785 #define sizeToInt( x ) ( ( unsigned int ) ( x ) )
786 #define intToByte( x ) ( ( unsigned char ) ( x ) )
787 
788 /* Clear/set object error information */
789 
790 #define clearErrorInfo( objectInfoPtr ) \
791  { \
792  ( objectInfoPtr )->errorLocus = CRYPT_ATTRIBUTE_NONE; \
793  ( objectInfoPtr )->errorType = CRYPT_OK; \
794  }
795 
796 #define setErrorInfo( objectInfoPtr, locus, type ) \
797  { \
798  ( objectInfoPtr )->errorLocus = locus; \
799  ( objectInfoPtr )->errorType = type; \
800  }
801 
802 /****************************************************************************
803 * *
804 * Internal API Functions *
805 * *
806 ****************************************************************************/
807 
808 /* Pull in the internal API function definitions and prototypes */
809 
810 #if defined( INC_ALL )
811  #include "int_api.h"
812 #else
813  #include "misc/int_api.h"
814 #endif /* Compiler-specific includes */
815 
816 /****************************************************************************
817 * *
818 * Debugging Functions *
819 * *
820 ****************************************************************************/
821 
822 /* Pull in the debugging function definitions and prototypes */
823 
824 #if defined( INC_ALL )
825  #include "debug.h"
826 #else
827  #include "misc/debug.h"
828 #endif /* Compiler-specific includes */
829 
830 #endif /* _CRYPT_DEFINED */