cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
cryptkrn.h
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * cryptlib Kernel Interface Header File *
4 * Copyright Peter Gutmann 1992-2011 *
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  transaparent 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 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 /* The data type used to store subtype values */
218 
219 #ifdef SYSTEM_16BIT
220  typedef long OBJECT_SUBTYPE;
221 #else
222  typedef int OBJECT_SUBTYPE;
223 #endif /* 16- vs.32-bit systems */
224 
225 /* Message flags. Normally messages can only be sent to external objects,
226  however we can also explicitly send them to internal objects which means
227  that we use the internal rather than external access ACL. This can only
228  be done from inside cryptlib, for example when an object sends a message
229  to a subordinate object */
230 
231 #define MESSAGE_FLAG_INTERNAL 0x100
232 #define MKINTERNAL( message ) ( message | MESSAGE_FLAG_INTERNAL )
233 
234 /* A mask to extract the basic message type */
235 
236 #define MESSAGE_MASK 0xFF
237 
238 /* The message types that can be sent to an object via krnlSendMessage().
239  By default messages can only be sent to externally visible objects, there
240  are also internal versions that can be sent to all objects. The object
241  messages have the following arguments:
242 
243  Type DataPtr Value
244  --------------------------- ------- -----
245  MESSAGE_DESTROY NULL 0
246  MESSAGE_INC/DECREFCOUNT NULL 0
247  MESSAGE_GETDEPENDENT &objectHandle objectType
248  MESSAGE_SETDEPENDENT &objectHandle incRefCount
249  MESSAGE_CLONE NULL cloneContext
250  MESSAGE_GET/SETATTRIBUTE &value attributeType
251  MESSAGE_DELETEATTRIBUTE NULL attributeType
252  MESSAGE_COMPARE &value compareType
253  MESSAGE_CHECK NULL requestedUse
254  MESSAGE_SELFTEST NULL 0
255 
256  MESSAGE_CHANGENOTIFY &value attributeType
257 
258  MESSAGE_CTX_ENCRYPT/DECRYPT/SIGN/-
259  SIGCHECK/HASH &value valueLength
260  MESSAGE_CTX_GENKEY NULL 0
261  MESSAGE_CTX_GENIV NULL 0
262 
263  MESSAGE_CRT_SIGN, NULL sigKey
264  MESSAGE_CRT_SIGCHECK, NULL verifyObject
265  MESSAGE_CRT_EXPORT, &value formatType
266 
267  MESSAGE_DEV_QUERYCAPABILITY &queryInfo algorithm
268  MESSAGE_DEV_EXPORT/IMPORT/SIGN/-
269  SIGCHECK/DERIVE/KDF &mechanismInfo mechanismType
270  MESSAGE_DEV_CREATEOBJECT &createInfo objectType
271  MESSAGE_DEV_CREATEOBJECT_INDIRECT &createInfo objectType
272 
273  MESSAGE_ENV_PUSH/POPDATA &value 0
274 
275  MESSAGE_KEY_GET/SET/DELETEKEY &keymgmtInfo itemType
276  MESSAGE_KEY_GETFIRST/NEXTCERT &keymgmtInfo itemType
277  MESSAGE_KEY_CERTMGMT &certMgmtInfo action
278 
279  MESSAGE_USER_USERMGMT &value action
280  MESSAGE_USER_TRUSTMGMT &value action */
281 
282 typedef enum {
283  MESSAGE_NONE, /* No message */
284 
285  /* Control messages to externally visible objects (the internal versions
286  are defined further down). These messages are handled directly by
287  the kernel and don't affect the object itself except for
288  MESSAGE_DESTROY which is generated by the kernel in response to the
289  final MESSAGE_DECREFCOUNT sent to an object. These are forwarded out
290  to the object to get it to clean up its state before the kernel
291  destroys it */
292  MESSAGE_DESTROY, /* Destroy the object */
293  MESSAGE_INCREFCOUNT, /* Increment object ref.count */
294  MESSAGE_DECREFCOUNT, /* Decrement object ref.count */
295  MESSAGE_GETDEPENDENT, /* Get dependent object */
296  MESSAGE_SETDEPENDENT, /* Set dependent object (e.g.ctx->dev) */
297  MESSAGE_CLONE, /* Clone the object */
298 
299  /* Attribute messages. The reason for the numeric vs.non-numeric
300  attribute messages is that for improved error checking the data types
301  that these work with are explicitly specified by the user based on
302  which function they call to get/set them rather than being implicitly
303  specified by the attribute ID. Because of the explicit typing, the
304  handlers have to be able to check to make sure that the actual type
305  matches what the user specified, so we need one message type for
306  numeric attributes and one for string attributes */
307  MESSAGE_GETATTRIBUTE, /* Get numeric object attribute */
308  MESSAGE_GETATTRIBUTE_S, /* Get string object attribute */
309  MESSAGE_SETATTRIBUTE, /* Set numeric object attribute */
310  MESSAGE_SETATTRIBUTE_S, /* Set string object attribute */
311  MESSAGE_DELETEATTRIBUTE, /* Delete object attribute */
312 
313  /* General messages. The check message is used for informational
314  purposes only so that problems (e.g. an attempt to use a public key
315  where a private key is required) can be reported to the user
316  immediately as a function parameter error rather than appearing much
317  later as an object use permission error when the kernel blocks the
318  access. Final access checking is always still done at the kernel
319  level to avoid the confused deputy problem */
320  MESSAGE_COMPARE, /* Compare objs. or obj.properties */
321  MESSAGE_CHECK, /* Check object info */
322  MESSAGE_SELFTEST, /* Perform a self-test */
323 
324  /* Messages sent from the kernel to object message handlers. These never
325  originate from outside the kernel but are generated in response to
326  other messages to notify an object of a change in its state */
327  MESSAGE_CHANGENOTIFY, /* Notification of obj.status chge.*/
328 
329  /* Object-type-specific messages */
330  MESSAGE_CTX_ENCRYPT, /* Context: Action = encrypt */
331  MESSAGE_CTX_DECRYPT, /* Context: Action = decrypt */
332  MESSAGE_CTX_SIGN, /* Context: Action = sign */
333  MESSAGE_CTX_SIGCHECK, /* Context: Action = sigcheck */
334  MESSAGE_CTX_HASH, /* Context: Action = hash */
335  MESSAGE_CTX_GENKEY, /* Context: Generate a key */
336  MESSAGE_CTX_GENIV, /* Context: Generate an IV */
337  MESSAGE_CRT_SIGN, /* Cert: Action = sign cert */
338  MESSAGE_CRT_SIGCHECK, /* Cert: Action = check/verify cert */
339  MESSAGE_CRT_EXPORT, /* Cert: Export encoded cert data */
340  MESSAGE_DEV_QUERYCAPABILITY,/* Device: Query capability */
341  MESSAGE_DEV_EXPORT, /* Device: Action = export key */
342  MESSAGE_DEV_IMPORT, /* Device: Action = import key */
343  MESSAGE_DEV_SIGN, /* Device: Action = sign */
344  MESSAGE_DEV_SIGCHECK, /* Device: Action = sig.check */
345  MESSAGE_DEV_DERIVE, /* Device: Action = derive key */
346  MESSAGE_DEV_KDF, /* Device: Action = KDF */
347  MESSAGE_DEV_CREATEOBJECT, /* Device: Create object */
348  MESSAGE_DEV_CREATEOBJECT_INDIRECT, /* Device: Create obj.from data */
349  MESSAGE_ENV_PUSHDATA, /* Envelope: Push data */
350  MESSAGE_ENV_POPDATA, /* Envelope: Pop data */
351  MESSAGE_KEY_GETKEY, /* Keyset: Instantiate ctx/cert */
352  MESSAGE_KEY_SETKEY, /* Keyset: Add ctx/cert */
353  MESSAGE_KEY_DELETEKEY, /* Keyset: Delete key/cert */
354  MESSAGE_KEY_GETFIRSTCERT, /* Keyset: Get first cert in sequence */
355  MESSAGE_KEY_GETNEXTCERT, /* Keyset: Get next cert in sequence */
356  MESSAGE_KEY_CERTMGMT, /* Keyset: Cert management */
357  MESSAGE_USER_USERMGMT, /* User: User management */
358  MESSAGE_USER_TRUSTMGMT, /* User: Trust management */
359  MESSAGE_LAST, /* Last valid message type */
360 
361  /* Internal-object versions of the above messages */
368 
374 
378 
380 
411  } MESSAGE_TYPE;
412 
413 /* The properties that MESSAGE_COMPARE can compare */
414 
415 typedef enum {
416  MESSAGE_COMPARE_NONE, /* No comparison */
417  MESSAGE_COMPARE_HASH, /* Compare hash/MAC value */
418  MESSAGE_COMPARE_ICV, /* Compare ICV value */
419  MESSAGE_COMPARE_KEYID, /* Compare key IDs */
420  MESSAGE_COMPARE_KEYID_PGP, /* Compare PGP key IDs */
421  MESSAGE_COMPARE_KEYID_OPENPGP, /* Compare OpenPGP key IDs */
422  MESSAGE_COMPARE_SUBJECT, /* Compare subject */
424  MESSAGE_COMPARE_FINGERPRINT_SHA1,/* Compare cert.fingerprint */
425  MESSAGE_COMPARE_FINGERPRINT_SHA2,/* Compare fingerprint, SHA2 */
426  MESSAGE_COMPARE_FINGERPRINT_SHAng,/* Compare fingerprint, SHAng */
427  MESSAGE_COMPARE_CERTOBJ, /* Compare cert objects */
428  MESSAGE_COMPARE_LAST /* Last possible compare type */
430 
431 /* The checks that MESSAGE_CHECK performs. There are a number of variations
432  of the checking we can perform, either the object is initialised in a
433  state to perform the required action (meaning that it has to be in the
434  high state), the object is ready to be initialised for the required
435  action, for example an encryption context about to have a key loaded for
436  encryption (meaning that it has to be in the low state), or the check is
437  on a passive container object that constrains another object (for example
438  a cert being attached to a context) for which the state isn't important
439  in this instance. Usually we check to make sure that the cert is in the
440  high state, but when a cert is being created/imported it may not be in
441  the high state yet at the time the check is being carried out */
442 
443 typedef enum {
444  /* Standard checks, for which the object must be initialised in a state
445  to perform this operation */
446  MESSAGE_CHECK_NONE, /* No check */
447  MESSAGE_CHECK_PKC, /* Public or private key context */
448  MESSAGE_CHECK_PKC_PRIVATE, /* Private key context */
449  MESSAGE_CHECK_PKC_ENCRYPT, /* Public encryption context */
450  MESSAGE_CHECK_PKC_DECRYPT, /* Private decryption context */
451  MESSAGE_CHECK_PKC_SIGCHECK, /* Public signature check context */
452  MESSAGE_CHECK_PKC_SIGN, /* Private signature context */
453  MESSAGE_CHECK_PKC_KA_EXPORT, /* Key agreement - export context */
454  MESSAGE_CHECK_PKC_KA_IMPORT, /* Key agreement - import context */
455  MESSAGE_CHECK_CRYPT, /* Conventional encryption context */
456  MESSAGE_CHECK_HASH, /* Hash context */
457  MESSAGE_CHECK_MAC, /* MAC context */
458 
459  /* Checks that an object is ready to be initialised to perform this
460  operation */
461  MESSAGE_CHECK_CRYPT_READY, /* Ready for conv.encr. init */
462  MESSAGE_CHECK_MAC_READY, /* Ready for MAC init */
463  MESSAGE_CHECK_KEYGEN_READY, /* Ready for key generation */
464 
465  /* Checks on purely passive container objects that constrain action
466  objects */
467  MESSAGE_CHECK_PKC_ENCRYPT_AVAIL,/* Encryption available */
468  MESSAGE_CHECK_PKC_DECRYPT_AVAIL,/* Decryption available */
469  MESSAGE_CHECK_PKC_SIGCHECK_AVAIL, /* Signature check available */
470  MESSAGE_CHECK_PKC_SIGN_AVAIL, /* Signature available */
471  MESSAGE_CHECK_PKC_KA_EXPORT_AVAIL, /* Key agreement - export available */
472  MESSAGE_CHECK_PKC_KA_IMPORT_AVAIL, /* Key agreement - import available */
473 
474  /* Misc.checks for meta-capabilities not directly connected with object
475  actions. The certificate check is used to verify that a certificate
476  is generally valid (for example not expired) without having to
477  performing a full signature verification up to a trusted root, this
478  is used to verify certificates passed in as parameters (for example
479  server certificates) to ensure that the client doesn't get invalid
480  data back when it tries to connect to the server. The CA check
481  applies to both PKC contexts and certificates, when the message is
482  forwarded to a dependent CA cert it's forwarded as the internal
483  MESSAGE_CHECK_CACERT check type, since MESSAGE_CHECK_CA requires both
484  a PKC context and a certificate */
485  MESSAGE_CHECK_CERT, /* Generic certificate */
486  MESSAGE_CHECK_CERTxx, /* Internal value used for cert.checks */
487  MESSAGE_CHECK_CA, /* Cert signing capability */
488  MESSAGE_CHECK_CACERT, /* Internal value used for CA checks */
489  MESSAGE_CHECK_LAST /* Last possible check type */
491 
492 /* The notifications that a MESSAGE_CHANGENOTIFY can deliver */
493 
494 typedef enum {
495  MESSAGE_CHANGENOTIFY_NONE, /* No notification */
496  MESSAGE_CHANGENOTIFY_STATE, /* Object should save/rest.int.state */
497  MESSAGE_CHANGENOTIFY_OBJHANDLE, /* Object cloned, handle changed */
498  MESSAGE_CHANGENOTIFY_OWNERHANDLE, /* Object cloned, owner handle changed */
499  MESSAGE_CHANGENOTIFY_LAST /* Last possible notification type */
501 
502 /* The operations that a MESSAGE_USER_USERMGMT can perform */
503 
504 typedef enum {
505  MESSAGE_USERMGMT_NONE, /* No operation */
506  MESSAGE_USERMGMT_ZEROISE, /* Zeroise users */
507  MESSAGE_USERMGMT_LAST /* Last possible operation type */
509 
510 /* The operations that a MESSAGE_USER_TRUSTMGMT can perform */
511 
512 typedef enum {
513  MESSAGE_TRUSTMGMT_NONE, /* No operation */
514  MESSAGE_TRUSTMGMT_ADD, /* Add trusted cert */
515  MESSAGE_TRUSTMGMT_DELETE, /* Delete trusted cert */
516  MESSAGE_TRUSTMGMT_CHECK, /* Check trust status of cert */
517  MESSAGE_TRUSTMGMT_GETISSUER, /* Get trusted issuer cert */
518  MESSAGE_TRUSTMGMT_LAST /* Last possible operation type */
520 
521 /* Options for the MESSAGE_SETDEPENDENT message */
522 
523 typedef enum {
524  SETDEP_OPTION_NONE, /* No option */
525  SETDEP_OPTION_NOINCREF, /* Don't inc.dep.objs reference count */
526  SETDEP_OPTION_INCREF, /* Increment dep.objs reference count */
527  SETDEP_OPTION_LAST /* Last possible option type */
529 
530 /* When getting/setting string data that consists of (value, length) pairs,
531  we pass a pointer to a value-and-length structure rather than a pointer
532  to the data itself */
533 
534 typedef struct {
535  BUFFER_FIXED( length ) \
536  void *data; /* Data */
537  int length; /* Length */
538  } MESSAGE_DATA;
539 
540 #define setMessageData( msgDataPtr, dataPtr, dataLength ) \
541  { \
542  ( msgDataPtr )->data = ( dataPtr ); \
543  ( msgDataPtr )->length = ( dataLength ); \
544  }
545 
546 /* When passing constant data to krnlSendMessage() we get compiler warnings
547  because the function is prototyped as taking a 'void *'. The following
548  symbolic value for use in casts corrects the parameter mismatch */
549 
550 typedef void *MESSAGE_CAST;
551 
552 /* Some messages communicate standard data values that are used again and
553  again, so we predefine values for these that can be used globally */
554 
555 #define MESSAGE_VALUE_TRUE ( ( MESSAGE_CAST ) &messageValueTrue )
556 #define MESSAGE_VALUE_FALSE ( ( MESSAGE_CAST ) &messageValueFalse )
557 #define MESSAGE_VALUE_OK ( ( MESSAGE_CAST ) &messageValueCryptOK )
558 #define MESSAGE_VALUE_ERROR ( ( MESSAGE_CAST ) &messageValueCryptError )
559 #define MESSAGE_VALUE_UNUSED ( ( MESSAGE_CAST ) &messageValueCryptUnused )
560 #define MESSAGE_VALUE_DEFAULT ( ( MESSAGE_CAST ) &messageValueCryptUseDefault )
561 #define MESSAGE_VALUE_CURSORFIRST ( ( MESSAGE_CAST ) &messageValueCursorFirst )
562 #define MESSAGE_VALUE_CURSORNEXT ( ( MESSAGE_CAST ) &messageValueCursorNext )
563 #define MESSAGE_VALUE_CURSORPREVIOUS ( ( MESSAGE_CAST ) &messageValueCursorPrevious )
564 #define MESSAGE_VALUE_CURSORLAST ( ( MESSAGE_CAST ) &messageValueCursorLast )
565 
566 extern const int messageValueTrue, messageValueFalse;
571 
572 /* Check for membership within an attribute class */
573 
574 #define isAttribute( attribute ) \
575  ( ( attribute ) > CRYPT_ATTRIBUTE_NONE && \
576  ( attribute ) < CRYPT_ATTRIBUTE_LAST )
577 #define isInternalAttribute( attribute ) \
578  ( ( attribute ) > CRYPT_IATTRIBUTE_FIRST && \
579  ( attribute ) < CRYPT_IATTRIBUTE_LAST )
580 
581 /* Check whether a message is in a given message class, used in object
582  message handlers */
583 
584 #define isAttributeMessage( message ) \
585  ( ( message ) >= MESSAGE_GETATTRIBUTE && \
586  ( message ) <= MESSAGE_DELETEATTRIBUTE )
587 #define isActionMessage( message ) \
588  ( ( message ) >= MESSAGE_CTX_ENCRYPT && \
589  ( message ) <= MESSAGE_CTX_HASH )
590 #define isMechanismActionMessage( message ) \
591  ( ( message ) >= MESSAGE_DEV_EXPORT && \
592  ( message ) <= MESSAGE_DEV_KDF )
593 
594 /* The following handles correspond to built-in fixed object types that are
595  available throughout the architecture. Currently there are two objects,
596  an internal system object that encapsulates the built-in RNG and the
597  built-in mechanism types (if this ever becomes a bottleneck the two can be
598  separated into different objects) and a default user object which is used
599  when there are no explicit user objects being employed */
600 
601 #define SYSTEM_OBJECT_HANDLE 0 /* Internal system object */
602 #define DEFAULTUSER_OBJECT_HANDLE 1 /* Default user object */
603 
604 #define NO_SYSTEM_OBJECTS 2 /* Total number of system objects */
605 
606 /* We limit the maximum number of objects to a sensible value to prevent
607  deliberate/accidental DoS attacks. The following represents about 32MB
608  of object data, which should be a good indication that there are more
609  objects present than there should be */
610 
611 #define MAX_OBJECTS 16384
612 
613 /****************************************************************************
614 * *
615 * Action Message Types *
616 * *
617 ****************************************************************************/
618 
619 /* Action messages come in two types, direct action messages and mechanism-
620  action messages. Action messages apply directly to action objects (for
621  example transform a block of data) while mechanism-action messages apply
622  to device objects and involve extra formatting above and beyond the
623  direct action (for example perform PKCS #1 padding and then transform a
624  block of data).
625 
626  Each object that processes direct action messages can can have a range of
627  permission settings that control how action messages sent to it are
628  handled. The most common case is that the action isn't available for
629  this object, ACTION_PERM_NOTAVAIL. This is an all-zero permission, so
630  the default is deny-all unless the action is explicitly permitted. The
631  other permissions are ACTION_PERM_NONE, which means that the action is in
632  theory available but has been turned off, ACTION_PERM_NONE_EXTERNAL,
633  which means that the action is only valid if the message is coming from
634  inside cryptlib, and ACTION_PERM_ALL, which means that the action is
635  available for anyone. In order to set all permissions to a certain value
636  (e.g. NONE_EXTERNAL), we define overall values xxx_ALL that (in
637  combination with the kernel-enforced ratchet) can be used to set all
638  settings to (at most) the given value.
639 
640  The order of the action bits is:
641 
642  hash sign encr
643  | | |
644  xx xx xx xx xx xx
645  | | |
646  kgen sigch decr
647 
648  x. .x|x. .x|x. .x Hex digits
649 
650  Common settings are 0xCFF (new PKC, all operations), 0x0F (key-loaded
651  conv., all operations), and 0xAA (key-loaded PKC, internal-only
652  operations).
653 
654  The kernel enforces a ratchet for these setting that only allows them to
655  be set to a more restrictive value than their existing one. If a setting
656  starts out as not available on object creation, it can never be enabled.
657  If a setting starts as 'none-external', it can only be set to a straight
658  'none', but never to 'all' */
659 
660 #define ACTION_PERM_NOTAVAIL 0x00
661 #define ACTION_PERM_NONE 0x01
662 #define ACTION_PERM_NONE_EXTERNAL 0x02
663 #define ACTION_PERM_ALL 0x03
664 
665 #define ACTION_PERM_NONE_ALL 0x000
666 #define ACTION_PERM_NONE_EXTERNAL_ALL 0xAAA
667 #define ACTION_PERM_ALL_MAX 0xFFF
668 
669 #define ACTION_PERM_BASE MESSAGE_CTX_ENCRYPT
670 #define ACTION_PERM_MASK 0x03
671 #define ACTION_PERM_BITS 2
672 #define ACTION_PERM_COUNT ( MESSAGE_CTX_GENKEY - \
673  MESSAGE_CTX_ENCRYPT + 1 )
674 #define ACTION_PERM_LAST \
675  ( 1 << ( ( ( ACTION_PERM_COUNT ) * ACTION_PERM_BITS ) + 1 ) )
676 #define ACTION_PERM_SHIFT( action ) \
677  ( ( ( action ) - ACTION_PERM_BASE ) * ACTION_PERM_BITS )
678 #define MK_ACTION_PERM( action, perm ) \
679  ( ( perm ) << ACTION_PERM_SHIFT( action ) )
680 #define MK_ACTION_PERM_NONE_EXTERNAL( action ) \
681  ( ( action ) & ACTION_PERM_NONE_EXTERNAL_ALL )
682 
683 /* Symbolic defines to allow the action flags to be range-checked alongside
684  all of the other flag types */
685 
686 #define ACTION_PERM_FLAG_NONE 0x000
687 #define ACTION_PERM_FLAG_MAX 0xFFF
688 
689 /* The mechanism types. The distinction between the PKCS #1 and raw PKCS #1
690  mechanisms is somewhat artificial in that they do the same thing, however
691  it's easier for the kernel to perform security checks on parameters if
692  the two are distinct */
693 
694 typedef enum {
695  MECHANISM_NONE, /* No mechanism */
696  MECHANISM_ENC_PKCS1, /* PKCS #1 en/decrypt */
697  MECHANISM_ENC_PKCS1_PGP, /* PKCS #1 using PGP formatting */
698  MECHANISM_ENC_PKCS1_RAW, /* PKCS #1 returning uninterpreted data */
699  MECHANISM_ENC_OAEP, /* OAEP en/decrypt */
700  MECHANISM_ENC_CMS, /* CMS key wrap */
701  MECHANISM_SIG_PKCS1, /* PKCS #1 sign */
702  MECHANISM_SIG_SSL, /* SSL sign with dual hashes */
703  MECHANISM_DERIVE_PKCS5, /* PKCS #5 derive */
704  MECHANISM_DERIVE_PKCS12, /* PKCS #12 derive */
705  MECHANISM_DERIVE_SSL, /* SSL derive */
706  MECHANISM_DERIVE_TLS, /* TLS derive */
707  MECHANISM_DERIVE_TLS12, /* TLS 1.2 derive */
708  MECHANISM_DERIVE_CMP, /* CMP/Entrust derive */
709  MECHANISM_DERIVE_PGP, /* OpenPGP S2K derive */
710  MECHANISM_PRIVATEKEYWRAP, /* Private key wrap */
711  MECHANISM_PRIVATEKEYWRAP_PKCS8, /* PKCS #8 private key wrap */
712  MECHANISM_PRIVATEKEYWRAP_PGP2, /* PGP 2.x private key wrap */
713  MECHANISM_PRIVATEKEYWRAP_OPENPGP_OLD,/* Legacy OpenPGP private key wrap */
714  MECHANISM_PRIVATEKEYWRAP_OPENPGP,/* OpenPGP private key wrap */
715  MECHANISM_LAST /* Last valid mechanism type */
716  } MECHANISM_TYPE;
717 
718 /* A structure to hold information needed by the key export/import mechanism.
719  The key can be passed as raw key data or as a context if tied to hardware
720  that doesn't allow keying material outside the hardware's security
721  perimeter:
722 
723  PKCS #1, wrappedData = wrapped key
724  PKCS #1 PGP keyData = -
725  keyContext = context containing key
726  wrapContext = wrap/unwrap PKC context
727  auxContext = CRYPT_UNUSED
728  auxInfo = CRYPT_UNUSED
729  PKCS #1 raw wrappedData = wrapped raw data
730  keyData = raw data
731  keyContext = CRYPT_UNUSED
732  wrapContext = wrap/unwrap PKC context
733  auxContext = CRYPT_UNUSED
734  auxInfo = CRYPT_UNUSED
735  OAEP wrappedData = wrapped key
736  keyData = -
737  keyContext = context containing key
738  wrapContext = wrap/unwrap PKC context
739  auxContext = CRYPT_UNUSED
740  auxInfo = MGF1 algorithm
741  CMS wrappedData = wrapped key
742  keyData = -
743  keyContext = context containing key
744  wrapContext = wrap/unwrap conventional context
745  auxContext = CRYPT_UNUSED
746  auxInfo = CRYPT_UNUSED
747  Private wrappedData = padded encrypted private key components
748  key wrap keyData = -
749  keyContext = context containing private key
750  wrapContext = wrap/unwrap conventional context
751  auxContext = CRYPT_UNUSED
752  auxInfo = CRYPT_UNUSED */
753 
754 typedef struct {
755  BUFFER_OPT_FIXED( wrappedDataLength ) \
756  void *wrappedData; /* Wrapped key */
759  void *keyData; /* Raw key */
761  CRYPT_HANDLE keyContext; /* Context containing raw key */
762  CRYPT_HANDLE wrapContext; /* Wrap/unwrap context */
763  CRYPT_HANDLE auxContext; /* Auxiliary context */
764  int auxInfo; /* Auxiliary info */
766 
767 /* A structure to hold information needed by the sign/sig check mechanism:
768 
769  PKCS #1 signature = signature
770  hashContext = hash to sign
771  signContext = signing key
772 
773  SSL signature = signature
774  hashContext, hashContext2 = dual hashes to sign
775  signContext = signing key */
776 
777 typedef struct {
779  void *signature; /* Signature */
781  CRYPT_CONTEXT hashContext; /* Hash context */
782  CRYPT_CONTEXT hashContext2; /* Secondary hash context */
783  CRYPT_HANDLE signContext; /* Signing context */
785 
786 /* A structure to hold information needed by the key derivation mechanism.
787  This differs from the KDF mechanism that follows in that the "Derive"
788  form is used with an iteration count for password-based key derivation
789  while the "KDF" form is used without an iteration count for straight key
790  derivation from a master secret. An exception to this is the SSL/TLS
791  derivation, which uses the resulting data in so many ways that it's not
792  possible to perform a generic context -> context transformation but
793  requires a generalisation in which the raw output data is available:
794 
795  PKCS #5, dataOut = key data
796  CMP, PGP dataIn = password
797  hashAlgo = hash algorithm
798  salt = salt
799  iterations = iteration count
800  SSL/TLS/ dataOut = key data/master secret
801  TLS 1.2 dataIn = master secret/premaster secret
802  hashAlgo = CRYPT_USE_DEFAULT
803  salt = client || server random/server || client random
804  iterations = 1 */
805 
806 typedef struct {
807  BUFFER_OPT_FIXED( dataOutLength ) \
808  void *dataOut; /* Output keying information */
810  BUFFER_FIXED( dataInLength ) \
811  const void *dataIn; /* Input keying information */
813  CRYPT_ALGO_TYPE hashAlgo; /* Hash algorithm */
814  int hashParam; /* Optional algorithm parameters */
816  const void *salt; /* Salt/randomiser */
818  int iterations; /* Iterations of derivation function */
820 
821 /* A structure to hold information needed by the KDF mechanism:
822 
823  CMS AuthEnc keyContext = encryption/MAC context
824  masterKeyContext = context containing master secret
825  hashAlgo = hash algorithm
826  salt = salt */
827 
828 typedef struct {
829  CRYPT_HANDLE keyContext; /* Context containing derived key */
830  CRYPT_HANDLE masterKeyContext; /* Context containing master key */
831  CRYPT_ALGO_TYPE hashAlgo; /* Hash algorithm */
832  int hashParam; /* Optional algorithm parameters */
834  const void *salt; /* Salt/randomiser */
837 
838 /* Macros to make it easier to work with the mechanism info types. The
839  shortened name forms in the macro args are necessary to avoid clashes with
840  the struct members. The long lines are necessary because older Borland
841  compilers can't handle line breaks at this point in a macro definition */
842 
843 #define clearMechanismInfo( mechanismInfo ) \
844  memset( mechanismInfo, 0, sizeof( *mechanismInfo ) )
845 
846 #define setMechanismWrapInfo( mechanismInfo, wrapped, wrappedLen, key, keyLen, keyCtx, wrapCtx ) \
847  { \
848  memset( mechanismInfo, 0, sizeof( MECHANISM_WRAP_INFO ) ); \
849  ( mechanismInfo )->wrappedData = ( wrapped ); \
850  ( mechanismInfo )->wrappedDataLength = ( wrappedLen ); \
851  ( mechanismInfo )->keyData = ( key ); \
852  ( mechanismInfo )->keyDataLength = ( keyLen ); \
853  ( mechanismInfo )->keyContext = ( keyCtx ); \
854  ( mechanismInfo )->wrapContext = ( wrapCtx ); \
855  ( mechanismInfo )->auxContext = \
856  ( mechanismInfo )->auxInfo = CRYPT_UNUSED; \
857  }
858 
859 #define setMechanismWrapInfoEx( mechanismInfo, wrapped, wrappedLen, key, keyLen, keyCtx, wrapCtx, auxCtx, auxInf ) \
860  { \
861  memset( mechanismInfo, 0, sizeof( MECHANISM_WRAP_INFO ) ); \
862  ( mechanismInfo )->wrappedData = ( wrapped ); \
863  ( mechanismInfo )->wrappedDataLength = ( wrappedLen ); \
864  ( mechanismInfo )->keyData = ( key ); \
865  ( mechanismInfo )->keyDataLength = ( keyLen ); \
866  ( mechanismInfo )->keyContext = ( keyCtx ); \
867  ( mechanismInfo )->wrapContext = ( wrapCtx ); \
868  ( mechanismInfo )->auxContext = ( auxCtx ); \
869  ( mechanismInfo )->auxInfo = ( auxInf ); \
870  }
871 
872 #define setMechanismSignInfo( mechanismInfo, sig, sigLen, hashCtx, hashCtx2, signCtx ) \
873  { \
874  memset( mechanismInfo, 0, sizeof( MECHANISM_SIGN_INFO ) ); \
875  ( mechanismInfo )->signature = ( sig ); \
876  ( mechanismInfo )->signatureLength = ( sigLen ); \
877  ( mechanismInfo )->hashContext = ( hashCtx ); \
878  ( mechanismInfo )->hashContext2 = ( hashCtx2 ); \
879  ( mechanismInfo )->signContext = ( signCtx ); \
880  }
881 
882 #define setMechanismDeriveInfo( mechanismInfo, out, outLen, in, inLen, hAlgo, slt, sltLen, iters ) \
883  { \
884  memset( mechanismInfo, 0, sizeof( MECHANISM_DERIVE_INFO ) ); \
885  ( mechanismInfo )->dataOut = ( out ); \
886  ( mechanismInfo )->dataOutLength = ( outLen ); \
887  ( mechanismInfo )->dataIn = ( in ); \
888  ( mechanismInfo )->dataInLength = ( inLen ); \
889  ( mechanismInfo )->hashAlgo = ( hAlgo ); \
890  ( mechanismInfo )->salt = ( slt ); \
891  ( mechanismInfo )->saltLength = ( sltLen ); \
892  ( mechanismInfo )->iterations = ( iters ); \
893  }
894 
895 #define setMechanismKDFInfo( mechanismInfo, keyCtx, masterKeyCtx, hAlgo, slt, sltLen ) \
896  { \
897  memset( mechanismInfo, 0, sizeof( MECHANISM_KDF_INFO ) ); \
898  ( mechanismInfo )->keyContext = ( keyCtx ); \
899  ( mechanismInfo )->masterKeyContext = ( masterKeyCtx ); \
900  ( mechanismInfo )->hashAlgo = ( hAlgo ); \
901  ( mechanismInfo )->salt = ( slt ); \
902  ( mechanismInfo )->saltLength = ( sltLen ); \
903  }
904 
905 /****************************************************************************
906 * *
907 * Misc Message Types *
908 * *
909 ****************************************************************************/
910 
911 /* Beside the general value+length and mechanism messages, we also have a
912  number of special-purposes messages that require their own parameter
913  data structures. These are:
914 
915  Create object messages, used to create objects via a device, either
916  directly or indirectly by instantiating the object from encoded data (for
917  example a certificate object from a certificate). Usually the device is
918  the system object, but it can also be used to create contexts in hardware
919  devices. In addition to the creation parameters we also pass in the
920  owner's user object to be stored with the object data for use when
921  needed */
922 
923 typedef struct {
924  CRYPT_HANDLE cryptHandle; /* Handle to created object */
925  CRYPT_USER cryptOwner; /* New object's owner */
926  int arg1, arg2; /* Integer args */
927  BUFFER_OPT_FIXED( strArgLen1 ) \
928  const void *strArg1;
929  BUFFER_OPT_FIXED( strArgLen2 ) \
930  const void *strArg2; /* String args */
931  int strArgLen1, strArgLen2;
933 
934 #define setMessageCreateObjectInfo( createObjectInfo, a1 ) \
935  { \
936  memset( createObjectInfo, 0, sizeof( MESSAGE_CREATEOBJECT_INFO ) ); \
937  ( createObjectInfo )->cryptHandle = CRYPT_ERROR; \
938  ( createObjectInfo )->cryptOwner = CRYPT_ERROR; \
939  ( createObjectInfo )->arg1 = ( a1 ); \
940  }
941 
942 #define setMessageCreateObjectIndirectInfo( createObjectInfo, data, dataLen, type ) \
943  { \
944  memset( createObjectInfo, 0, sizeof( MESSAGE_CREATEOBJECT_INFO ) ); \
945  ( createObjectInfo )->cryptHandle = CRYPT_ERROR; \
946  ( createObjectInfo )->cryptOwner = CRYPT_ERROR; \
947  ( createObjectInfo )->strArg1 = ( data ); \
948  ( createObjectInfo )->strArgLen1 = ( dataLen ); \
949  ( createObjectInfo )->arg1 = ( type ); \
950  }
951 
952 /* Key management messages, used to set, get and delete keys. The item type,
953  keyIDtype, keyID, and keyIDlength are mandatory, the aux.info depends on
954  the type of message (optional password for private key get/set, state
955  information for get next cert, null otherwise), and the flags are
956  generally only required where the keyset can hold multiple types of keys
957  (for example a crypto device acting as a keyset, or a PKCS #15 token).
958 
959  An itemType of KEYMGMT_ITEM_PUBLICKEY is somewhat more general than its
960  name implies in that keysets/devices that store private key information
961  alongside public-key data may delete both types of items if asked to
962  delete a KEYMGMT_ITEM_PUBLICKEY since the two items are (implicitly)
963  connected.
964 
965  An itemType of KEYMGMT_ITEM_REQUEST is distinct from the subtype
966  KEYMGMT_ITEM_REVREQUEST because the former is for certification requests
967  while the latter is for revocation requests, the distinction is made
968  because some protocols only allow certification but not revocation
969  requests and we want to trap these as soon as possible rather than some
970  way down the road when error reporting becomes a lot more nonspecific.
971 
972  An itemType of KEYMGMT_ITEM_KEYMETADATA is a KEYMGMT_ITEM_PRIVATEKEY with
973  the context passed in being a dummy context with actual keying data held
974  in a crypto device. What's stored in the keyset is purely the
975  surrounding metadata like labels, dates, and ID information. This is
976  distinct from a KEYMGMT_ITEM_PRIVATEKEY both to allow for better checking
977  by the kernel, since a KEYMGMT_ITEM_KEYMETADATA object may not be in the
978  high state yet when it's used and doens't need a password like a
979  KEYMGMT_ITEM_PRIVATEKEY does. In addition keeping the types distinct is
980  a safety feature since otherwise we'd need to allow a special-case
981  KEYMGMT_ITEM_PRIVATEKEY store without a password, which is just asking
982  for trouble. Note that KEYMGMT_ITEM_PRIVATEKEY items are write-only, for
983  reads they're treated the same as KEYMGMT_ITEM_PRIVATEKEY except that a
984  dummy context is created.
985 
986  In addition to the flags that are used to handle various special-case
987  read accesses, we can also specify a usage preference (e.g.
988  confidentiality vs.signature) for cases where we may have multiple keys
989  with the same keyID that differ only in required usage */
990 
991 typedef enum {
992  KEYMGMT_ITEM_NONE, /* No item type */
993  KEYMGMT_ITEM_PUBLICKEY, /* Access public key */
994  KEYMGMT_ITEM_PRIVATEKEY, /* Access private key */
995  KEYMGMT_ITEM_SECRETKEY, /* Access secret key */
996  KEYMGMT_ITEM_REQUEST, /* Access cert request */
997  KEYMGMT_ITEM_REVREQUEST, /* Access cert revocation request */
998  KEYMGMT_ITEM_PKIUSER, /* Access PKI user info */
999  KEYMGMT_ITEM_REVOCATIONINFO,/* Access revocation info/CRL */
1000  KEYMGMT_ITEM_KEYMETADATA, /* Access key metadata for dummy ctx.*/
1001  KEYMGMT_ITEM_DATA, /* Other data (for PKCS #15 tokens) */
1002  KEYMGMT_ITEM_LAST /* Last item type */
1004 
1005 #define KEYMGMT_FLAG_NONE 0x0000 /* No flag */
1006 #define KEYMGMT_FLAG_CHECK_ONLY 0x0001 /* Perform existence check only */
1007 #define KEYMGMT_FLAG_LABEL_ONLY 0x0002 /* Get key label only */
1008 #define KEYMGMT_FLAG_UPDATE 0x0004 /* Update existing (allow dups) */
1009 #define KEYMGMT_FLAG_DATAONLY_CERT 0x0008 /* Create data-only certs */
1010 #define KEYMGMT_FLAG_USAGE_CRYPT 0x0010 /* Prefer encryption key */
1011 #define KEYMGMT_FLAG_USAGE_SIGN 0x0020 /* Prefer signature key */
1012 #define KEYMGMT_FLAG_GETISSUER 0x0040 /* Get issuing PKI user for cert */
1013 #define KEYMGMT_FLAG_INITIALOP 0x0080 /* Initial cert issue operation */
1014 #define KEYMGMT_FLAG_MAX 0x00FF /* Maximum possible flag value */
1015 
1016 #define KEYMGMT_MASK_USAGEOPTIONS ( KEYMGMT_FLAG_USAGE_CRYPT | \
1017  KEYMGMT_FLAG_USAGE_SIGN )
1018 #define KEYMGMT_MASK_CERTOPTIONS ( KEYMGMT_FLAG_DATAONLY_CERT | \
1019  KEYMGMT_FLAG_USAGE_CRYPT | \
1020  KEYMGMT_FLAG_USAGE_SIGN )
1021 typedef struct {
1022  CRYPT_HANDLE cryptHandle; /* Returned key */
1023  CRYPT_KEYID_TYPE keyIDtype; /* Key ID type */
1025  const void *keyID; /* Key ID */
1028  void *auxInfo; /* Aux.info (e.g.password for private key) */
1030  int flags; /* Access options */
1032 
1033 #define setMessageKeymgmtInfo( keymgmtInfo, idType, id, idLength, aux, auxLen, keyFlags ) \
1034  { \
1035  ( keymgmtInfo )->cryptHandle = CRYPT_ERROR; \
1036  ( keymgmtInfo )->keyIDtype = ( idType ); \
1037  ( keymgmtInfo )->keyID = ( id ); \
1038  ( keymgmtInfo )->keyIDlength = ( idLength ); \
1039  ( keymgmtInfo )->auxInfo = ( aux ); \
1040  ( keymgmtInfo )->auxInfoLength = ( auxLen ); \
1041  ( keymgmtInfo )->flags = ( keyFlags ); \
1042  }
1043 
1044 /* Cert management messages used to handle CA operations. All fields are
1045  mandatory, however the cryptCert and request fields may be set to
1046  CRYPT_UNUSED to indicate 'don't care' conditions */
1047 
1048 typedef struct {
1049  CRYPT_CERTIFICATE cryptCert; /* Returned cert */
1050  CRYPT_CONTEXT caKey; /* CA key to sign item */
1051  CRYPT_CERTIFICATE request; /* Request for operation */
1053 
1054 #define setMessageCertMgmtInfo( certMgmtInfo, mgmtCaKey, mgmtRequest ) \
1055  { \
1056  ( certMgmtInfo )->cryptCert = CRYPT_ERROR; \
1057  ( certMgmtInfo )->caKey = ( mgmtCaKey ); \
1058  ( certMgmtInfo )->request = ( mgmtRequest ); \
1059  }
1060 
1061 /****************************************************************************
1062 * *
1063 * Kernel Functions *
1064 * *
1065 ****************************************************************************/
1066 
1067 /* cryptlib initialistion/shutdown functions */
1068 
1069 int initCryptlib( void );
1070 int endCryptlib( void );
1071 #if defined( __PALMOS__ ) || defined( __WIN32__ ) || defined( __WINCE__ )
1072  void preInit( void );
1073  void postShutdown( void );
1074 #endif /* Systems with OS-specific pre-init/post-shutdown facilities */
1075 
1076 /* Prototype for an object's message-handling function */
1077 
1078 typedef int ( *MESSAGE_FUNCTION )( INOUT void *objectInfoPtr,
1079  const MESSAGE_TYPE message,
1080  void *messageDataPtr,
1081  const int messageValue ) \
1082  STDC_NONNULL_ARG( ( 1 ) );
1083 
1084 /* If the message-handler can unlock an object to allow other threads
1085  access, it has to be able to inform the kernel of this. The following
1086  structure and macros allow this information to be passed back to the
1087  kernel via the message function's objectInfoPtr */
1088 
1089 typedef struct {
1090  void *objectInfoPtr; /* Original objectInfoPtr */
1091  BOOLEAN isUnlocked; /* Whether obj.is now unlocked */
1093 
1094 #define initMessageExtInfo( messageExtInfo, objectInfo ) \
1095  { \
1096  memset( messageExtInfo, 0, sizeof( MESSAGE_FUNCTION_EXTINFO ) ); \
1097  ( messageExtInfo )->objectInfoPtr = objectInfo; \
1098  }
1099 #define setMessageObjectLocked( messageExtInfo ) \
1100  ( messageExtInfo )->isUnlocked = FALSE
1101 #define setMessageObjectUnlocked( messageExtInfo ) \
1102  ( messageExtInfo )->isUnlocked = TRUE
1103 #define isMessageObjectUnlocked( messageExtInfo ) \
1104  ( ( messageExtInfo )->isUnlocked )
1105 
1106 /* Object management functions. A dummy object is one that exists but
1107  doesn't have the capabilities of the actual object, for example an
1108  encryption context that just maps to underlying crypto hardware. This
1109  doesn't affect krnlCreateObject(), but is used by the object-type-
1110  specific routines that decorate the results of krnlCreateObject() with
1111  object-specific extras */
1112 
1113 #define CREATEOBJECT_FLAG_NONE 0x00 /* No create-object flags */
1114 #define CREATEOBJECT_FLAG_SECUREMALLOC \
1115  0x01 /* Use krnlMemAlloc() to alloc.*/
1116 #define CREATEOBJECT_FLAG_DUMMY 0x02 /* Dummy obj.used as placeholder */
1117 #define CREATEOBJECT_FLAG_PERSISTENT 0x04 /* Obj.backed by key in device */
1118 #define CREATEOBJECT_FLAG_MAX 0x0F /* Maximum possible flag value */
1119 
1120 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 9 ) ) \
1121 int krnlCreateObject( OUT_HANDLE_OPT int *objectHandle,
1122  OUT_BUFFER_ALLOC_OPT( objectDataSize ) void **objectDataPtr,
1124  IN_ENUM( OBJECT ) const OBJECT_TYPE type,
1125  IN_ENUM( OBJECT_SUB ) const OBJECT_SUBTYPE subType,
1126  IN_FLAGS( CREATEOBJECT ) const int createObjectFlags,
1128  IN_FLAGS( ACTION ) const int actionFlags,
1130 int krnlSendMessage( IN_HANDLE const int objectHandle,
1132  void *messageDataPtr, const int messageValue );
1133 
1134 /* Since some messages contain no data but act only as notifiers, we define
1135  the following macro to make using them less messy */
1136 
1137 #define krnlSendNotifier( handle, message ) \
1138  krnlSendMessage( handle, message, NULL, 0 )
1139 
1140 /* In some rare cases we have to access an object directly without sending
1141  it a message. This happens either with certs where we're already
1142  processing a message for one cert and need to access internal data in
1143  another cert, when we're working with a crypto device tied to a context
1144  where we need access to both context and device internals at the same
1145  time, or when we're updating config data in a user object. This type of
1146  access is handled by the following function, which also explicitly
1147  disallows any access types apart from the three described here */
1148 
1149 CHECK_RETVAL STDC_NONNULL_ARG( ( 3 ) ) \
1150 int krnlAcquireObject( IN_HANDLE const int objectHandle,
1151  IN_ENUM( OBJECT ) const OBJECT_TYPE type,
1153  IN_ERROR const int errorCode );
1154 int krnlReleaseObject( IN_HANDLE const int objectHandle );
1155 
1156 /* In even rarer cases, we have to allow a second thread access to an object
1157  when another thread has it locked, providing a (somewhat crude) mechanism
1158  for making kernel calls interruptible and resumable. This only occurs in
1159  two cases, for the system object when a background polling thread is
1160  adding entropy to the system device and for the user object when we're
1161  saving configuration data to persistent storage (we temporarily unlock it
1162  to allow other threads access, since the act of writing the marshalled
1163  data to storage doesn't require the user object) */
1164 
1165 STDC_NONNULL_ARG( ( 2 ) ) \
1166 int krnlSuspendObject( IN_HANDLE const int objectHandle,
1168 CHECK_RETVAL \
1169 int krnlResumeObject( IN_HANDLE const int objectHandle,
1170  IN_INT_Z const int refCount );
1171 
1172 /* When the kernel is closing down, any cryptlib-internal threads should
1173  exit as quickly as possible. For threads coming in from the outside this
1174  happens automatically because any message it tries to send fails, but for
1175  internal worker threads (for example the async driver-binding thread or
1176  randomness polling threads) that don't perform many kernel calls, the
1177  thread has to periodically check whether the kernel is still active. The
1178  following function is used to indicate whether the kernel is shutting
1179  down */
1180 
1181 CHECK_RETVAL_BOOL \
1182 BOOLEAN krnlIsExiting( void );
1183 
1184 /* Semaphores and mutexes */
1185 
1186 typedef enum {
1187  SEMAPHORE_NONE, /* No semaphore */
1188  SEMAPHORE_DRIVERBIND, /* Async driver bind */
1189  SEMAPHORE_LAST /* Last semaphore */
1190  } SEMAPHORE_TYPE;
1191 
1192 typedef enum {
1193  MUTEX_NONE, /* No mutex */
1194  MUTEX_SCOREBOARD, /* Session scoreboard */
1195  MUTEX_SOCKETPOOL, /* Network socket pool */
1196  MUTEX_RANDOM, /* Randomness subsystem */
1197  MUTEX_LAST /* Last mutex */
1198  } MUTEX_TYPE;
1199 
1200 /* Execute a function in a background thread. This takes a pointer to the
1201  function to execute in the background thread, a block of memory for
1202  thread state storage, a set of parameters to pass to the thread function,
1203  and an optional semaphore ID to set once the thread is started. A
1204  function is run via a background thread as follows:
1205 
1206  void threadFunction( const THREAD_PARAMS *threadParams )
1207  {
1208  }
1209 
1210  krnlDispatchThread( threadFunction, &threadState, ptrParam, intParam,
1211  SEMAPHORE_ID );
1212 
1213  Note that the thread parameters must be held in static storage because
1214  the caller's stack frame may have long since disappeared before the
1215  thread gets to access them */
1216 
1217 struct TF;
1218 
1219 typedef void ( *THREAD_FUNCTION )( const struct TF *threadParams );
1220 
1221 typedef BYTE THREAD_STATE[ 48 ];
1222 
1223 typedef struct TF {
1224  void *ptrParam; /* Pointer parameter */
1225  int intParam; /* Integer parameter */
1226  } THREAD_PARAMS;
1227 
1228 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1229 int krnlDispatchThread( THREAD_FUNCTION threadFunction,
1230  THREAD_STATE threadState, void *ptrParam,
1231  const int intParam, const SEMAPHORE_TYPE semaphore );
1232 
1233 /* Wait on a semaphore, enter and exit a mutex */
1234 
1235 CHECK_RETVAL_BOOL \
1236 BOOLEAN krnlWaitSemaphore( IN_ENUM( SEMAPHORE ) const SEMAPHORE_TYPE semaphore );
1237 CHECK_RETVAL \
1238 int krnlEnterMutex( IN_ENUM( MUTEX ) const MUTEX_TYPE mutex );
1239 void krnlExitMutex( IN_ENUM( MUTEX ) const MUTEX_TYPE mutex );
1240 
1241 /* Secure memory handling functions */
1242 
1243 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1244 int krnlMemalloc( OUT_BUFFER_ALLOC_OPT( size ) void **pointer,
1246 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
1247 int krnlMemfree( INOUT_PTR void **pointer );
1248 
1249 #ifdef NEED_ENUMFIX
1250  #undef OBJECT_TYPE_LAST
1251  #undef MESSAGE_COMPARE_LAST
1252  #undef MESSAGE_CHECK_LAST
1253  #undef MESSAGE_CHANGENOTIFY_LAST
1254  #undef MECHANISM_LAST
1255  #undef KEYMGMT_ITEM_LAST
1256  #undef SEMAPHORE_LAST
1257  #undef MUTEX_LAST
1258 #endif /* NEED_ENUMFIX */
1259 #endif /* _CRYPTKRN_DEFINED */