1 /****************************************************************************
2 *																			*
3 *					  cryptlib Kernel Interface Header File 				*
4 *						Copyright Peter Gutmann 1992-2015					*
5 *																			*
6 ****************************************************************************/
7 
8 #ifndef _CRYPTKRN_DEFINED
9 
10 #define _CRYPTKRN_DEFINED
11 
12 /* Macros to handle code correctness checking of critical sections of the
13    code such as the kernel and CSPRNG (sed quis custodiet ipsos custodes?),
14    extending the design-by-contract macros in misc/int_api.h */
15 
16 /* Value of a variable at the start of block scope, used for postcondition
17    predicates.  The pointer is declared as BYTE * rather than the more
18    general void * in order to allow range comparisons, and a BYTE * rather
19    than char * because of compilers that complain about comparisons between
20    signed and unsigned pointer types.  Note that these declarations must be
21    the last in any set of variable declarations since some of the higher-
22    overhead checks are only applied in the debug build and the release build
23    expands them to nothing, leaving only the terminating semicolon on the
24    line, which must follow all other declarations */
25 
26 #define ORIGINAL_VALUE( x )			orig_##x
27 #define ORIGINAL_INT( x )			const int orig_##x = ( int ) x
28 #define ORIGINAL_PTR( x )			const BYTE *orig_##x = ( const BYTE * ) x
29 
30 /* Sometimes we can't use the preprocessor tricks above because the value
31    being saved isn't a primitive type or the variable value isn't available
32    at the start of the block, in which case we have to use the somewhat less
33    transparent macros below.
34 
35    In a small number of cases the values declared by these macros are only
36    used in debug builds, leading to unused-variable warnings in release
37    builds.  This is infrequent enough that there's not much point in adding
38    even further special-casing for them */
39 
40 #define ORIGINAL_INT_VAR( x, y )	const int orig_##x = ( y )
41 #define DECLARE_ORIGINAL_INT( x )	int orig_##x
42 #define STORE_ORIGINAL_INT( x, y )	orig_##x = ( y )
43 
44 /* Some checks have a relatively high overhead (for example for_all and
45    there_exists on arrays) so we only perform them in the debug build */
46 
47 #if !defined( NDEBUG )
48 
49 /* Universal qualifiers: for_all, there_exists.  Because of the typical use
50    of 'i' as loop variables we'll get compiler warnings about duplicate
51    variable declarations, unfortunately we can't fix this with something
52    like '_local_##iter' because the loop test condition is a free-form
53    expression and there's no easy way to create a localised form of all
54    references to the loop variable inside the expression */
55 
56 #define FORALL( iter, start, end, condition ) \
57 		{ \
58 		int iter; \
59 		\
60 		for( iter = ( start ); iter < ( end ); iter++ ) \
61 			assert( condition ); \
62 		}
63 
64 #define EXISTS( iter, start, end, condition ) \
65 		{ \
66 		int iter; \
67 		\
68 		for( iter = ( start ); iter < ( end ); iter++ ) \
69 			{ \
70 			if( condition ) \
71 				break; \
72 			} \
73 		assert( iter < ( end ) ); \
74 		}
75 #else
76 
77 /* Non-debug version, no-op out the various checks */
78 
79 #define TEMP_INT( a )
80 #define TEMP_VAR( a )
81 #define FORALL( a, b, c, d )
82 #define EXISTS( a, b, c, d )
83 
84 #endif /* NDEBUG */
85 
86 /****************************************************************************
87 *																			*
88 *							Object Message Types							*
89 *																			*
90 ****************************************************************************/
91 
92 /* The object types */
93 
94 typedef enum {
95 	OBJECT_TYPE_NONE,				/* No object type */
96 	OBJECT_TYPE_CONTEXT,			/* Context */
97 	OBJECT_TYPE_KEYSET,				/* Keyset */
98 	OBJECT_TYPE_ENVELOPE,			/* Envelope */
99 	OBJECT_TYPE_CERTIFICATE,		/* Certificate */
100 	OBJECT_TYPE_DEVICE,				/* Crypto device */
101 	OBJECT_TYPE_SESSION,			/* Secure session */
102 	OBJECT_TYPE_USER,				/* User object */
103 	OBJECT_TYPE_LAST				/* Last possible object type */
104 	} OBJECT_TYPE;
105 
106 /* Object subtypes.  The subtype names aren't needed by the kernel (it just
107    treats the values as an anonymous bitfield during an ACL check) but they
108    are used in the ACL definitions and by the code that calls
109    krnlCreateObject(), so they need to be defined here.
110 
111    Because there are so many object subtypes we have to split them across
112    two 32-bit bitfields in order to permit a simple bitwise AND check, if we
113    ordered them by the more obvious major and minor type (that is, object
114    type and subtype) this wouldn't be necessary but it would increase the
115    size of the compiled ACL table (from 2 * 32 bits to NO_OBJECT_TYPES *
116    32 bits) and would make automated consistency checking difficult since
117    it's no longer possible to spot a case where a subtype bit for object A
118    has inadvertently been set for object B.
119 
120    To resolve this, we divide the subtype bit field into two smaller bit
121    fields (classes) with the high two bits designating which class the
122    subtype is in (actually we use the bits one below the high bit since
123    this may be interpreted as a sign bit by some preprocessors even if it's
124    declared as a xxxxUL, so in the following discussion we're talking about
125    logical rather than physical high bits).  Class A is always 01xxx...,
126    class B is always 10xxx...  If we get an entry that has 11xxx... we know
127    that the ACL entry is inconsistent.  This isn't pretty, but it's the
128    least ugly way to do it that still allows the ACL table to be built
129    using the preprocessor.
130 
131    Note that the device and keyset values must be in the same class, since
132    they're interchangeable for many message types and this simplifies some
133    of the MKACL() macros that only need to initialise one class type.
134 
135    The different between SUBTYPE_KEYSET_FILE, SUBTYPE_KEYSET_FILE_PARTIAL,
136    and SUBTYPE_KEYSET_FILE_READONLY is that SUBTYPE_KEYSET_FILE stores a
137    full index of key ID types and allows storage of any data type,
138    SUBTYPE_KEYSET_FILE_PARTIAL only handles one or two key IDs and a
139    restricted set of data types so that only a single private key and
140    associated public key and certificate can be stored, and
141    SUBTYPE_KEYSET_FILE_READONLY is even more restricted and can't be
142    updated in any sensible manner.
143 
144    The difference between SUBTYPE_KEYSET_DBMS and SUBTYPE_KEYSET_DBMS_STORE
145    is similar, the former is a simple certificate-and-CRL store while the
146    latter stores assorted CA management data items and supports extended
147    operations */
148 
149 #define SUBTYPE_CLASS_MASK			0x70000000L
150 #define SUBTYPE_CLASS_A				0x10000000L
151 #define SUBTYPE_CLASS_B				0x20000000L
152 #define SUBTYPE_CLASS_C				0x40000000L
153 
154 #define MK_SUBTYPE_A( value )		( SUBTYPE_CLASS_A | ( 1L << ( value - 1 ) ) )
155 #define MK_SUBTYPE_B( value )		( SUBTYPE_CLASS_B | ( 1L << ( value - 1 ) ) )
156 #define MK_SUBTYPE_C( value )		( SUBTYPE_CLASS_C | ( 1L << ( value - 1 ) ) )
157 
158 #define SUBTYPE_NONE				0x00000000L
159 
160 #define SUBTYPE_CTX_CONV			MK_SUBTYPE_A( 1 )
161 #define SUBTYPE_CTX_PKC				MK_SUBTYPE_A( 2 )
162 #define SUBTYPE_CTX_HASH			MK_SUBTYPE_A( 3 )
163 #define SUBTYPE_CTX_MAC				MK_SUBTYPE_A( 4 )
164 #define SUBTYPE_CTX_GENERIC			MK_SUBTYPE_A( 5 )
165 
166 #define SUBTYPE_CERT_CERT			MK_SUBTYPE_A( 6 )
167 #define SUBTYPE_CERT_CERTREQ		MK_SUBTYPE_A( 7 )
168 #define SUBTYPE_CERT_REQ_CERT		MK_SUBTYPE_A( 8 )
169 #define SUBTYPE_CERT_REQ_REV		MK_SUBTYPE_A( 9 )
170 #define SUBTYPE_CERT_CERTCHAIN		MK_SUBTYPE_A( 10 )
171 #define SUBTYPE_CERT_ATTRCERT		MK_SUBTYPE_A( 11 )
172 #define SUBTYPE_CERT_CRL			MK_SUBTYPE_A( 12 )
173 #define SUBTYPE_CERT_CMSATTR		MK_SUBTYPE_A( 13 )
174 #define SUBTYPE_CERT_RTCS_REQ		MK_SUBTYPE_A( 14 )
175 #define SUBTYPE_CERT_RTCS_RESP		MK_SUBTYPE_A( 15 )
176 #define SUBTYPE_CERT_OCSP_REQ		MK_SUBTYPE_A( 16 )
177 #define SUBTYPE_CERT_OCSP_RESP		MK_SUBTYPE_A( 17 )
178 #define SUBTYPE_CERT_PKIUSER		MK_SUBTYPE_A( 18 )
179 
180 #define SUBTYPE_ENV_ENV				MK_SUBTYPE_B( 1 )
181 #define SUBTYPE_ENV_ENV_PGP			MK_SUBTYPE_B( 2 )
182 #define SUBTYPE_ENV_DEENV			MK_SUBTYPE_B( 3 )
183 
184 #define SUBTYPE_KEYSET_FILE			MK_SUBTYPE_B( 4 )
185 #define SUBTYPE_KEYSET_FILE_PARTIAL	MK_SUBTYPE_B( 5 )
186 #define SUBTYPE_KEYSET_FILE_READONLY MK_SUBTYPE_B( 6 )
187 #define SUBTYPE_KEYSET_DBMS			MK_SUBTYPE_B( 7 )
188 #define SUBTYPE_KEYSET_DBMS_STORE	MK_SUBTYPE_B( 8 )
189 #define SUBTYPE_KEYSET_HTTP			MK_SUBTYPE_B( 9 )
190 #define SUBTYPE_KEYSET_LDAP			MK_SUBTYPE_B( 10 )
191 
192 #define SUBTYPE_DEV_SYSTEM			MK_SUBTYPE_B( 11 )
193 #define SUBTYPE_DEV_PKCS11			MK_SUBTYPE_B( 12 )
194 #define SUBTYPE_DEV_CRYPTOAPI		MK_SUBTYPE_B( 13 )
195 #define SUBTYPE_DEV_HARDWARE		MK_SUBTYPE_B( 14 )
196 
197 #define SUBTYPE_SESSION_SSH			MK_SUBTYPE_C( 1 )
198 #define SUBTYPE_SESSION_SSH_SVR		MK_SUBTYPE_C( 2 )
199 #define SUBTYPE_SESSION_SSL			MK_SUBTYPE_C( 3 )
200 #define SUBTYPE_SESSION_SSL_SVR		MK_SUBTYPE_C( 4 )
201 #define SUBTYPE_SESSION_RTCS		MK_SUBTYPE_C( 5 )
202 #define SUBTYPE_SESSION_RTCS_SVR	MK_SUBTYPE_C( 6 )
203 #define SUBTYPE_SESSION_OCSP		MK_SUBTYPE_C( 7 )
204 #define SUBTYPE_SESSION_OCSP_SVR	MK_SUBTYPE_C( 8 )
205 #define SUBTYPE_SESSION_TSP			MK_SUBTYPE_C( 9 )
206 #define SUBTYPE_SESSION_TSP_SVR		MK_SUBTYPE_C( 10 )
207 #define SUBTYPE_SESSION_CMP			MK_SUBTYPE_C( 11 )
208 #define SUBTYPE_SESSION_CMP_SVR		MK_SUBTYPE_C( 12 )
209 #define SUBTYPE_SESSION_SCEP		MK_SUBTYPE_C( 13 )
210 #define SUBTYPE_SESSION_SCEP_SVR	MK_SUBTYPE_C( 14 )
211 #define SUBTYPE_SESSION_CERT_SVR	MK_SUBTYPE_C( 15 )
212 
213 #define SUBTYPE_USER_SO				MK_SUBTYPE_C( 16 )
214 #define SUBTYPE_USER_NORMAL			MK_SUBTYPE_C( 17 )
215 #define SUBTYPE_USER_CA				MK_SUBTYPE_C( 18 )
216 
217 #define SUBTYPE_LAST				SUBTYPE_USER_CA
218 
219 /* The data type used to store subtype values */
220 
221 #ifdef SYSTEM_16BIT
222   typedef long OBJECT_SUBTYPE;
223 #else
224   typedef int OBJECT_SUBTYPE;
225 #endif /* 16- vs.32-bit systems */
226 
227 /* Message flags.  Normally messages can only be sent to external objects,
228    however we can also explicitly send them to internal objects which means
229    that we use the internal rather than external access ACL.  This can only
230    be done from inside cryptlib, for example when an object sends a message
231    to a subordinate object */
232 
233 #define MESSAGE_FLAG_INTERNAL		0x100
234 #define MKINTERNAL( message )		( message | MESSAGE_FLAG_INTERNAL )
235 
236 /* A mask to extract the basic message type */
237 
238 #define MESSAGE_MASK				0xFF
239 
240 /* The message types that can be sent to an object via krnlSendMessage().
241    By default messages can only be sent to externally visible objects, there
242    are also internal versions that can be sent to all objects.  The object
243    messages have the following arguments:
244 
245 	Type								DataPtr			Value
246 	---------------------------			-------			-----
247 	MESSAGE_DESTROY						NULL			0
248 	MESSAGE_INC/DECREFCOUNT				NULL			0
249 	MESSAGE_GETDEPENDENT				&objectHandle	objectType
250 	MESSAGE_SETDEPENDENT				&objectHandle	incRefCount
251 	MESSAGE_CLONE						NULL			cloneContext
252 	MESSAGE_GET/SETATTRIBUTE			&value			attributeType
253 	MESSAGE_DELETEATTRIBUTE				NULL			attributeType
254 	MESSAGE_COMPARE						&value			compareType
255 	MESSAGE_CHECK						NULL			requestedUse
256 	MESSAGE_SELFTEST					NULL			0
257 
258 	MESSAGE_CHANGENOTIFY				&value			attributeType
259 
260 	MESSAGE_CTX_ENCRYPT/DECRYPT/SIGN/-
261 		SIGCHECK/HASH					&value			valueLength
262 	MESSAGE_CTX_GENKEY					NULL			0
263 	MESSAGE_CTX_GENIV					NULL			0
264 
265 	MESSAGE_CRT_SIGN,					NULL			sigKey
266 	MESSAGE_CRT_SIGCHECK,				NULL			verifyObject
267 	MESSAGE_CRT_EXPORT,					&value			formatType
268 
269 	MESSAGE_DEV_QUERYCAPABILITY			&queryInfo		algorithm
270 	MESSAGE_DEV_EXPORT/IMPORT/SIGN/-
271 		SIGCHECK/DERIVE/KDF				&mechanismInfo	mechanismType
272 	MESSAGE_DEV_CREATEOBJECT			&createInfo		objectType
273 	MESSAGE_DEV_CREATEOBJECT_INDIRECT	&createInfo		objectType
274 
275 	MESSAGE_ENV_PUSH/POPDATA			&value			0
276 
277 	MESSAGE_KEY_GET/SET/DELETEKEY		&keymgmtInfo	itemType
278 	MESSAGE_KEY_GETFIRST/NEXTCERT		&keymgmtInfo	itemType
279 	MESSAGE_KEY_CERTMGMT				&certMgmtInfo	action
280 
281 	MESSAGE_USER_USERMGMT				&value			action
282 	MESSAGE_USER_TRUSTMGMT				&value			action */
283 
284 typedef enum {
285 	MESSAGE_NONE,				/* No message type */
286 
287 	/* Control messages to externally visible objects (the internal versions
288 	   are defined further down).  These messages are handled directly by
289 	   the kernel and don't affect the object itself except for
290 	   MESSAGE_DESTROY which is generated by the kernel in response to the
291 	   final MESSAGE_DECREFCOUNT sent to an object.  These are forwarded out
292 	   to the object to get it to clean up its state before the kernel
293 	   destroys it */
294 	MESSAGE_DESTROY,			/* Destroy the object */
295 	MESSAGE_INCREFCOUNT,		/* Increment object ref.count */
296 	MESSAGE_DECREFCOUNT,		/* Decrement object ref.count */
297 	MESSAGE_GETDEPENDENT,		/* Get dependent object */
298 	MESSAGE_SETDEPENDENT,		/* Set dependent object (e.g.ctx->dev) */
299 	MESSAGE_CLONE,				/* Clone the object */
300 
301 	/* Attribute messages.  The reason for the numeric vs.non-numeric
302 	   attribute messages is that for improved error checking the data types
303 	   that these work with are explicitly specified by the user based on
304 	   which function they call to get/set them rather than being implicitly
305 	   specified by the attribute ID.  Because of the explicit typing, the
306 	   handlers have to be able to check to make sure that the actual type
307 	   matches what the user specified, so we need one message type for
308 	   numeric attributes and one for string attributes */
309 	MESSAGE_GETATTRIBUTE,		/* Get numeric object attribute */
310 	MESSAGE_GETATTRIBUTE_S,		/* Get string object attribute */
311 	MESSAGE_SETATTRIBUTE,		/* Set numeric object attribute */
312 	MESSAGE_SETATTRIBUTE_S,		/* Set string object attribute */
313 	MESSAGE_DELETEATTRIBUTE,	/* Delete object attribute */
314 
315 	/* General messages.  The check message is used for informational
316 	   purposes only so that problems (e.g. an attempt to use a public key
317 	   where a private key is required) can be reported to the user
318 	   immediately as a function parameter error rather than appearing much
319 	   later as an object use permission error when the kernel blocks the
320 	   access.  Final access checking is always still done at the kernel
321 	   level to avoid the confused deputy problem */
322 	MESSAGE_COMPARE,			/* Compare objs. or obj.properties */
323 	MESSAGE_CHECK,				/* Check object info */
324 	MESSAGE_SELFTEST,			/* Perform a self-test */
325 
326 	/* Messages sent from the kernel to object message handlers.  These never
327 	   originate from outside the kernel but are generated in response to
328 	   other messages to notify an object of a change in its state */
329 	MESSAGE_CHANGENOTIFY,		/* Notification of obj.status chge.*/
330 
331 	/* Object-type-specific messages */
332 	MESSAGE_CTX_ENCRYPT,		/* Context: Action = encrypt */
333 	MESSAGE_CTX_DECRYPT,		/* Context: Action = decrypt */
334 	MESSAGE_CTX_SIGN,			/* Context: Action = sign */
335 	MESSAGE_CTX_SIGCHECK,		/* Context: Action = sigcheck */
336 	MESSAGE_CTX_HASH,			/* Context: Action = hash */
337 	MESSAGE_CTX_GENKEY,			/* Context: Generate a key */
338 	MESSAGE_CTX_GENIV,			/* Context: Generate an IV */
339 	MESSAGE_CRT_SIGN,			/* Cert: Action = sign cert */
340 	MESSAGE_CRT_SIGCHECK,		/* Cert: Action = check/verify cert */
341 	MESSAGE_CRT_EXPORT,			/* Cert: Export encoded cert data */
342 	MESSAGE_DEV_QUERYCAPABILITY,/* Device: Query capability */
343 	MESSAGE_DEV_EXPORT,			/* Device: Action = export key */
344 	MESSAGE_DEV_IMPORT,			/* Device: Action = import key */
345 	MESSAGE_DEV_SIGN,			/* Device: Action = sign */
346 	MESSAGE_DEV_SIGCHECK,		/* Device: Action = sig.check */
347 	MESSAGE_DEV_DERIVE,			/* Device: Action = derive key */
348 	MESSAGE_DEV_KDF,			/* Device: Action = KDF */
349 	MESSAGE_DEV_CREATEOBJECT,	/* Device: Create object */
350 	MESSAGE_DEV_CREATEOBJECT_INDIRECT,	/* Device: Create obj.from data */
351 	MESSAGE_ENV_PUSHDATA,		/* Envelope: Push data */
352 	MESSAGE_ENV_POPDATA,		/* Envelope: Pop data */
353 	MESSAGE_KEY_GETKEY,			/* Keyset: Instantiate ctx/cert */
354 	MESSAGE_KEY_SETKEY,			/* Keyset: Add ctx/cert */
355 	MESSAGE_KEY_DELETEKEY,		/* Keyset: Delete key/cert */
356 	MESSAGE_KEY_GETFIRSTCERT,	/* Keyset: Get first cert in sequence */
357 	MESSAGE_KEY_GETNEXTCERT,	/* Keyset: Get next cert in sequence */
358 	MESSAGE_KEY_CERTMGMT,		/* Keyset: Cert management */
359 	MESSAGE_USER_USERMGMT,		/* User: User management */
360 	MESSAGE_USER_TRUSTMGMT,		/* User: Trust management */
361 	MESSAGE_LAST,				/* Last valid message type */
362 
363 	/* Internal-object versions of the above messages */
364 	IMESSAGE_DESTROY = MKINTERNAL( MESSAGE_DESTROY ),
365 	IMESSAGE_INCREFCOUNT = MKINTERNAL( MESSAGE_INCREFCOUNT ),
366 	IMESSAGE_DECREFCOUNT = MKINTERNAL( MESSAGE_DECREFCOUNT ),
367 	IMESSAGE_GETDEPENDENT = MKINTERNAL( MESSAGE_GETDEPENDENT ),
368 	IMESSAGE_SETDEPENDENT = MKINTERNAL( MESSAGE_SETDEPENDENT ),
369 	IMESSAGE_CLONE = MKINTERNAL( MESSAGE_CLONE ),
370 
371 	IMESSAGE_GETATTRIBUTE = MKINTERNAL( MESSAGE_GETATTRIBUTE ),
372 	IMESSAGE_GETATTRIBUTE_S = MKINTERNAL( MESSAGE_GETATTRIBUTE_S ),
373 	IMESSAGE_SETATTRIBUTE = MKINTERNAL( MESSAGE_SETATTRIBUTE ),
374 	IMESSAGE_SETATTRIBUTE_S = MKINTERNAL( MESSAGE_SETATTRIBUTE_S ),
375 	IMESSAGE_DELETEATTRIBUTE = MKINTERNAL( MESSAGE_DELETEATTRIBUTE ),
376 
377 	IMESSAGE_COMPARE = MKINTERNAL( MESSAGE_COMPARE ),
378 	IMESSAGE_CHECK = MKINTERNAL( MESSAGE_CHECK ),
379 	IMESSAGE_SELFTEST = MKINTERNAL( MESSAGE_SELFTEST ),
380 
381 	IMESSAGE_CHANGENOTIFY = MKINTERNAL( MESSAGE_CHANGENOTIFY ),
382 
383 	IMESSAGE_CTX_ENCRYPT = MKINTERNAL( MESSAGE_CTX_ENCRYPT ),
384 	IMESSAGE_CTX_DECRYPT = MKINTERNAL( MESSAGE_CTX_DECRYPT ),
385 	IMESSAGE_CTX_SIGN = MKINTERNAL( MESSAGE_CTX_SIGN ),
386 	IMESSAGE_CTX_SIGCHECK = MKINTERNAL( MESSAGE_CTX_SIGCHECK ),
387 	IMESSAGE_CTX_HASH = MKINTERNAL( MESSAGE_CTX_HASH ),
388 	IMESSAGE_CTX_GENKEY = MKINTERNAL( MESSAGE_CTX_GENKEY ),
389 	IMESSAGE_CTX_GENIV = MKINTERNAL( MESSAGE_CTX_GENIV ),
390 	IMESSAGE_CRT_SIGN = MKINTERNAL( MESSAGE_CRT_SIGN ),
391 	IMESSAGE_CRT_SIGCHECK = MKINTERNAL( MESSAGE_CRT_SIGCHECK ),
392 	IMESSAGE_CRT_EXPORT = MKINTERNAL( MESSAGE_CRT_EXPORT ),
393 	IMESSAGE_DEV_QUERYCAPABILITY = MKINTERNAL( MESSAGE_DEV_QUERYCAPABILITY ),
394 	IMESSAGE_DEV_EXPORT = MKINTERNAL( MESSAGE_DEV_EXPORT ),
395 	IMESSAGE_DEV_IMPORT = MKINTERNAL( MESSAGE_DEV_IMPORT ),
396 	IMESSAGE_DEV_SIGN = MKINTERNAL( MESSAGE_DEV_SIGN ),
397 	IMESSAGE_DEV_SIGCHECK = MKINTERNAL( MESSAGE_DEV_SIGCHECK ),
398 	IMESSAGE_DEV_DERIVE = MKINTERNAL( MESSAGE_DEV_DERIVE ),
399 	IMESSAGE_DEV_KDF = MKINTERNAL( MESSAGE_DEV_KDF ),
400 	IMESSAGE_DEV_CREATEOBJECT = MKINTERNAL( MESSAGE_DEV_CREATEOBJECT ),
401 	IMESSAGE_DEV_CREATEOBJECT_INDIRECT = MKINTERNAL( MESSAGE_DEV_CREATEOBJECT_INDIRECT ),
402 	IMESSAGE_ENV_PUSHDATA = MKINTERNAL( MESSAGE_ENV_PUSHDATA ),
403 	IMESSAGE_ENV_POPDATA = MKINTERNAL( MESSAGE_ENV_POPDATA ),
404 	IMESSAGE_KEY_GETKEY = MKINTERNAL( MESSAGE_KEY_GETKEY ),
405 	IMESSAGE_KEY_SETKEY = MKINTERNAL( MESSAGE_KEY_SETKEY ),
406 	IMESSAGE_KEY_DELETEKEY = MKINTERNAL( MESSAGE_KEY_DELETEKEY ),
407 	IMESSAGE_KEY_GETFIRSTCERT = MKINTERNAL( MESSAGE_KEY_GETFIRSTCERT ),
408 	IMESSAGE_KEY_GETNEXTCERT = MKINTERNAL( MESSAGE_KEY_GETNEXTCERT ),
409 	IMESSAGE_KEY_CERTMGMT = MKINTERNAL( MESSAGE_KEY_CERTMGMT ),
410 	IMESSAGE_USER_USERMGMT = MKINTERNAL( MESSAGE_USER_USERMGMT ),
411 	IMESSAGE_USER_TRUSTMGMT = MKINTERNAL( MESSAGE_USER_TRUSTMGMT ),
412 	IMESSAGE_LAST = MKINTERNAL( MESSAGE_LAST )
413 	} MESSAGE_TYPE;
414 
415 /* The properties that MESSAGE_COMPARE can compare */
416 
417 typedef enum {
418 	MESSAGE_COMPARE_NONE,			/* No comparison type */
419 	MESSAGE_COMPARE_HASH,			/* Compare hash/MAC value */
420 	MESSAGE_COMPARE_ICV,			/* Compare ICV value */
421 	MESSAGE_COMPARE_KEYID,			/* Compare key IDs */
422 	MESSAGE_COMPARE_KEYID_PGP,		/* Compare PGP key IDs */
423 	MESSAGE_COMPARE_KEYID_OPENPGP,	/* Compare OpenPGP key IDs */
424 	MESSAGE_COMPARE_SUBJECT,		/* Compare subject */
425 	MESSAGE_COMPARE_ISSUERANDSERIALNUMBER,	/* Compare iAndS */
426 	MESSAGE_COMPARE_SUBJECTKEYIDENTIFIER,	/* Compare subjectKeyIdentifier */
427 	MESSAGE_COMPARE_FINGERPRINT_SHA1,/* Compare cert.fingerprint */
428 	MESSAGE_COMPARE_FINGERPRINT_SHA2,/* Compare fingerprint, SHA2 */
429 	MESSAGE_COMPARE_FINGERPRINT_SHAng,/* Compare fingerprint, SHAng */
430 	MESSAGE_COMPARE_CERTOBJ,		/* Compare cert objects */
431 	MESSAGE_COMPARE_LAST			/* Last possible compare type */
432 	} MESSAGE_COMPARE_TYPE;
433 
434 /* The checks that MESSAGE_CHECK performs.  There are a number of variations
435    of the checking we can perform, either the object is initialised in a
436    state to perform the required action (meaning that it has to be in the
437    high state), the object is ready to be initialised for the required
438    action, for example an encryption context about to have a key loaded for
439    encryption (meaning that it has to be in the low state), or the check is
440    on a passive container object that constrains another object (for example
441    a cert being attached to a context) for which the state isn't important
442    in this instance.  Usually we check to make sure that the cert is in the
443    high state, but when a cert is being created/imported it may not be in
444    the high state yet at the time the check is being carried out */
445 
446 typedef enum {
447 	/* Standard checks, for which the object must be initialised in a state
448 	   to perform this operation */
449 	MESSAGE_CHECK_NONE,				/* No check type */
450 	MESSAGE_CHECK_PKC,				/* Public or private key context */
451 	MESSAGE_CHECK_PKC_PRIVATE,		/* Private key context */
452 	MESSAGE_CHECK_PKC_ENCRYPT,		/* Public encryption context */
453 	MESSAGE_CHECK_PKC_DECRYPT,		/* Private decryption context */
454 	MESSAGE_CHECK_PKC_SIGCHECK,		/* Public signature check context */
455 	MESSAGE_CHECK_PKC_SIGN,			/* Private signature context */
456 	MESSAGE_CHECK_PKC_KA_EXPORT,	/* Key agreement - export context */
457 	MESSAGE_CHECK_PKC_KA_IMPORT,	/* Key agreement - import context */
458 	MESSAGE_CHECK_CRYPT,			/* Conventional encryption context */
459 	MESSAGE_CHECK_HASH,				/* Hash context */
460 	MESSAGE_CHECK_MAC,				/* MAC context */
461 
462 	/* Checks that an object is ready to be initialised to perform this
463 	   operation */
464 	MESSAGE_CHECK_CRYPT_READY,		/* Ready for conv.encr. init */
465 	MESSAGE_CHECK_MAC_READY,		/* Ready for MAC init */
466 	MESSAGE_CHECK_KEYGEN_READY,		/* Ready for key generation */
467 
468 	/* Checks on purely passive container objects that constrain action
469 	   objects */
470 	MESSAGE_CHECK_PKC_ENCRYPT_AVAIL,/* Encryption available */
471 	MESSAGE_CHECK_PKC_DECRYPT_AVAIL,/* Decryption available */
472 	MESSAGE_CHECK_PKC_SIGCHECK_AVAIL,	/* Signature check available */
473 	MESSAGE_CHECK_PKC_SIGN_AVAIL,	/* Signature available */
474 	MESSAGE_CHECK_PKC_KA_EXPORT_AVAIL,	/* Key agreement - export available */
475 	MESSAGE_CHECK_PKC_KA_IMPORT_AVAIL,	/* Key agreement - import available */
476 
477 	/* Misc.checks for meta-capabilities not directly connected with object
478 	   actions.  The certificate check is used to verify that a certificate
479 	   is generally valid (for example not expired) without having to
480 	   performing a full signature verification up to a trusted root, this
481 	   is used to verify certificates passed in as parameters (for example
482 	   server certificates) to ensure that the client doesn't get invalid
483 	   data back when it tries to connect to the server.  The CA check
484 	   applies to both PKC contexts and certificates, when the message is
485 	   forwarded to a dependent CA cert it's forwarded as the internal
486 	   MESSAGE_CHECK_CACERT check type, since MESSAGE_CHECK_CA requires both
487 	   a PKC context and a certificate */
488 	MESSAGE_CHECK_CERT,				/* Generic certificate */
489 	MESSAGE_CHECK_CERTxx,			/* Internal value used for cert.checks */
490 	MESSAGE_CHECK_CA,				/* Cert signing capability */
491 	MESSAGE_CHECK_CACERT,			/* Internal value used for CA checks */
492 	MESSAGE_CHECK_LAST				/* Last possible check type */
493 	} MESSAGE_CHECK_TYPE;
494 
495 /* The notifications that a MESSAGE_CHANGENOTIFY can deliver */
496 
497 typedef enum {
498 	MESSAGE_CHANGENOTIFY_NONE,		/* No notification type */
499 	MESSAGE_CHANGENOTIFY_STATE,		/* Object should save/rest.int.state */
500 	MESSAGE_CHANGENOTIFY_OBJHANDLE,	/* Object cloned, handle changed */
501 	MESSAGE_CHANGENOTIFY_OWNERHANDLE,	/* Object cloned, owner handle changed */
502 	MESSAGE_CHANGENOTIFY_LAST		/* Last possible notification type */
503 	} MESSAGE_CHANGENOTIFY_TYPE;
504 
505 /* The operations that a MESSAGE_USER_USERMGMT can perform */
506 
507 typedef enum {
508 	MESSAGE_USERMGMT_NONE,			/* No operation type */
509 	MESSAGE_USERMGMT_ZEROISE,		/* Zeroise users */
510 	MESSAGE_USERMGMT_LAST			/* Last possible operation type */
511 	} MESSAGE_USERMGMT_TYPE;
512 
513 /* The operations that a MESSAGE_USER_TRUSTMGMT can perform */
514 
515 typedef enum {
516 	MESSAGE_TRUSTMGMT_NONE,			/* No operation type */
517 	MESSAGE_TRUSTMGMT_ADD,			/* Add trusted cert */
518 	MESSAGE_TRUSTMGMT_DELETE,		/* Delete trusted cert */
519 	MESSAGE_TRUSTMGMT_CHECK,		/* Check trust status of cert */
520 	MESSAGE_TRUSTMGMT_GETISSUER,	/* Get trusted issuer cert */
521 	MESSAGE_TRUSTMGMT_LAST			/* Last possible operation type */
522 	} MESSAGE_TRUSTMGMT_TYPE;
523 
524 /* Options for the MESSAGE_SETDEPENDENT message */
525 
526 typedef enum {
527 	SETDEP_OPTION_NONE,				/* No option type */
528 	SETDEP_OPTION_NOINCREF,			/* Don't inc.dep.objs reference count */
529 	SETDEP_OPTION_INCREF,			/* Increment dep.objs reference count */
530 	SETDEP_OPTION_LAST				/* Last possible option type */
531 	} MESSAGE_SETDEPENDENT_TYPE;
532 
533 /* When getting/setting string data that consists of (value, length) pairs,
534    we pass a pointer to a value-and-length structure rather than a pointer
535    to the data itself */
536 
537 typedef struct {
538 	BUFFER_FIXED( length ) \
539 	void *data;							/* Data */
540 	int length;							/* Length */
541 	} MESSAGE_DATA;
542 
543 #define setMessageData( msgDataPtr, dataPtr, dataLength ) \
544 	{ \
545 	( msgDataPtr )->data = ( dataPtr ); \
546 	( msgDataPtr )->length = ( dataLength ); \
547 	}
548 
549 /* When passing constant data to krnlSendMessage() we get compiler warnings
550    because the function is prototyped as taking a 'void *'.  The following
551    symbolic value for use in casts corrects the parameter mismatch */
552 
553 typedef void *MESSAGE_CAST;
554 
555 /* Some messages communicate standard data values that are used again and
556    again, so we predefine values for these that can be used globally */
557 
558 #define MESSAGE_VALUE_TRUE			( ( MESSAGE_CAST ) &messageValueTrue )
559 #define MESSAGE_VALUE_FALSE			( ( MESSAGE_CAST ) &messageValueFalse )
560 #define MESSAGE_VALUE_OK			( ( MESSAGE_CAST ) &messageValueCryptOK )
561 #define MESSAGE_VALUE_ERROR			( ( MESSAGE_CAST ) &messageValueCryptError )
562 #define MESSAGE_VALUE_UNUSED		( ( MESSAGE_CAST ) &messageValueCryptUnused )
563 #define MESSAGE_VALUE_DEFAULT		( ( MESSAGE_CAST ) &messageValueCryptUseDefault )
564 #define MESSAGE_VALUE_CURSORFIRST	( ( MESSAGE_CAST ) &messageValueCursorFirst )
565 #define MESSAGE_VALUE_CURSORNEXT	( ( MESSAGE_CAST ) &messageValueCursorNext )
566 #define MESSAGE_VALUE_CURSORPREVIOUS ( ( MESSAGE_CAST ) &messageValueCursorPrevious )
567 #define MESSAGE_VALUE_CURSORLAST	( ( MESSAGE_CAST ) &messageValueCursorLast )
568 
569 extern const int messageValueTrue, messageValueFalse;
570 extern const int messageValueCryptOK, messageValueCryptError;
571 extern const int messageValueCryptUnused, messageValueCryptUseDefault;
572 extern const int messageValueCursorFirst, messageValueCursorNext;
573 extern const int messageValueCursorPrevious, messageValueCursorLast;
574 
575 /* Check for membership within an attribute class */
576 
577 #define isAttribute( attribute ) \
578 	( ( attribute ) > CRYPT_ATTRIBUTE_NONE && \
579 	  ( attribute ) < CRYPT_ATTRIBUTE_LAST )
580 #define isInternalAttribute( attribute ) \
581 	( ( attribute ) > CRYPT_IATTRIBUTE_FIRST && \
582 	  ( attribute ) < CRYPT_IATTRIBUTE_LAST )
583 
584 /* Check whether a message is in a given message class, used in object
585    message handlers */
586 
587 #define isAttributeMessage( message ) \
588 	( ( message ) >= MESSAGE_GETATTRIBUTE && \
589 	  ( message ) <= MESSAGE_DELETEATTRIBUTE )
590 #define isActionMessage( message ) \
591 	( ( message ) >= MESSAGE_CTX_ENCRYPT && \
592 	  ( message ) <= MESSAGE_CTX_HASH )
593 #define isMechanismActionMessage( message ) \
594 	( ( message ) >= MESSAGE_DEV_EXPORT && \
595 	  ( message ) <= MESSAGE_DEV_KDF )
596 
597 /* The following handles correspond to built-in fixed object types that are
598    available throughout the architecture.  Currently there are two objects,
599    an internal system object that encapsulates the built-in RNG and the
600    built-in mechanism types (if this ever becomes a bottleneck the two can be
601    separated into different objects) and a default user object which is used
602    when there are no explicit user objects being employed */
603 
604 #define SYSTEM_OBJECT_HANDLE	0	/* Internal system object */
605 #define DEFAULTUSER_OBJECT_HANDLE 1	/* Default user object */
606 
607 #define NO_SYSTEM_OBJECTS		2	/* Total number of system objects */
608 
609 /* We limit the maximum number of objects to a sensible value to prevent
610    deliberate/accidental DoS attacks.  The following represents about 32MB
611    of object data, which should be a good indication that there are more
612    objects present than there should be */
613 
614 #define MAX_OBJECTS				16384
615 
616 /****************************************************************************
617 *																			*
618 *							Action Message Types							*
619 *																			*
620 ****************************************************************************/
621 
622 /* Action messages come in two types, direct action messages and mechanism-
623    action messages.  Action messages apply directly to action objects (for
624    example transform a block of data) while mechanism-action messages apply
625    to device objects and involve extra formatting above and beyond the
626    direct action (for example perform PKCS #1 padding and then transform a
627    block of data).
628 
629    Each object that processes direct action messages can can have a range of
630    permission settings that control how action messages sent to it are
631    handled.  The most common case is that the action isn't available for
632    this object, ACTION_PERM_NOTAVAIL.  This is an all-zero permission, so
633    the default is deny-all unless the action is explicitly permitted.  The
634    other permissions are ACTION_PERM_NONE, which means that the action is in
635    theory available but has been turned off, ACTION_PERM_NONE_EXTERNAL,
636    which means that the action is only valid if the message is coming from
637    inside cryptlib, and ACTION_PERM_ALL, which means that the action is
638    available for anyone.  In order to set all permissions to a certain value
639    (e.g. NONE_EXTERNAL), we define overall values xxx_ALL that (in
640    combination with the kernel-enforced ratchet) can be used to set all
641    settings to (at most) the given value.
642 
643    The order of the action bits is:
644 
645 	  hash   sign  encr
646 		|	  |		|
647 	xx xx xx xx xx xx
648 	 |	   |	 |
649 	kgen sigch  decr
650 
651     x. .x|x. .x|x. .x	Hex digits
652 
653    Common settings are 0xCFF (new PKC, all operations), 0x0F (key-loaded
654    conv., all operations), and 0xAA (key-loaded PKC, internal-only
655    operations).
656 
657    The kernel enforces a ratchet for these setting that only allows them to
658    be set to a more restrictive value than their existing one.  If a setting
659    starts out as not available on object creation, it can never be enabled.
660    If a setting starts as 'none-external', it can only be set to a straight
661    'none', but never to 'all' */
662 
663 #define ACTION_PERM_NOTAVAIL		0x00
664 #define ACTION_PERM_NONE			0x01
665 #define ACTION_PERM_NONE_EXTERNAL	0x02
666 #define ACTION_PERM_ALL				0x03
667 
668 #define ACTION_PERM_NONE_ALL			0x000
669 #define ACTION_PERM_NONE_EXTERNAL_ALL	0xAAA
670 #define ACTION_PERM_ALL_MAX				0xFFF
671 
672 #define ACTION_PERM_BASE	MESSAGE_CTX_ENCRYPT
673 #define ACTION_PERM_MASK	0x03
674 #define ACTION_PERM_BITS	2
675 #define ACTION_PERM_COUNT	( MESSAGE_CTX_GENKEY - \
676 							  MESSAGE_CTX_ENCRYPT + 1 )
677 #define ACTION_PERM_LAST	\
678 		( 1 << ( ( ( ACTION_PERM_COUNT ) * ACTION_PERM_BITS ) + 1 ) )
679 #define ACTION_PERM_SHIFT( action ) \
680 		( ( ( action ) - ACTION_PERM_BASE ) * ACTION_PERM_BITS )
681 #define MK_ACTION_PERM( action, perm ) \
682 		( ( perm ) << ACTION_PERM_SHIFT( action ) )
683 #define MK_ACTION_PERM_NONE_EXTERNAL( action ) \
684 		( ( action ) & ACTION_PERM_NONE_EXTERNAL_ALL )
685 
686 /* Symbolic defines to allow the action flags to be range-checked alongside
687    all of the other flag types */
688 
689 #define ACTION_PERM_FLAG_NONE		0x000
690 #define ACTION_PERM_FLAG_MAX		0xFFF
691 
692 /* The mechanism types.  The distinction between the PKCS #1 and raw PKCS #1
693    mechanisms is somewhat artificial in that they do the same thing, however
694    it's easier for the kernel to perform security checks on parameters if
695    the two are distinct */
696 
697 typedef enum {
698 	MECHANISM_NONE,				/* No mechanism type */
699 	MECHANISM_ENC_PKCS1,		/* PKCS #1 en/decrypt */
700 	MECHANISM_ENC_PKCS1_PGP,	/* PKCS #1 using PGP formatting */
701 	MECHANISM_ENC_PKCS1_RAW,	/* PKCS #1 returning uninterpreted data */
702 	MECHANISM_ENC_OAEP,			/* OAEP en/decrypt */
703 	MECHANISM_ENC_CMS,			/* CMS key wrap */
704 	MECHANISM_SIG_PKCS1,		/* PKCS #1 sign */
705 	MECHANISM_SIG_SSL,			/* SSL sign with dual hashes */
706 	MECHANISM_DERIVE_PKCS5,		/* PKCS #5 derive */
707 	MECHANISM_DERIVE_PKCS12,	/* PKCS #12 derive */
708 	MECHANISM_DERIVE_SSL,		/* SSL derive */
709 	MECHANISM_DERIVE_TLS,		/* TLS derive */
710 	MECHANISM_DERIVE_TLS12,		/* TLS 1.2 derive */
711 	MECHANISM_DERIVE_CMP,		/* CMP/Entrust derive */
712 	MECHANISM_DERIVE_PGP,		/* OpenPGP S2K derive */
713 	MECHANISM_PRIVATEKEYWRAP,	/* Private key wrap */
714 	MECHANISM_PRIVATEKEYWRAP_PKCS8,	/* PKCS #8 private key wrap */
715 	MECHANISM_PRIVATEKEYWRAP_PGP2,	/* PGP 2.x private key wrap */
716 	MECHANISM_PRIVATEKEYWRAP_OPENPGP_OLD,/* Legacy OpenPGP private key wrap */
717 	MECHANISM_PRIVATEKEYWRAP_OPENPGP,/* OpenPGP private key wrap */
718 	MECHANISM_LAST				/* Last possible mechanism type */
719 	} MECHANISM_TYPE;
720 
721 /* A structure to hold information needed by the key export/import mechanism.
722    The key can be passed as raw key data or as a context if tied to hardware
723    that doesn't allow keying material outside the hardware's security
724    perimeter:
725 
726 	PKCS #1,	wrappedData = wrapped key
727 	PKCS #1 PGP	keyData = -
728 				keyContext = context containing key
729 				wrapContext = wrap/unwrap PKC context
730 				auxContext = CRYPT_UNUSED
731 				auxInfo = CRYPT_UNUSED
732 	PKCS #1	raw	wrappedData = wrapped raw data
733 				keyData = raw data
734 				keyContext = CRYPT_UNUSED
735 				wrapContext = wrap/unwrap PKC context
736 				auxContext = CRYPT_UNUSED
737 				auxInfo = CRYPT_UNUSED
738 	OAEP		wrappedData = wrapped key
739 				keyData = -
740 				keyContext = context containing key
741 				wrapContext = wrap/unwrap PKC context
742 				auxContext = CRYPT_UNUSED
743 				auxInfo = MGF1 algorithm
744 	CMS			wrappedData = wrapped key
745 				keyData = -
746 				keyContext = context containing key
747 				wrapContext = wrap/unwrap conventional context
748 				auxContext = CRYPT_UNUSED
749 				auxInfo = CRYPT_UNUSED
750 	Private		wrappedData = padded encrypted private key components
751 	key wrap	keyData = -
752 				keyContext = context containing private key
753 				wrapContext = wrap/unwrap conventional context
754 				auxContext = CRYPT_UNUSED
755 				auxInfo = CRYPT_UNUSED */
756 
757 typedef struct {
758 	BUFFER_OPT_FIXED( wrappedDataLength ) \
759 		void *wrappedData;					/* Wrapped key */
760 	int wrappedDataLength;
761 	BUFFER_FIXED( keyDataLength ) \
762 		void *keyData;						/* Raw key */
763 	int keyDataLength;
764 	VALUE_HANDLE CRYPT_HANDLE keyContext;	/* Context containing raw key */
765 	VALUE_HANDLE CRYPT_HANDLE wrapContext;	/* Wrap/unwrap context */
766 	VALUE_HANDLE CRYPT_HANDLE auxContext;	/* Auxiliary context */
767 	int auxInfo;							/* Auxiliary info */
768 	} MECHANISM_WRAP_INFO;
769 
770 /* A structure to hold information needed by the sign/sig check mechanism:
771 
772 	PKCS #1		signature = signature
773 				hashContext = hash to sign
774 				signContext = signing key
775 
776 	SSL			signature = signature
777 				hashContext, hashContext2 = dual hashes to sign
778 				signContext = signing key */
779 
780 typedef struct {
781 	BUFFER_OPT_FIXED( signatureLength ) \
782 		void *signature;					/* Signature */
783 	int signatureLength;
784 	VALUE_HANDLE CRYPT_CONTEXT hashContext;	/* Hash context */
785 	VALUE_HANDLE CRYPT_CONTEXT hashContext2;/* Secondary hash context */
786 	VALUE_HANDLE CRYPT_HANDLE signContext;	/* Signing context */
787 	} MECHANISM_SIGN_INFO;
788 
789 /* A structure to hold information needed by the key derivation mechanism.
790    This differs from the KDF mechanism that follows in that the "Derive"
791    form is used with an iteration count for password-based key derivation
792    while the "KDF" form is used without an iteration count for straight key
793    derivation from a master secret.  An exception to this is the SSL/TLS
794    derivation, which uses the resulting data in so many ways that it's not
795    possible to perform a generic context -> context transformation but
796    requires a generalisation in which the raw output data is available:
797 
798 	PKCS #5,	dataOut = key data
799 	CMP, PGP	dataIn = password
800 				hashAlgo = hash algorithm
801 				salt = salt
802 				iterations = iteration count
803 	SSL/TLS/	dataOut = key data/master secret
804 		TLS 1.2	dataIn = master secret/premaster secret
805 				hashAlgo = CRYPT_USE_DEFAULT
806 				salt = client || server random/server || client random
807 				iterations = 1 */
808 
809 typedef struct {
810 	BUFFER_OPT_FIXED( dataOutLength ) \
811 		void *dataOut;						/* Output keying information */
812 	int dataOutLength;
813 	BUFFER_FIXED( dataInLength ) \
814 		const void *dataIn;					/* Input keying information */
815 	int dataInLength;
816 	VALUE_HANDLE CRYPT_ALGO_TYPE hashAlgo;	/* Hash algorithm */
817 	int hashParam;							/* Optional algorithm parameters */
818 	BUFFER_OPT_FIXED( saltLength ) \
819 		const void *salt;					/* Salt/randomiser */
820 	int saltLength;
821 	int iterations;							/* Iterations of derivation function */
822 	} MECHANISM_DERIVE_INFO;
823 
824 /* A structure to hold information needed by the KDF mechanism:
825 
826 	CMS AuthEnc	keyContext = encryption/MAC context
827 				masterKeyContext = context containing master secret
828 				hashAlgo = hash algorithm
829 				salt = salt */
830 
831 typedef struct {
832 	VALUE_HANDLE CRYPT_HANDLE keyContext;	/* Context containing derived key */
833 	VALUE_HANDLE CRYPT_HANDLE masterKeyContext;/* Context containing master key */
834 	VALUE_HANDLE CRYPT_ALGO_TYPE hashAlgo;	/* Hash algorithm */
835 	int hashParam;							/* Optional algorithm parameters */
836 	BUFFER_OPT_FIXED( saltLength ) \
837 		const void *salt;					/* Salt/randomiser */
838 	int saltLength;
839 	} MECHANISM_KDF_INFO;
840 
841 /* Macros to make it easier to work with the mechanism info types.  The
842    shortened name forms in the macro args are necessary to avoid clashes with
843    the struct members.  The long lines are necessary because older Borland
844    compilers can't handle line breaks at this point in a macro definition */
845 
846 #define clearMechanismInfo( mechanismInfo ) \
847 		memset( mechanismInfo, 0, sizeof( *mechanismInfo ) )
848 
849 #define setMechanismWrapInfo( mechanismInfo, wrapped, wrappedLen, key, keyLen, keyCtx, wrapCtx ) \
850 		{ \
851 		memset( mechanismInfo, 0, sizeof( MECHANISM_WRAP_INFO ) ); \
852 		( mechanismInfo )->wrappedData = ( wrapped ); \
853 		( mechanismInfo )->wrappedDataLength = ( wrappedLen ); \
854 		( mechanismInfo )->keyData = ( key ); \
855 		( mechanismInfo )->keyDataLength = ( keyLen ); \
856 		( mechanismInfo )->keyContext = ( keyCtx ); \
857 		( mechanismInfo )->wrapContext = ( wrapCtx ); \
858 		( mechanismInfo )->auxContext = \
859 			( mechanismInfo )->auxInfo = CRYPT_UNUSED; \
860 		ANALYSER_HINT( isHandleRangeValid( ( mechanismInfo )->keyContext ) ); \
861 		}			   /* Hack for unimplemented VALUE() op.in VS 2013 */
862 
863 #define setMechanismWrapInfoEx( mechanismInfo, wrapped, wrappedLen, key, keyLen, keyCtx, wrapCtx, auxCtx, auxInf ) \
864 		{ \
865 		memset( mechanismInfo, 0, sizeof( MECHANISM_WRAP_INFO ) ); \
866 		( mechanismInfo )->wrappedData = ( wrapped ); \
867 		( mechanismInfo )->wrappedDataLength = ( wrappedLen ); \
868 		( mechanismInfo )->keyData = ( key ); \
869 		( mechanismInfo )->keyDataLength = ( keyLen ); \
870 		( mechanismInfo )->keyContext = ( keyCtx ); \
871 		( mechanismInfo )->wrapContext = ( wrapCtx ); \
872 		( mechanismInfo )->auxContext = ( auxCtx ); \
873 		( mechanismInfo )->auxInfo = ( auxInf ); \
874 		}
875 
876 #define setMechanismSignInfo( mechanismInfo, sig, sigLen, hashCtx, hashCtx2, signCtx ) \
877 		{ \
878 		memset( mechanismInfo, 0, sizeof( MECHANISM_SIGN_INFO ) ); \
879 		( mechanismInfo )->signature = ( sig ); \
880 		( mechanismInfo )->signatureLength = ( sigLen ); \
881 		( mechanismInfo )->hashContext = ( hashCtx ); \
882 		( mechanismInfo )->hashContext2 = ( hashCtx2 ); \
883 		( mechanismInfo )->signContext = ( signCtx ); \
884 		}
885 
886 #define setMechanismDeriveInfo( mechanismInfo, out, outLen, in, inLen, hAlgo, slt, sltLen, iters ) \
887 		{ \
888 		memset( mechanismInfo, 0, sizeof( MECHANISM_DERIVE_INFO ) ); \
889 		( mechanismInfo )->dataOut = ( out ); \
890 		( mechanismInfo )->dataOutLength = ( outLen ); \
891 		( mechanismInfo )->dataIn = ( in ); \
892 		( mechanismInfo )->dataInLength = ( inLen ); \
893 		( mechanismInfo )->hashAlgo = ( hAlgo ); \
894 		( mechanismInfo )->salt = ( slt ); \
895 		( mechanismInfo )->saltLength = ( sltLen ); \
896 		( mechanismInfo )->iterations = ( iters ); \
897 		}
898 
899 #define setMechanismKDFInfo( mechanismInfo, keyCtx, masterKeyCtx, hAlgo, slt, sltLen ) \
900 		{ \
901 		memset( mechanismInfo, 0, sizeof( MECHANISM_KDF_INFO ) ); \
902 		( mechanismInfo )->keyContext = ( keyCtx ); \
903 		( mechanismInfo )->masterKeyContext = ( masterKeyCtx ); \
904 		( mechanismInfo )->hashAlgo = ( hAlgo ); \
905 		( mechanismInfo )->salt = ( slt ); \
906 		( mechanismInfo )->saltLength = ( sltLen ); \
907 		}
908 
909 /****************************************************************************
910 *																			*
911 *								Misc Message Types							*
912 *																			*
913 ****************************************************************************/
914 
915 /* Beside the general value+length and mechanism messages, we also have a
916    number of special-purposes messages that require their own parameter
917    data structures.  These are:
918 
919    Create object messages, used to create objects via a device, either
920    directly or indirectly by instantiating the object from encoded data (for
921    example a certificate object from a certificate).  Usually the device is
922    the system object, but it can also be used to create contexts in hardware
923    devices.  In addition to the creation parameters we also pass in the
924    owner's user object to be stored with the object data for use when
925    needed.
926 
927    For the create-indirect certificate case, the arguments are:
928 
929 	arg1		Certificate object type.
930 	arg2		Optional certificate object ID type, used as an indicator of
931 				the primary object in a collection like a certificate chain
932 				or set.
933 	arg3		Optional KEYMGMT_FLAGs.
934 	strArg1		Certificate object data.
935 	strArg2		Optional certificate object ID (see arg2) */
936 
937 typedef struct {
938 	VALUE_HANDLE CRYPT_HANDLE cryptHandle;	/* Handle to created object */
939 	VALUE_HANDLE CRYPT_USER cryptOwner;		/* New object's owner */
940 	int arg1, arg2, arg3;					/* Integer args */
941 	BUFFER_OPT_FIXED( strArgLen1 ) \
942 		const void *strArg1;
943 	BUFFER_OPT_FIXED( strArgLen2 ) \
944 		const void *strArg2;				/* String args */
945 	VALUE_INT int strArgLen1;
946 	VALUE_INT_SHORT int strArgLen2;
947 	} MESSAGE_CREATEOBJECT_INFO;
948 
949 #define setMessageCreateObjectInfo( createObjectInfo, a1 ) \
950 		{ \
951 		memset( createObjectInfo, 0, sizeof( MESSAGE_CREATEOBJECT_INFO ) ); \
952 		( createObjectInfo )->cryptHandle = CRYPT_ERROR; \
953 		( createObjectInfo )->cryptOwner = CRYPT_ERROR; \
954 		( createObjectInfo )->arg1 = ( a1 ); \
955 		ANALYSER_HINT( isHandleRangeValid( ( createObjectInfo )->cryptHandle ) ); \
956 		}			   /* Hack for unimplemented VALUE() op.in VS 2013 */
957 
958 #define setMessageCreateObjectIndirectInfo( createObjectInfo, data, dataLen, type ) \
959 		{ \
960 		memset( createObjectInfo, 0, sizeof( MESSAGE_CREATEOBJECT_INFO ) ); \
961 		( createObjectInfo )->cryptHandle = CRYPT_ERROR; \
962 		( createObjectInfo )->cryptOwner = CRYPT_ERROR; \
963 		( createObjectInfo )->strArg1 = ( data ); \
964 		( createObjectInfo )->strArgLen1 = ( dataLen ); \
965 		( createObjectInfo )->arg1 = ( type ); \
966 		ANALYSER_HINT( isHandleRangeValid( ( createObjectInfo )->cryptHandle ) ); \
967 		}			   /* Hack for unimplemented VALUE() op.in VS 2013 */
968 
969 #define setMessageCreateObjectIndirectInfoEx( createObjectInfo, data, dataLen, type, options ) \
970 		{ \
971 		memset( createObjectInfo, 0, sizeof( MESSAGE_CREATEOBJECT_INFO ) ); \
972 		( createObjectInfo )->cryptHandle = CRYPT_ERROR; \
973 		( createObjectInfo )->cryptOwner = CRYPT_ERROR; \
974 		( createObjectInfo )->strArg1 = ( data ); \
975 		( createObjectInfo )->strArgLen1 = ( dataLen ); \
976 		( createObjectInfo )->arg1 = ( type ); \
977 		( createObjectInfo )->arg3 = ( options ); \
978 		ANALYSER_HINT( isHandleRangeValid( ( createObjectInfo )->cryptHandle ) ); \
979 		}			   /* Hack for unimplemented VALUE() op.in VS 2013 */
980 
981 #define updateMessageCreateObjectIndirectInfo( createObjectInfo, idType, id, idLength ) \
982 		{ \
983 		( createObjectInfo )->arg2 = ( idType ); \
984 		( createObjectInfo )->strArg2 = ( id ); \
985 		( createObjectInfo )->strArgLen2 = ( idLength ); \
986 		}
987 
988 /* Key management messages, used to set, get and delete keys.  The item type,
989    keyIDtype, keyID, and keyIDlength are mandatory, the aux.info depends on
990    the type of message (optional password for private key get/set, state
991    information for get next cert, null otherwise), and the flags are
992    generally only required where the keyset can hold multiple types of keys
993    (for example a crypto device acting as a keyset, or a PKCS #15 token).
994 
995    An itemType of KEYMGMT_ITEM_PUBLICKEY is somewhat more general than its
996    name implies in that keysets/devices that store private key information
997    alongside public-key data may delete both types of items if asked to
998    delete a KEYMGMT_ITEM_PUBLICKEY since the two items are (implicitly)
999    connected.
1000 
1001    An itemType of KEYMGMT_ITEM_REQUEST is distinct from the subtype
1002    KEYMGMT_ITEM_REVREQUEST because the former is for certification requests
1003    while the latter is for revocation requests, the distinction is made
1004    because some protocols only allow certification but not revocation
1005    requests and we want to trap these as soon as possible rather than some
1006    way down the road when error reporting becomes a lot more nonspecific.
1007 
1008    An itemType of KEYMGMT_ITEM_KEYMETADATA is a KEYMGMT_ITEM_PRIVATEKEY with
1009    the context passed in being a dummy context with actual keying data held
1010    in a crypto device.  What's stored in the keyset is purely the
1011    surrounding metadata like labels, dates, and ID information.  This is
1012    distinct from a KEYMGMT_ITEM_PRIVATEKEY both to allow for better checking
1013    by the kernel, since a KEYMGMT_ITEM_KEYMETADATA object may not be in the
1014    high state yet when it's used and doens't need a password like a
1015    KEYMGMT_ITEM_PRIVATEKEY does.  In addition keeping the types distinct is
1016    a safety feature since otherwise we'd need to allow a special-case
1017    KEYMGMT_ITEM_PRIVATEKEY store without a password, which is just asking
1018    for trouble.  Note that KEYMGMT_ITEM_PRIVATEKEY items are write-only, for
1019    reads they're treated the same as KEYMGMT_ITEM_PRIVATEKEY except that a
1020    dummy context is created.
1021 
1022    In addition to the flags that are used to handle various special-case
1023    read accesses, we can also specify a usage preference (e.g.
1024    confidentiality vs.signature) for cases where we may have multiple keys
1025    with the same keyID that differ only in required usage */
1026 
1027 typedef enum {
1028 	KEYMGMT_ITEM_NONE,			/* No item type */
1029 	KEYMGMT_ITEM_PUBLICKEY,		/* Access public key */
1030 	KEYMGMT_ITEM_PRIVATEKEY,	/* Access private key */
1031 	KEYMGMT_ITEM_SECRETKEY,		/* Access secret key */
1032 	KEYMGMT_ITEM_REQUEST,		/* Access cert request */
1033 	KEYMGMT_ITEM_REVREQUEST,	/* Access cert revocation request */
1034 	KEYMGMT_ITEM_PKIUSER,		/* Access PKI user info */
1035 	KEYMGMT_ITEM_REVOCATIONINFO,/* Access revocation info/CRL */
1036 	KEYMGMT_ITEM_KEYMETADATA,	/* Access key metadata for dummy ctx.*/
1037 	KEYMGMT_ITEM_DATA,			/* Other data (for PKCS #15 tokens) */
1038 	KEYMGMT_ITEM_LAST			/* Last possible item type */
1039 	} KEYMGMT_ITEM_TYPE;
1040 
1041 #define KEYMGMT_FLAG_NONE			0x0000	/* No flag type */
1042 #define KEYMGMT_FLAG_CHECK_ONLY		0x0001	/* Perform existence check only */
1043 #define KEYMGMT_FLAG_LABEL_ONLY		0x0002	/* Get key label only */
1044 #define KEYMGMT_FLAG_UPDATE			0x0004	/* Update existing (allow dups) */
1045 #define KEYMGMT_FLAG_DATAONLY_CERT	0x0008	/* Create data-only certificate */
1046 #define KEYMGMT_FLAG_CERT_AS_CERTCHAIN 0x010 /* Force creation of cert.chain
1047 												even if single cert.present */
1048 #define KEYMGMT_FLAG_USAGE_CRYPT	0x0020	/* Prefer encryption key */
1049 #define KEYMGMT_FLAG_USAGE_SIGN		0x0040	/* Prefer signature key */
1050 #define KEYMGMT_FLAG_GETISSUER		0x0080	/* Get issuing PKI user for cert */
1051 #define KEYMGMT_FLAG_INITIALOP		0x0100	/* Initial cert issue operation */
1052 #define KEYMGMT_FLAG_MAX			0x01FF	/* Maximum possible flag value */
1053 
1054 #define KEYMGMT_MASK_USAGEOPTIONS	( KEYMGMT_FLAG_USAGE_CRYPT | \
1055 									  KEYMGMT_FLAG_USAGE_SIGN )
1056 #define KEYMGMT_MASK_CERTOPTIONS	( KEYMGMT_FLAG_DATAONLY_CERT | \
1057 									  KEYMGMT_FLAG_CERT_AS_CERTCHAIN | \
1058 									  KEYMGMT_FLAG_USAGE_CRYPT | \
1059 									  KEYMGMT_FLAG_USAGE_SIGN )
1060 typedef struct {
1061 	VALUE_HANDLE CRYPT_HANDLE cryptHandle;	/* Returned key */
1062 	VALUE_HANDLE CRYPT_KEYID_TYPE keyIDtype;/* Key ID type */
1063 	BUFFER_OPT_FIXED( keyIDlength ) \
1064 		const void *keyID;					/* Key ID */
1065 	VALUE_INT_SHORT int keyIDlength;
1066 	BUFFER_OPT_FIXED( auxInfoLength ) \
1067 		void *auxInfo;						/* Aux.info (e.g.password for private key) */
1068 	VALUE_INT_SHORT int auxInfoLength;
1069 	int flags;								/* Access options */
1070 	} MESSAGE_KEYMGMT_INFO;
1071 
1072 #define setMessageKeymgmtInfo( keymgmtInfo, idType, id, idLength, aux, auxLen, keyFlags ) \
1073 		{ \
1074 		( keymgmtInfo )->cryptHandle = CRYPT_ERROR; \
1075 		( keymgmtInfo )->keyIDtype = ( idType ); \
1076 		( keymgmtInfo )->keyID = ( id ); \
1077 		( keymgmtInfo )->keyIDlength = ( idLength ); \
1078 		( keymgmtInfo )->auxInfo = ( aux ); \
1079 		( keymgmtInfo )->auxInfoLength = ( auxLen ); \
1080 		( keymgmtInfo )->flags = ( keyFlags ); \
1081 		ANALYSER_HINT( isHandleRangeValid( ( keymgmtInfo )->cryptHandle ) ); \
1082 		}			   /* Hack for unimplemented VALUE() op.in VS 2013 */
1083 
1084 /* Cert management messages used to handle CA operations.  All fields are
1085    mandatory, however the cryptCert and request fields may be set to
1086    CRYPT_UNUSED to indicate 'don't care' conditions */
1087 
1088 typedef struct {
1089 	CRYPT_CERTIFICATE cryptCert;	/* Returned cert */
1090 	CRYPT_CONTEXT caKey;			/* CA key to sign item */
1091 	CRYPT_CERTIFICATE request;		/* Request for operation */
1092 	} MESSAGE_CERTMGMT_INFO;
1093 
1094 #define setMessageCertMgmtInfo( certMgmtInfo, mgmtCaKey, mgmtRequest ) \
1095 		{ \
1096 		( certMgmtInfo )->cryptCert = CRYPT_ERROR; \
1097 		( certMgmtInfo )->caKey = ( mgmtCaKey ); \
1098 		( certMgmtInfo )->request = ( mgmtRequest ); \
1099 		ANALYSER_HINT( isHandleRangeValid( ( certMgmtInfo )->cryptCert ) ); \
1100 		}			   /* Hack for unimplemented VALUE() op.in VS 2013 */
1101 
1102 /****************************************************************************
1103 *																			*
1104 *								Kernel Functions							*
1105 *																			*
1106 ****************************************************************************/
1107 
1108 /* Error-detecting function pointers.  We store two copes of the pointer,
1109    the value itself and its bitwise inverse.  If on retrieving them their
1110    XOR isn't all-ones then one of the values has been corrupted and the
1111    pointer isn't safe to dereference.  The macros are used as:
1112 
1113 	FNPTR_DECLARE( PTR_TYPE, ptrStorage );
1114 
1115 	FNPTR_SET( ptrStorage, functionAddress );
1116 	functionPtr = FNPTR_GET( ptrStorage );
1117 	ENSURES( functionPtr != 0 );
1118 
1119    In terms of what to store and how, would could store two copies of the
1120    same value but that wouldn't detect identical corruption on both
1121    values.  We could also mask the value with a secret seed generated at
1122    runtime, but that's more useful for preventing pointer-overwriting
1123    attacks than detecting corruption, and it's not clear whether that's
1124    a real threat.  Finally, we could actually store a triple modular-
1125    redundant copy, but if we're trying to deal with that level of
1126    corruption then there are likely to be all sorts of other problems as
1127    well that we'd need to handle */
1128 
1129 #define FNPTR_TYPE				uintptr_t
1130 
1131 #define FNPTR_DECLARE( type, name ) \
1132 		type name##1; \
1133 		FNPTR_TYPE name##2
1134 
1135 #define FNPTR_INIT				NULL, 0
1136 
1137 #define FNPTR_SET( name, value ) \
1138 			{ \
1139 			name##1 = value; \
1140 			name##2 = ( ( FNPTR_TYPE ) value ) ^ ~0; \
1141 			}
1142 
1143 #define FNPTR_ISSET( name ) \
1144 		( ( name##1 ) != NULL && ( name##2 ) != 0 )
1145 
1146 #define FNPTR_GET( name ) \
1147 		( ( ( ( ( FNPTR_TYPE ) name##1 ) ^ ( name##2 ) ) != ~0 ) ? NULL : name##1 )
1148 
1149 /* cryptlib initialisation/shutdown functions */
1150 
1151 CHECK_RETVAL \
1152 int initCryptlib( void );
1153 CHECK_RETVAL \
1154 int endCryptlib( void );
1155 #if defined( __PALMOS__ ) || defined( __WIN32__ ) || defined( __WINCE__ )
1156   void preInit( void );
1157   void postShutdown( void );
1158 #endif /* Systems with OS-specific pre-init/post-shutdown facilities */
1159 
1160 /* Prototype for an object's message-handling function */
1161 
1162 RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1163 typedef int ( *MESSAGE_FUNCTION )( INOUT void *objectInfoPtr,
1164 								   IN_ENUM( MESSAGE ) \
1165 										const MESSAGE_TYPE message,
1166 								   void *messageDataPtr,
1167 								   const int messageValue );
1168 
1169 /* If the message-handler can unlock an object to allow other threads
1170    access, it has to be able to inform the kernel of this.  The following
1171    structure and macros allow this information to be passed back to the
1172    kernel via the message function's objectInfoPtr */
1173 
1174 typedef struct {
1175 	void *objectInfoPtr;					/* Original objectInfoPtr */
1176 	BOOLEAN isUnlocked;						/* Whether obj.is now unlocked */
1177 	} MESSAGE_FUNCTION_EXTINFO;
1178 
1179 #define initMessageExtInfo( messageExtInfo, objectInfo ) \
1180 		{ \
1181 		memset( messageExtInfo, 0, sizeof( MESSAGE_FUNCTION_EXTINFO ) ); \
1182 		( messageExtInfo )->objectInfoPtr = objectInfo; \
1183 		}
1184 #define setMessageObjectLocked( messageExtInfo ) \
1185 		( messageExtInfo )->isUnlocked = FALSE
1186 #define setMessageObjectUnlocked( messageExtInfo ) \
1187 		( messageExtInfo )->isUnlocked = TRUE
1188 #define isMessageObjectUnlocked( messageExtInfo ) \
1189 		( ( messageExtInfo )->isUnlocked )
1190 
1191 /* Object management functions.  A dummy object is one that exists but
1192    doesn't have the capabilities of the actual object, for example an
1193    encryption context that just maps to underlying crypto hardware.  This
1194    doesn't affect krnlCreateObject(), but is used by the object-type-
1195    specific routines that decorate the results of krnlCreateObject() with
1196    object-specific extras.
1197 
1198    Since krnlSendMessage() is the universal entry-point for the kernel API,
1199    it's heavily annotated to provide compile-time warnings of issues.  Since
1200    this is checked anyway at runtime, it's not clear whether this is really
1201    useful or just a gratuitous means of exercising the static analyser's
1202    capabilities... */
1203 
1204 #define CREATEOBJECT_FLAG_NONE		0x00	/* No create-object flags */
1205 #define CREATEOBJECT_FLAG_SECUREMALLOC \
1206 									0x01	/* Use krnlMemAlloc() to alloc.*/
1207 #define CREATEOBJECT_FLAG_DUMMY		0x02	/* Dummy obj.used as placeholder */
1208 #define CREATEOBJECT_FLAG_PERSISTENT 0x04	/* Obj.backed by key in device */
1209 #define CREATEOBJECT_FLAG_MAX		0x0F	/* Maximum possible flag value */
1210 
1211 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 9 ) ) \
1212 int krnlCreateObject( OUT_HANDLE_OPT int *objectHandle,
1213 					  OUT_BUFFER_ALLOC_OPT( objectDataSize ) void **objectDataPtr,
1214 					  IN_LENGTH_SHORT const int objectDataSize,
1215 					  IN_ENUM( OBJECT_TYPE ) const OBJECT_TYPE type,
1216 					  IN_ENUM( SUBTYPE ) const OBJECT_SUBTYPE subType,
1217 					  IN_FLAGS_Z( CREATEOBJECT ) const int createObjectFlags,
1218 					  IN_HANDLE_OPT const CRYPT_USER owner,
1219 					  IN_FLAGS_Z( ACTION_PERM ) const int actionFlags,
1220 					  IN MESSAGE_FUNCTION messageFunction );
1221 RETVAL \
1222 PARAMCHECK_MESSAGE( MESSAGE_DESTROY, PARAM_NULL, PARAM_IS( 0 ) ) \
1223 PARAMCHECK_MESSAGE( MESSAGE_INCREFCOUNT, PARAM_NULL, PARAM_IS( 0 ) ) \
1224 PARAMCHECK_MESSAGE( MESSAGE_DECREFCOUNT, PARAM_NULL, PARAM_IS( 0 ) ) \
1225 PARAMCHECK_MESSAGE( MESSAGE_GETDEPENDENT, OUT, IN_ENUM( OBJECT_TYPE ) ) \
1226 PARAMCHECK_MESSAGE( MESSAGE_SETDEPENDENT, IN, IN ) \
1227 PARAMCHECK_MESSAGE( MESSAGE_CLONE, PARAM_NULL, IN_HANDLE ) \
1228 PARAMCHECK_MESSAGE( MESSAGE_GETATTRIBUTE, OUT, IN_ATTRIBUTE ) \
1229 PARAMCHECK_MESSAGE( MESSAGE_GETATTRIBUTE_S, INOUT, IN_ATTRIBUTE ) \
1230 PARAMCHECK_MESSAGE( MESSAGE_SETATTRIBUTE, IN, IN_ATTRIBUTE ) \
1231 PARAMCHECK_MESSAGE( MESSAGE_SETATTRIBUTE_S, IN, IN_ATTRIBUTE ) \
1232 PARAMCHECK_MESSAGE( MESSAGE_DELETEATTRIBUTE, PARAM_NULL, IN_ATTRIBUTE ) \
1233 PARAMCHECK_MESSAGE( MESSAGE_COMPARE, IN, IN_ENUM( MESSAGE_COMPARE ) ) \
1234 PARAMCHECK_MESSAGE( MESSAGE_CHECK, PARAM_NULL, IN_ENUM( MESSAGE_CHECK ) ) \
1235 PARAMCHECK_MESSAGE( MESSAGE_SELFTEST, PARAM_NULL, PARAM_IS( 0 ) ) \
1236 PARAMCHECK_MESSAGE( MESSAGE_CHANGENOTIFY, PARAM_NULL, PARAM_IS( 0 ) ) \
1237 PARAMCHECK_MESSAGE( MESSAGE_CTX_ENCRYPT, INOUT, IN_LENGTH ) \
1238 PARAMCHECK_MESSAGE( MESSAGE_CTX_DECRYPT, INOUT, IN_LENGTH ) \
1239 PARAMCHECK_MESSAGE( MESSAGE_CTX_SIGN, IN, IN_LENGTH ) \
1240 PARAMCHECK_MESSAGE( MESSAGE_CTX_SIGCHECK, IN, IN_LENGTH ) \
1241 PARAMCHECK_MESSAGE( MESSAGE_CTX_HASH, IN, IN_LENGTH_Z ) \
1242 PARAMCHECK_MESSAGE( MESSAGE_CTX_GENKEY, PARAM_NULL, PARAM_IS( 0 ) ) \
1243 PARAMCHECK_MESSAGE( MESSAGE_CTX_GENIV, PARAM_NULL, PARAM_IS( 0 ) ) \
1244 PARAMCHECK_MESSAGE( MESSAGE_CRT_SIGN, PARAM_NULL, IN_HANDLE ) \
1245 PARAMCHECK_MESSAGE( MESSAGE_CRT_SIGCHECK, PARAM_NULL, IN_HANDLE_OPT ) \
1246 PARAMCHECK_MESSAGE( MESSAGE_CRT_EXPORT, INOUT, IN_ENUM( CRYPT_CERTFORMAT ) ) \
1247 PARAMCHECK_MESSAGE( MESSAGE_DEV_QUERYCAPABILITY, OUT, IN_ALGO ) \
1248 PARAMCHECK_MESSAGE( MESSAGE_DEV_EXPORT, INOUT, IN_ENUM( MECHANISM ) ) \
1249 PARAMCHECK_MESSAGE( MESSAGE_DEV_IMPORT, INOUT, IN_ENUM( MECHANISM ) ) \
1250 PARAMCHECK_MESSAGE( MESSAGE_DEV_SIGN, INOUT, IN_ENUM( MECHANISM ) ) \
1251 PARAMCHECK_MESSAGE( MESSAGE_DEV_SIGCHECK, INOUT, IN_ENUM( MECHANISM ) ) \
1252 PARAMCHECK_MESSAGE( MESSAGE_DEV_DERIVE, INOUT, IN_ENUM( MECHANISM ) ) \
1253 PARAMCHECK_MESSAGE( MESSAGE_DEV_KDF, INOUT, IN_ENUM( MECHANISM ) ) \
1254 PARAMCHECK_MESSAGE( MESSAGE_DEV_CREATEOBJECT, INOUT, IN_ENUM( OBJECT_TYPE ) ) \
1255 PARAMCHECK_MESSAGE( MESSAGE_DEV_CREATEOBJECT_INDIRECT, INOUT, IN_ENUM( OBJECT_TYPE ) ) \
1256 PARAMCHECK_MESSAGE( MESSAGE_ENV_PUSHDATA, INOUT, PARAM_IS( 0 ) ) \
1257 PARAMCHECK_MESSAGE( MESSAGE_ENV_POPDATA, INOUT, PARAM_IS( 0 ) ) \
1258 PARAMCHECK_MESSAGE( MESSAGE_KEY_GETKEY, INOUT, IN_ENUM( KEYMGMT_ITEM ) ) \
1259 PARAMCHECK_MESSAGE( MESSAGE_KEY_SETKEY, INOUT, IN_ENUM( KEYMGMT_ITEM ) ) \
1260 PARAMCHECK_MESSAGE( MESSAGE_KEY_DELETEKEY, INOUT, IN_ENUM( KEYMGMT_ITEM ) ) \
1261 PARAMCHECK_MESSAGE( MESSAGE_KEY_GETFIRSTCERT, INOUT, IN_ENUM( KEYMGMT_ITEM ) ) \
1262 PARAMCHECK_MESSAGE( MESSAGE_KEY_GETNEXTCERT, INOUT, IN_ENUM( KEYMGMT_ITEM ) ) \
1263 PARAMCHECK_MESSAGE( MESSAGE_KEY_CERTMGMT, INOUT, IN_ENUM( CRYPT_CERTACTION ) ) \
1264 PARAMCHECK_MESSAGE( MESSAGE_USER_USERMGMT, INOUT, IN_ENUM( MESSAGE_USERMGMT ) ) \
1265 PARAMCHECK_MESSAGE( MESSAGE_USER_TRUSTMGMT, IN, IN_ENUM( MESSAGE_TRUSTMGMT ) ) \
1266 					/* Actually INOUT for MESSAGE_TRUSTMGMT_GETISSUER, but too \
1267 					   complex to annotate */ \
1268 int krnlSendMessage( IN_HANDLE const int objectHandle,
1269 					 IN_MESSAGE const MESSAGE_TYPE message,
1270 					 void *messageDataPtr, const int messageValue );
1271 
1272 /* Since some messages contain no data but act only as notifiers, we define
1273    the following macro to make using them less messy */
1274 
1275 #define krnlSendNotifier( handle, message ) \
1276 		krnlSendMessage( handle, message, NULL, 0 )
1277 
1278 /* In some rare cases we have to access an object directly without sending
1279    it a message.  This happens either with certs where we're already
1280    processing a message for one cert and need to access internal data in
1281    another cert, when we're working with a crypto device tied to a context
1282    where we need access to both context and device internals at the same
1283    time, or when we're updating config data in a user object.  This type of
1284    access is handled by the following function, which also explicitly
1285    disallows any access types apart from the three described here */
1286 
1287 CHECK_RETVAL STDC_NONNULL_ARG( ( 3 ) ) \
1288 int krnlAcquireObject( IN_HANDLE const int objectHandle,
1289 					   IN_ENUM( OBJECT_TYPE ) const OBJECT_TYPE type,
1290 					   OUT_PTR_COND void **objectPtr,
1291 					   IN_ERROR const int errorCode );
1292 RETVAL \
1293 int krnlReleaseObject( IN_HANDLE const int objectHandle );
1294 
1295 /* In even rarer cases, we have to allow a second thread access to an object
1296    when another thread has it locked, providing a (somewhat crude) mechanism
1297    for making kernel calls interruptible and resumable.  This only occurs in
1298    two cases, for the system object when a background polling thread is
1299    adding entropy to the system device and for the user object when we're
1300    saving configuration data to persistent storage (we temporarily unlock it
1301    to allow other threads access, since the act of writing the marshalled
1302    data to storage doesn't require the user object) */
1303 
1304 RETVAL STDC_NONNULL_ARG( ( 2 ) ) \
1305 int krnlSuspendObject( IN_HANDLE const int objectHandle,
1306 					   OUT_INT_Z int *refCount );
1307 CHECK_RETVAL \
1308 int krnlResumeObject( IN_HANDLE const int objectHandle,
1309 					  IN_INT_Z const int refCount );
1310 
1311 /* When the kernel is closing down, any cryptlib-internal threads should
1312    exit as quickly as possible.  For threads coming in from the outside this
1313    happens automatically because any message it tries to send fails, but for
1314    internal worker threads (for example the async driver-binding thread or
1315    randomness polling threads) that don't perform many kernel calls, the
1316    thread has to periodically check whether the kernel is still active.  The
1317    following function is used to indicate whether the kernel is shutting
1318    down */
1319 
1320 CHECK_RETVAL_BOOL \
1321 BOOLEAN krnlIsExiting( void );
1322 
1323 /* Semaphores and mutexes */
1324 
1325 typedef enum {
1326 	SEMAPHORE_NONE,					/* No semaphore */
1327 	SEMAPHORE_DRIVERBIND,			/* Async driver bind */
1328 	SEMAPHORE_LAST					/* Last possible semaphore */
1329 	} SEMAPHORE_TYPE;
1330 
1331 typedef enum {
1332 	MUTEX_NONE,						/* No mutex */
1333 	MUTEX_SCOREBOARD,				/* Session scoreboard */
1334 	MUTEX_SOCKETPOOL,				/* Network socket pool */
1335 	MUTEX_RANDOM,					/* Randomness subsystem */
1336 	MUTEX_LAST						/* Last possible mutex */
1337 	} MUTEX_TYPE;
1338 
1339 /* Execute a function in a background thread.  This takes a pointer to the
1340    function to execute in the background thread, a block of memory for
1341    thread state storage, a set of parameters to pass to the thread function,
1342    and an optional semaphore ID to set once the thread is started.  A
1343    function is run via a background thread as follows:
1344 
1345 	void threadFunction( const THREAD_PARAMS *threadParams )
1346 		{
1347 		}
1348 
1349 	krnlDispatchThread( threadFunction, &threadState, ptrParam, intParam,
1350 						SEMAPHORE_ID );
1351 
1352    Note that the thread parameters must be held in static storage because
1353    the caller's stack frame may have long since disappeared before the
1354    thread gets to access them */
1355 
1356 struct TF;
1357 
1358 typedef void ( *THREAD_FUNCTION )( const struct TF *threadParams );
1359 
1360 typedef BYTE THREAD_STATE[ 48 ];
1361 
1362 typedef struct TF {
1363 	void *ptrParam;					/* Pointer parameter */
1364 	int intParam;					/* Integer parameter */
1365 	} THREAD_PARAMS;
1366 
1367 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1368 int krnlDispatchThread( THREAD_FUNCTION threadFunction,
1369 						THREAD_STATE threadState, void *ptrParam,
1370 						const int intParam, const SEMAPHORE_TYPE semaphore );
1371 
1372 /* Wait on a semaphore, enter and exit a mutex */
1373 
1374 CHECK_RETVAL_BOOL \
1375 BOOLEAN krnlWaitSemaphore( IN_ENUM( SEMAPHORE ) const SEMAPHORE_TYPE semaphore );
1376 CHECK_RETVAL \
1377 int krnlEnterMutex( IN_ENUM( MUTEX ) const MUTEX_TYPE mutex );
1378 void krnlExitMutex( IN_ENUM( MUTEX ) const MUTEX_TYPE mutex );
1379 
1380 /* Secure memory handling functions */
1381 
1382 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1383 int krnlMemalloc( OUT_BUFFER_ALLOC_OPT( size ) void **pointer,
1384 				  IN_LENGTH int size );
1385 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1386 int krnlMemfree( INOUT_PTR void **pointer );
1387 
1388 #ifdef NEED_ENUMFIX
1389   #undef OBJECT_TYPE_LAST
1390   #undef MESSAGE_COMPARE_LAST
1391   #undef MESSAGE_CHECK_LAST
1392   #undef MESSAGE_CHANGENOTIFY_LAST
1393   #undef MECHANISM_LAST
1394   #undef KEYMGMT_ITEM_LAST
1395   #undef SEMAPHORE_LAST
1396   #undef MUTEX_LAST
1397 #endif /* NEED_ENUMFIX */
1398 #endif /* _CRYPTKRN_DEFINED */
1399