1 /****************************************************************************
2 *																			*
3 *					  cryptlib Internal General Header File 				*
4 *						Copyright Peter Gutmann 1992-2014					*
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 <limits.h>
209 #include <stdlib.h>
210 #include <string.h>
211 
212 /* If the global cryptlib header hasn't been included yet, include it now */
213 
214 #ifndef _CRYPTLIB_DEFINED
215   #include "cryptlib.h"
216 #endif /* _CRYPTLIB_DEFINED */
217 
218 /* Since some of the _LAST types are used in the code, we have to undefine
219    them again if they've been used in the enum-fix kludge */
220 
221 #ifdef NEED_ENUMFIX
222   #undef CRYPT_ALGO_LAST
223   #undef CRYPT_MODE_LAST
224   #undef CRYPT_KEYSET_LAST
225   #undef CRYPT_DEVICE_LAST
226   #undef CRYPT_CERTTYPE_LAST
227   #undef CRYPT_FORMAT_LAST
228   #undef CRYPT_SESSION_LAST
229   #undef CRYPT_USER_LAST
230   #undef CRYPT_IATTRIBUTE_LAST
231   #undef CRYPT_CRLEXTREASON_LAST
232   #undef CRYPT_CONTENT_LAST
233   #undef CRYPT_SIGNATURELEVEL_LAST
234   #undef CRYPT_CERTFORMAT_LAST
235   #undef CRYPT_REQUESTTYPE_LAST
236   #undef CRYPT_KEYID_LAST
237   #undef CRYPT_OBJECT_LAST
238   #undef CRYPT_ERRTYPE_LAST
239   #undef CRYPT_CERTACTION_LAST
240   #undef CRYPT_KEYOPT_LAST
241 #endif /* NEED_ENUMFIX */
242 
243 /****************************************************************************
244 *																			*
245 *						System- and Compiler-Specific Defines				*
246 *																			*
247 ****************************************************************************/
248 
249 /* Pull in the system and compiler-specific defines and values */
250 
251 #if defined( INC_ALL )
252   #include "os_spec.h"
253 #else
254   #include "misc/os_spec.h"
255 #endif /* Compiler-specific includes */
256 
257 /* Pull in the source code analysis header */
258 
259 #if defined( INC_ALL )
260   #include "analyse.h"
261 #else
262   #include "misc/analyse.h"
263 #endif /* Compiler-specific includes */
264 
265 /****************************************************************************
266 *																			*
267 *								Config Options								*
268 *																			*
269 ****************************************************************************/
270 
271 /* Pull in the cryptlib initialisation options file, which contains the
272    various USE_xxx defines that enable different cryptlib features.  Note
273    that this *must* be included after os_spec.h, which performs OS detection
274    used by config.h to enable/disable various code features */
275 
276 #if defined( INC_ALL )
277   #include "config.h"
278 #else
279   #include "misc/config.h"
280 #endif /* Compiler-specific includes */
281 
282 /****************************************************************************
283 *																			*
284 *						Data Size and Crypto-related Constants				*
285 *																			*
286 ****************************************************************************/
287 
288 /* Pull in the data-size and crypt-related constants */
289 
290 #if defined( INC_ALL )
291   #include "consts.h"
292 #else
293   #include "misc/consts.h"
294 #endif /* Compiler-specific includes */
295 
296 /****************************************************************************
297 *																			*
298 *								Kernel Interface							*
299 *																			*
300 ****************************************************************************/
301 
302 /* Pull in the cryptlib kernel interface defines */
303 
304 #include "cryptkrn.h"
305 
306 /****************************************************************************
307 *																			*
308 *								Portability Defines							*
309 *																			*
310 ****************************************************************************/
311 
312 /* Read/write values as 16- and 32-bit big-endian data in cases where we're
313    not dealing with a stream.  Usage:
314 
315 	mget/putWord():
316 		SSHv1 (disabled by default).
317 		SOCKS wrapper in network code (disabled by default).
318 
319 	mget/putLong():
320 		SSHv1 (disabled by default).
321 		Sampling data from the crypto RNG to detect stuck-at faults.
322 		Debug version of clAlloc() */
323 
324 #if defined( USE_SSH1 )
325 
326 #define mgetWord( memPtr ) \
327 		( ( ( unsigned int ) memPtr[ 0 ] << 8 ) | \
328 			( unsigned int ) memPtr[ 1 ] ); \
329 		memPtr += 2
330 
331 #define mputWord( memPtr, data ) \
332 		memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
333 		memPtr[ 1 ] = ( BYTE ) ( ( data ) & 0xFF ); \
334 		memPtr += 2
335 #endif /* USE_SSH1 */
336 
337 #define mgetLong( memPtr ) \
338 		( ( ( unsigned long ) memPtr[ 0 ] << 24 ) | \
339 		  ( ( unsigned long ) memPtr[ 1 ] << 16 ) | \
340 		  ( ( unsigned long ) memPtr[ 2 ] << 8 ) | \
341 		    ( unsigned long ) memPtr[ 3 ] ); \
342 		memPtr += 4
343 
344 #define mputLong( memPtr, data ) \
345 		memPtr[ 0 ] = ( BYTE ) ( ( ( data ) >> 24 ) & 0xFF ); \
346 		memPtr[ 1 ] = ( BYTE ) ( ( ( data ) >> 16 ) & 0xFF ); \
347 		memPtr[ 2 ] = ( BYTE ) ( ( ( data ) >> 8 ) & 0xFF ); \
348 		memPtr[ 3 ] = ( BYTE ) ( ( data ) & 0xFF ); \
349 		memPtr += 4
350 
351 /****************************************************************************
352 *																			*
353 *								Data Structures								*
354 *																			*
355 ****************************************************************************/
356 
357 /* Information on exported key/signature data.  This is an extended version
358    of the data returned by the externally-visible cryptQueryObject() routine */
359 
360 typedef struct {
361 	/* Object format and status information */
362 	CRYPT_FORMAT_TYPE formatType;	/* Object format type */
363 	CRYPT_OBJECT_TYPE type;			/* Object type */
364 	long size;						/* Object size */
365 	VALUE( 0, 10 ) \
366 	int version;					/* Object format version */
367 
368 	/* The encryption algorithm and mode */
369 	CRYPT_ALGO_TYPE cryptAlgo;		/* The encryption algorithm */
370 	CRYPT_MODE_TYPE cryptMode;		/* The encryption mode */
371 	int cryptAlgoParam;				/* Optional algorithm parameter */
372 
373 	/* The key ID for public key objects */
374 	BUFFER( CRYPT_MAX_HASHSIZE, keyIDlength ) \
375 	BYTE keyID[ CRYPT_MAX_HASHSIZE + 8 ];/* PKC key ID */
376 	VALUE( 0, CRYPT_MAX_HASHSIZE ) \
377 	int keyIDlength;
378 
379 	/* The IV for conventionally encrypted data */
380 	BUFFER( CRYPT_MAX_IVSIZE, ivLength ) \
381 	BYTE iv[ CRYPT_MAX_IVSIZE + 8 ];/* IV */
382 	VALUE( 0, CRYPT_MAX_IVSIZE ) \
383 	int ivLength;
384 
385 	/* The key derivation algorithm and iteration count for conventionally
386 	   encrypted keys */
387 	CRYPT_ALGO_TYPE keySetupAlgo;	/* Key setup algorithm */
388 	int keySetupAlgoParam;			/* Optional parameter for key setup algo */
389 	int keySetupIterations;			/* Key setup iteration count */
390 	int keySize;					/* Key size (if not implicit) */
391 	BUFFER( CRYPT_MAX_HASHSIZE, saltLength ) \
392 	BYTE salt[ CRYPT_MAX_HASHSIZE + 8 ];/* Key setup salt */
393 	VALUE( 0, CRYPT_MAX_HASHSIZE ) \
394 	int saltLength;
395 
396 	/* The hash algorithm for signatures */
397 	CRYPT_ALGO_TYPE hashAlgo;		/* Hash algorithm */
398 	int hashAlgoParam;				/* Optional algorithm parameter */
399 
400 	/* The encoded parameter data for authenticated encryption, and the
401 	   optional KDF and encryption and MAC algorithm parameter data within
402 	   that */
403 	BUFFER( 128, authEncParamLength ) \
404 	BYTE authEncParamData[ 128 + 8 ];
405 	VALUE( 0, 128 ) \
406 	int authEncParamLength;			/* AuthEnc parameter data */
407 	int kdfParamStart, kdfParamLength;	/* Position of opt.KDF params */
408 	int encParamStart, encParamLength;	/* Position of enc.parameters */
409 	int macParamStart, macParamLength;	/* Position of MAC parameters */
410 
411 	/* The start and length of the payload data, either the encrypted key or
412 	   the signature data */
413 	int dataStart, dataLength;
414 
415 	/* The start and length of the issuerAndSerialNumber, authenticated
416 	   attributes, and unauthenticated attributes for CMS objects */
417 	int iAndSStart, iAndSLength;
418 	int attributeStart, attributeLength;
419 	int unauthAttributeStart, unauthAttributeLength;
420 	} QUERY_INFO;
421 
422 /* DLP algorithms require composite parameters when en/decrypting and
423    signing/sig checking, so we can't just pass in a single buffer full of
424    data as we can with RSA.  In addition the data length changes, for
425    example for a DSA sig we pass in a 20-byte hash and get back a ~50-byte
426    sig, for sig.checking we pass in a 20-byte hash and ~50-byte sig and get
427    back nothing.  Because of this we have to use the following structure to
428    pass data to the DLP-based PKCs */
429 
430 typedef struct {
431 	BUFFER_FIXED( inLen1 ) \
432 	const BYTE *inParam1;
433 	BUFFER_OPT_FIXED( inLen2 ) \
434 	const BYTE *inParam2;				/* Input parameters */
435 	BUFFER_FIXED( outLen ) \
436 	BYTE *outParam;						/* Output parameter */
437 	int inLen1, inLen2, outLen;			/* Parameter lengths */
438 	CRYPT_FORMAT_TYPE formatType;		/* Paramter format type */
439 	} DLP_PARAMS;
440 
441 #define setDLPParams( dlpDataPtr, dataIn, dataInLen, dataOut, dataOutLen ) \
442 	{ \
443 	memset( ( dlpDataPtr ), 0, sizeof( DLP_PARAMS ) ); \
444 	( dlpDataPtr )->formatType = CRYPT_FORMAT_CRYPTLIB; \
445 	( dlpDataPtr )->inParam1 = ( dataIn ); \
446 	( dlpDataPtr )->inLen1 = ( dataInLen ); \
447 	( dlpDataPtr )->outParam = ( dataOut ); \
448 	( dlpDataPtr )->outLen = ( dataOutLen ); \
449 	}
450 
451 /* When calling key agreement functions we have to pass a mass of cruft
452    around instead of the usual flat data (even more than the generic DLP
453    parameter information) for which we use the following structure.  The
454    public value is the public key value used for the agreement process,
455    typically y = g^x mod p for DH-like mechanisms.  The ukm is the user
456    keying material, typically something which is mixed into the DH process
457    to make the new key unique.  The wrapped key is the output (originator)/
458    input(recipient) to the keyagreement process.  The session key context
459    contains a context into which the derived key is loaded.  Typical
460    examples of use are:
461 
462 	PKCS #3: publicValue = y
463 	S/MIME: publicValue = y, ukm = 512-bit nonce, wrappedKey = g^x mod p
464 	SSH, SSL: publicValue = y, wrappedKey = x */
465 
466 typedef struct {
467 	BUFFER( CRYPT_MAX_PKCSIZE, publicValueLen ) \
468 	BYTE publicValue[ CRYPT_MAX_PKCSIZE + 8 ];
469 	VALUE( 0, CRYPT_MAX_PKCSIZE ) \
470 	int publicValueLen;				/* Public key value */
471 	BUFFER( CRYPT_MAX_PKCSIZE, wrappedKeyLen ) \
472 	BYTE wrappedKey[ CRYPT_MAX_PKCSIZE + 8 ];
473 	VALUE( 0, CRYPT_MAX_PKCSIZE ) \
474 	int wrappedKeyLen;				/* Wrapped key */
475 	} KEYAGREE_PARAMS;
476 
477 /****************************************************************************
478 *																			*
479 *								Useful General Macros						*
480 *																			*
481 ****************************************************************************/
482 
483 /* Reasonably reliable way to get rid of unused argument warnings in a
484    compiler-independant manner */
485 
486 #define UNUSED_ARG( arg )	( ( arg ) = ( arg ) )
487 
488 /* Although min() and max() aren't in the ANSI standard, most compilers have
489    them in one form or another, but just enough don't that we need to define
490    them ourselves in some cases */
491 
492 #if !defined( min )
493   #ifdef MIN
494 	#define min			MIN
495 	#define max			MAX
496   #else
497 	#define min( a, b )	( ( ( a ) < ( b ) ) ? ( a ) : ( b ) )
498 	#define max( a, b )	( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
499   #endif /* Various min/max macros */
500 #endif /* !min/max */
501 
502 /* Macros to convert to and from the bit counts used for some encryption
503    parameters */
504 
505 #define bitsToBytes( bits )			( ( ( bits ) + 7 ) >> 3 )
506 #define bytesToBits( bytes )		( ( bytes ) << 3 )
507 
508 /* When initialising a static block of bytes, it's useful to be able to
509    specify it as a character string, however this runs into problems with
510    the fact that the default char type is signed.  To get around this the
511    following macro declares a byte string as a set of unsigned bytes */
512 
513 #define MKDATA( x )					( ( BYTE * ) ( x ) )
514 
515 /* Macro to round a value up to the nearest multiple of a second value,
516    with the second value being a power of 2 */
517 
518 #define roundUp( size, roundSize ) \
519 	( ( ( size ) + ( ( roundSize ) - 1 ) ) & ~( ( roundSize ) - 1 ) )
520 
521 /* A macro to clear sensitive data from memory.  This is somewhat easier to
522    use than calling memset with the second parameter set to 0 all the time,
523    and makes it obvious where sensitive data is being erased.  In addition
524    some systems, recognising the problem of compilers removing what they see
525    as deas stores, have distinct memory zeroisation support, so if available
526    we use that */
527 
528 #if defined( _MSC_VER ) && VC_GE_2005( _MSC_VER )
529   /* This is just a mapping to RtlSecureZeroMemory() (via WinBase.h) which
530      is implemented as inline code implementing a loop on a pointer declared
531 	 volatile, but unlike the corresponding RtlZeroMemory() there's a
532 	 contract that this will always zeroise memory even in the face of
533 	 compiler changes that would otherwise optimise away the access */
534   #define zeroise( memory, size )	SecureZeroMemory( memory, size )
535 #elif defined( __STDC_LIB_EXT1__ )
536   /* C11 defines a function memset_s() that guarantees that it won't be
537 	 optimised away, although this is quite well obfuscated in the spec,
538 	 "the memory indicated by [the memset parameters] may be accessible in
539 	 the future and therefore must contain the values indicated by [the
540 	 value to set]", hopefully the implementers will know that this equates
541 	 to "the memset_s() call can't be optimised away" */
542   #define zeroise( memory, size )	memset_s( memory, size, 0, size )
543 #elif defined( __OpenBSD__ )
544   /* The OpenBSD folks defined their own won't-be-optimised-away bzero()
545 	 function */
546   #define zeroise( memory, size )	explicit_bzero( memory, size )
547 #else
548   #define zeroise( memory, size )	memset( memory, 0, size )
549 #endif /* Systems with distinct zeroise functions */
550 
551 /* A macro to check that a value is a possibly valid handle.  This doesn't
552    check that the handle refers to a valid object, merely that the value is
553    in the range for valid handles.  The full function isValidHandle() used
554    in the kernel does check that the handle refers to a valid object, being
555    more than just a range check */
556 
557 #define isHandleRangeValid( handle ) \
558 		( ( handle ) > NO_SYSTEM_OBJECTS - 1 && ( handle ) < MAX_OBJECTS )
559 
560 /* A macro to check whether an encryption mode needs an IV or not */
561 
562 #define needsIV( mode )	( ( mode ) == CRYPT_MODE_CBC || \
563 						  ( mode ) == CRYPT_MODE_CFB || \
564 						  ( mode ) == CRYPT_MODE_GCM )
565 
566 /* A macro to check whether an algorithm is a pure stream cipher (that is,
567    a real stream cipher rather than just a block cipher run in a stream
568    mode) */
569 
570 #define isStreamCipher( algorithm )		( ( algorithm ) == CRYPT_ALGO_RC4 )
571 
572 /* A macro to check whether an algorithm is regarded as being (relatively)
573    insecure or not.  This is used by some of the higher-level internal
574    routines that normally use the default algorithm set in the configuration
575    database if nothing else is explicitly specified, but that specifically
576    check for the weaker algorithms and use something stronger instead if a
577    weak algorithm is specified.  This is done both for luser-proofing and to
578    avoid possible problems from a trojan patching the configuration
579    database */
580 
581 #define isWeakCryptAlgo( algorithm )	( ( algorithm ) == CRYPT_ALGO_DES || \
582 										  ( algorithm ) == CRYPT_ALGO_RC2 || \
583 										  ( algorithm ) == CRYPT_ALGO_RC4 )
584 #define isWeakHashAlgo( algorithm )		( ( algorithm ) == CRYPT_ALGO_MD5 )
585 #define isWeakMacAlgo( algorithm )		( 0 )
586 										/* None left with HMAC-MD5 deprecated */
587 
588 /* Macros to check for membership in overall algorithm classes */
589 
590 #define isConvAlgo( algorithm ) \
591 		( ( algorithm ) >= CRYPT_ALGO_FIRST_CONVENTIONAL && \
592 		  ( algorithm ) <= CRYPT_ALGO_LAST_CONVENTIONAL )
593 #define isPkcAlgo( algorithm ) \
594 		( ( algorithm ) >= CRYPT_ALGO_FIRST_PKC && \
595 		  ( algorithm ) <= CRYPT_ALGO_LAST_PKC )
596 #define isHashAlgo( algorithm ) \
597 		( ( algorithm ) >= CRYPT_ALGO_FIRST_HASH && \
598 		  ( algorithm ) <= CRYPT_ALGO_LAST_HASH )
599 #define isHashMacExtAlgo( algorithm ) \
600 		( ( algorithm ) == CRYPT_ALGO_SHA2 || \
601 		  ( algorithm ) == CRYPT_ALGO_SHAng || \
602 		  ( algorithm ) == CRYPT_ALGO_HMAC_SHA2 || \
603 		  ( algorithm ) == CRYPT_ALGO_HMAC_SHAng )
604 #define isMacAlgo( algorithm ) \
605 		( ( algorithm ) >= CRYPT_ALGO_FIRST_MAC && \
606 		  ( algorithm ) <= CRYPT_ALGO_LAST_MAC )
607 #define isSpecialAlgo( algorithm ) \
608 		( ( algorithm ) == CRYPT_IALGO_GENERIC_SECRET )
609 
610 /* Macros to check whether a PKC algorithm is useful for a certain purpose
611    or requires special-case handling.  Note that isDlpAlgo() doesn't include
612    the ECC algorithms, which are also based on the DLP (although in this
613    case the ECDLP and not the standard DLP).  This is a bit ugly but it's
614    used in various places to distinguish DLP-based PKCs from non-DLP-based
615    PKCs, while ECDLP-based-PKCs are in a separate class.  This means that
616    when checking for the extended class { DLP | ECDLP } it's necessary to
617    explicitly include isEccAlgo() alongside isDlpAlgo() */
618 
619 #define isSigAlgo( algorithm ) \
620 	( ( algorithm ) == CRYPT_ALGO_RSA || ( algorithm ) == CRYPT_ALGO_DSA || \
621 	  ( algorithm ) == CRYPT_ALGO_ECDSA )
622 #define isCryptAlgo( algorithm ) \
623 	( ( algorithm ) == CRYPT_ALGO_RSA || ( algorithm ) == CRYPT_ALGO_ELGAMAL )
624 #define isKeyxAlgo( algorithm ) \
625 	( ( algorithm ) == CRYPT_ALGO_DH || ( algorithm ) == CRYPT_ALGO_ECDH )
626 #define isDlpAlgo( algorithm ) \
627 	( ( algorithm ) == CRYPT_ALGO_DSA || ( algorithm ) == CRYPT_ALGO_ELGAMAL || \
628 	  ( algorithm ) == CRYPT_ALGO_DH )
629 #define isEccAlgo( algorithm ) \
630 	( ( algorithm ) == CRYPT_ALGO_ECDSA || ( algorithm ) == CRYPT_ALGO_ECDH )
631 
632 /* Macros to check whether an algorithm has additional parameters that need
633    to be handled explicitly */
634 
635 #define isParameterisedConvAlgo( algorithm ) \
636 	( ( algorithm ) == CRYPT_ALGO_AES )
637 #define isParameterisedHashAlgo( algorithm ) \
638 	( ( algorithm ) == CRYPT_ALGO_SHA2 || ( algorithm ) == CRYPT_ALGO_SHAng )
639 #define isParameterisedMacAlgo( algorithm ) \
640 	( ( algorithm ) == CRYPT_ALGO_HMAC_SHA2 || \
641 	  ( algorithm ) == CRYPT_ALGO_HMAC_SHAng )
642 
643 /* A macro to check whether an error status is related to a data-formatting
644    problem or some other problem.  This is used to provide extended string-
645    format error information, if it's a data error then the message being
646    processed was (probably) invalid, if it's not a data error then it may be
647    due to an invalid decryption key being used or something similar that's
648    unrelated to the message itself.
649 
650    The exact definition of what constitutes a "data error" is a bit vague
651    but since it's only used to control what additional error information is
652    returned a certain level of fuzziness is permitted */
653 
654 #define isDataError( status ) \
655 		( ( status ) == CRYPT_ERROR_OVERFLOW || \
656 		  ( status ) == CRYPT_ERROR_UNDERFLOW || \
657 		  ( status ) == CRYPT_ERROR_BADDATA || \
658 		  ( status ) == CRYPT_ERROR_SIGNATURE || \
659 		  ( status ) == CRYPT_ERROR_NOTAVAIL || \
660 		  ( status ) == CRYPT_ERROR_INCOMPLETE || \
661 		  ( status ) == CRYPT_ERROR_COMPLETE || \
662 		  ( status ) == CRYPT_ERROR_INVALID )
663 
664 /* A macro to check whether a public key is too short to be secure.  This
665    is a bit more complex than just a range check because any length below
666    about 512 bits is probably a bad data error, while lengths from about
667    512 bits to MIN_PKCSIZE (for standard PKCs) or 120 bits to
668    MIN_PKCSIZE_ECC are too-short key errors */
669 
670 #define isShortPKCKey( keySize ) \
671 		( ( keySize ) >= MIN_PKCSIZE_THRESHOLD && \
672 		  ( keySize ) < MIN_PKCSIZE )
673 #define isShortECCKey( keySize ) \
674 		( ( keySize ) >= MIN_PKCSIZE_ECC_THRESHOLD && \
675 		  ( keySize ) < MIN_PKCSIZE_ECC )
676 
677 /* Perform a range check on a block of memory, checking that
678    { start, length } falls within { 0, totalLength }.  There are two
679    versions of this, the default which requires a nonzero start offset and
680    the special-case variant which allows a zero start offset, which is used
681    for situations like optionally MIME-wrapped data which have a nonzero
682    offset if there's a MIME header to be skipped but a zero offset if it's
683    unencapsulated data */
684 
685 #define rangeCheck( start, length, totalLength ) \
686 		( ( start ) <= 0 || ( length ) < 1 || \
687 		  ( start ) + ( length ) > ( totalLength ) ) ? FALSE : TRUE
688 #define rangeCheckZ( start, length, totalLength ) \
689 		( ( start ) < 0 || ( length ) < 1 || \
690 		  ( start ) + ( length ) > ( totalLength ) ) ? FALSE : TRUE
691 
692 /* Check the validity of a pointer passed to a cryptlib function.  Usually
693    the best that we can do is check that it's not null, but some OSes allow
694    for better checking than this, for example that it points to a block of
695    readable or writeable memory.  Under Windows IsBadReadPtr() will always
696    succeed if the size is 0, so we have to add a separate check to make sure
697    that it's non-NULL.
698 
699    There are additional caveats with the use of the Windows memory-checking
700    functions.  In theory these would be implemented via VirtualQuery(),
701    however this is quite slow, requiring a kernel transition and poking
702    around with the page protection mechanisms.  Instead, they try and read
703    or write the memory, with an exception handler wrapped around the access.
704    If the exception is thrown, they fail.  The problem with this way of
705    doing things is that if the memory address is a stack guard page used to
706    grow the stack (when the system-level exception handler sees an access to
707    the bottom-of-stack guard page, it knows that it has to grow the stack)
708    *and* the guard page is owned by another thread, IsBadXxxPtr() will catch
709    the exception and the system will never see it, so it can't grow the
710    stack past the current limit (note that this only occurs if the guard
711    page that we hit is owned by a different thread; if we own in then the
712    kernel will catch the STATUS_GUARD_PAGE_VIOLATION exception and grow the
713    stack as required).  In addition if it's the last guard page then instead
714    of getting an "out of stack" exception, it's turned into a no-op.  The
715    second time the last guard page is hit, the application is terminated by
716    the system, since it's passed its first-chance exception.
717 
718    A variation of this is that the calling app could be deliberately passing
719    a pointer to a guard page and catching the guard page exception in order
720    to dynamically generate the data that would fill the page (this can
721    happen for example when simulating a large address space with pointer
722    swizzling), but this is a pretty weird programming technique that's
723    unlikely to be used with a crypto library.
724 
725    A lesser problem is that there's a race condition in the checking, since
726    the memory can be unmapped between the IsBadXxxPtr() check and the actual
727    access, but you'd pretty much have to be trying to actively subvert the
728    checks to do something like this.
729 
730    For these reasons we use these functions mostly for debugging, wrapping
731    them up in assert()s in most cases where they're used.  Under Windows
732    Vista they've actually been turned into no-ops because of the above
733    problems, although it's probable that they'll be replaced by code to
734    check for NULL pointers, since Microsoft's docs indicate that this much
735    checking will still be done.  If necessary we could also replace the
736    no-op'd out versions with the equivalent code:
737 
738 	inline BOOL IsBadReadPtr( const VOID *lp, UINT_PTR ucb )
739 		{
740 		__try { memcmp( p, p, cb ); }
741 		__except( EXCEPTION_EXECUTE_HANDLER ) { return( FALSE ); }
742 		return( TRUE );
743 		}
744 
745 	inline BOOL IsBadWritePtr( LPVOID lp, UINT_PTR ucb )
746 		{
747 		__try { memset( p, 0, cb ); }
748 		__except( EXCEPTION_EXECUTE_HANDLER ) { return( FALSE ); }
749 		return( TRUE );
750 		}
751 
752    In a number of cases the code is called as
753    isXXXPtr( ptr, sizeof( ptrObject ) ), which causes warnings about
754    constant expressions, to avoid this we define a separate version
755    that avoids the size check.
756 
757    Under Unix we could in theory check against _etext but this is too
758    unreliable to use, with shared libraries the single shared image can be
759    mapped pretty much anywhere into the process' address space and there can
760    be multiple _etext's present, one per shared library, it fails with
761    SELinux (which is something you'd expect to see used in combination with
762    code that's been carefully written to do things like perform pointer
763    checking), and who knows what it'll do in combination with different
764    approaches to ASLR.  Because of its high level of nonportability (even on
765    the same system it can break depending on whether something like SELinux
766    is enabled or not) it's too dangerous to enable its use */
767 
768 #if defined( __WIN32__ ) || defined( __WINCE__ )
769   /* The use of code analysis complicates the pointer-checking macros
770 	 because they read memory that's uninitialised at that point.  This is
771 	 fine because we're only checking for readability/writeability, but the
772 	 analyser doesn't know this and flags it as an error.  To avoid this,
773 	 we remove the read/write calls when running the analyser */
774   #ifdef _PREFAST_
775 	#define isReadPtr( ptr, size )	( ( ptr ) != NULL && ( size ) > 0 )
776 	#define isWritePtr( ptr, size )	( ( ptr ) != NULL && ( size ) > 0 )
777 	#define isReadPtrConst( ptr, size ) \
778 									( ( ptr ) != NULL )
779 	#define isWritePtrConst( ptr, size ) \
780 									( ( ptr ) != NULL )
781   #else
782 	#define isReadPtr( ptr, size )	( ( ptr ) != NULL && ( size ) > 0 && \
783 									  !IsBadReadPtr( ( ptr ), ( size ) ) )
784 	#define isWritePtr( ptr, size )	( ( ptr ) != NULL && ( size ) > 0 && \
785 									  !IsBadWritePtr( ( ptr ), ( size ) ) )
786 	#define isReadPtrConst( ptr, size ) \
787 									( ( ptr ) != NULL && \
788 									  !IsBadReadPtr( ( ptr ), ( size ) ) )
789 	#define isWritePtrConst( ptr, size ) \
790 									( ( ptr ) != NULL && \
791 									  !IsBadWritePtr( ( ptr ), ( size ) ) )
792   #endif /* _PREFAST_ */
793 #elif defined( __UNIX__ ) && 0		/* See comment above */
794   extern int _etext;
795 
796   #define isReadPtr( ptr, size )	( ( ptr ) != NULL && \
797 									  ( void * ) ( ptr ) > ( void * ) &_etext && \
798 									  ( size ) > 0 )
799   #define isWritePtr( ptr, size )	( ( ptr ) != NULL && \
800 									  ( void * ) ( ptr ) > ( void * ) &_etext && \
801 									  ( size ) > 0 )
802   #define isReadPtrConst( ptr, size ) \
803 									( ( ptr ) != NULL && \
804 									  ( void * ) ( ptr ) > ( void * ) &_etext )
805   #define isWritePtrConst( ptr, size ) \
806 									( ( ptr ) != NULL && \
807 									  ( void * ) ( ptr ) > ( void * ) &_etext )
808 #else
809   #define isReadPtr( ptr, size )	( ( ptr ) != NULL && ( size ) > 0 )
810   #define isWritePtr( ptr, size )	( ( ptr ) != NULL && ( size ) > 0 )
811   #define isReadPtrConst( ptr, type ) \
812 									( ( ptr ) != NULL )
813   #define isWritePtrConst( ptr, type ) \
814 									( ( ptr ) != NULL )
815 #endif /* Pointer check macros */
816 
817 /* To avoid problems with signs, for example due to (signed) characters
818    being potentially converted to large signed integer values we perform a
819    safe conversion by going via an intermediate unsigned value, which in
820    the case of char -> int results in 0xFF turning into 0x000000FF rather
821    than 0xFFFFFFFF.
822 
823    For Visual Studio we explicitly mask some values to avoid runtime traps
824    in debug builds */
825 
826 #define byteToInt( x )				( ( unsigned char ) ( x ) )
827 #define intToLong( x )				( ( unsigned int ) ( x ) )
828 
829 #define sizeToInt( x )				( ( unsigned int ) ( x ) )
830 #if defined( _MSC_VER ) && VC_GE_2010( _MSC_VER )
831   #define intToByte( x )			( ( unsigned char ) ( ( x ) & 0xFF ) )
832 #else
833   #define intToByte( x )			( ( unsigned char ) ( x ) )
834 #endif /* VS 2010 or newer */
835 
836 /* Clear/set object error information */
837 
838 #define clearErrorInfo( objectInfoPtr ) \
839 	{ \
840 	( objectInfoPtr )->errorLocus = CRYPT_ATTRIBUTE_NONE; \
841 	( objectInfoPtr )->errorType = CRYPT_OK; \
842 	}
843 
844 #define setErrorInfo( objectInfoPtr, locus, type ) \
845 	{ \
846 	( objectInfoPtr )->errorLocus = locus; \
847 	( objectInfoPtr )->errorType = type; \
848 	}
849 
850 /****************************************************************************
851 *																			*
852 *								Internal API Functions						*
853 *																			*
854 ****************************************************************************/
855 
856 /* Pull in the internal API function definitions and prototypes */
857 
858 #if defined( INC_ALL )
859   #include "int_api.h"
860 #else
861   #include "misc/int_api.h"
862 #endif /* Compiler-specific includes */
863 
864 /****************************************************************************
865 *																			*
866 *								Debugging Functions							*
867 *																			*
868 ****************************************************************************/
869 
870 /* Pull in the debugging function definitions and prototypes */
871 
872 #if defined( INC_ALL )
873   #include "debug.h"
874   #include "fault.h"
875 #else
876   #include "misc/debug.h"
877   #include "misc/fault.h"
878 #endif /* Compiler-specific includes */
879 
880 #endif /* _CRYPT_DEFINED */
881