cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
cert.h
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * Certificate Routines Header File *
4 * Copyright Peter Gutmann 1996-2008 *
5 * *
6 ****************************************************************************/
7 
8 #ifndef _CERT_DEFINED
9 
10 #define _CERT_DEFINED
11 
12 #include <time.h>
13 #ifndef _STREAM_DEFINED
14  #if defined( INC_ALL )
15  #include "stream.h"
16  #else
17  #include "io/stream.h"
18  #endif /* Compiler-specific includes */
19 #endif /* _STREAM_DEFINED */
20 
21 /* The minimum size of an attribute, SEQUENCE (2), OID (5),
22  OCTET STRING (2+3 for payload). This is the amount of slop to allow when
23  reading attributes. Some software gets the length encoding wrong by a few
24  bytes, if what's left at the end of an encoded object is >= this value
25  then we look for attributes */
26 
27 #define MIN_ATTRIBUTE_SIZE 12
28 
29 /* The maximum size of a PKCS #7 certificate chain. The built-in bounds
30  value FAILSAFE_ITERATIONS_MED is used as a safety check for an upper
31  limit on chain lengths (that is, if we hit FAILSAFE_ITERATIONS_MED on
32  processing a certificate chain it's an internal error), so it has to
33  be larger than MAX_CHAINLENGTH */
34 
35 #define MAX_CHAINLENGTH 16
36 
37 #if MAX_CHAINLENGTH > FAILSAFE_ITERATIONS_MED
38  #error FAILSAFE_ITERATIONS_MED must be larger than the maximum certificate chain length
39 #endif /* MAX_CHAINLENGTH > FAILSAFE_ITERATIONS_MED */
40 
41 /* The default size of the serial number, size of the built-in serial number
42  buffer (anything larger than this uses a dynamically-allocated buffer)
43  and the maximum size in bytes of a serial number (for example in a
44  certificate or CRL). Technically values of any size are allowed but
45  anything larger than this is probably an error */
46 
47 #define DEFAULT_SERIALNO_SIZE 8
48 #define SERIALNO_BUFSIZE 32
49 #define MAX_SERIALNO_SIZE 256
50 
51 /* The size of the PKI user binary authenticator information before
52  checksumming and encoding and the size of the encrypted user info:
53  sizeofObject( 2 * sizeofObject( PKIUSER_AUTHENTICATOR_SIZE ) ) + PKCS #5
54  padding = 2 + ( 2 + 12 + 2 + 12 ) = 30 + 2 = 32. This works for both 64-
55  and 128-bit block ciphers */
56 
57 #define PKIUSER_AUTHENTICATOR_SIZE 12
58 #define PKIUSER_ENCR_AUTHENTICATOR_SIZE 32
59 
60 /* The size of the FIFO used to encode nested SEQUENCEs */
61 
62 #define ENCODING_FIFO_SIZE 10
63 
64 /* Normally we check for a valid time by making sure that it's more recent
65  than MIN_TIME_VALUE, however when reading a certificate the time can be
66  much earlier than this if it's an old certificate. To handle this we
67  define a certificate-specific time value that we use as the oldest valid
68  time value */
69 
70 #define MIN_CERT_TIME_VALUE ( ( 1996 - 1970 ) * 365 * 86400L )
71 
72 /* Certificate information flags. These are:
73 
74  FLAG_CERTCOLLECTION: Indicates that a certificate chain object contains
75  only an unordered collection of (non-duplicate) certificates
76  rather than a true certificate chain. Note that this is a pure
77  container object for which only the certificate chain member
78  contains certificates, the base certificate object doesn't
79  correspond to an actual certificate.
80 
81  FLAG_CRLENTRY: The CRL object contains the data from a single CRL entry
82  rather than being a complete CRL.
83 
84  FLAG_DATAONLY: Indicates a pure data object with no attached context.
85 
86  FLAG_PATHKLUDGE: Indicates that although the certificate appears to be a
87  self-signed (CA root) certificate it's actually a PKIX path
88  kludge certificate that's used to tie a re-issued CA certificate
89  (with a new CA key) to existing issued certificates signed with
90  the old CA key. This kludge requires that issuer DN == subject
91  DN, which would denote a CA root certificate under normal
92  circumstances.
93 
94  FLAG_SELFSIGNED: Indicates that the certificate is self-signed.
95 
96  FLAG_SIGCHECKED: Caches the check of the certificate signature. This is
97  done because it's only necessary to perform this once when the
98  certificate is checked for the first time. Checking of
99  certificate fields that aren't affected by the issuer
100  certificate is also cached, but this is handled by the
101  compliance-level check value rather than a simple boolean flag
102  since a certificate can be checked at various levels of
103  standards-compliance */
104 
105 #define CERT_FLAG_NONE 0x00 /* No flag */
106 #define CERT_FLAG_SELFSIGNED 0x01 /* Certificate is self-signed */
107 #define CERT_FLAG_SIGCHECKED 0x02 /* Signature has been checked */
108 #define CERT_FLAG_DATAONLY 0x04 /* Certificate is data-only (no context) */
109 #define CERT_FLAG_CRLENTRY 0x08 /* CRL is a standalone single entry */
110 #define CERT_FLAG_CERTCOLLECTION 0x10 /* Certificate chain is unordered collection */
111 #define CERT_FLAG_PATHKLUDGE 0x20 /* Certificate is a PKIX path kludge */
112 #define CERT_FLAG_MAX 0x3F /* Maximum possible flag value */
113 
114 /* When creating RTCS responses from a request there are several subtypes
115  that we can use based on a format specifier in the request. When we turn
116  the request into a response we check the format specifiers and record the
117  response format as being one of the following */
118 
119 typedef enum {
120  RTCSRESPONSE_TYPE_NONE, /* No response type */
121  RTCSRESPONSE_TYPE_BASIC, /* Basic response */
122  RTCSRESPONSE_TYPE_EXTENDED, /* Extended response */
123  RTCSRESPONSE_TYPE_LAST /* Last valid response type */
125 
126 /* Set the error locus and type. This is used for certificate checking
127  functions that need to return extended error information but can't modify
128  the certificate information struct due to it either being a const
129  parameter or only being available via a handle so that setErrorInfo()
130  can't be used */
131 
132 #define setErrorValues( locus, type ) \
133  *errorLocus = ( locus ); *errorType = ( type )
134 
135 /* The are several different classes of attributes that can be used
136  depending on the object that they're associated with. The following
137  values are used to select the class of attribute that we want to work
138  with */
139 
140 typedef enum {
141  ATTRIBUTE_CERTIFICATE, /* Certificate attributes */
142  ATTRIBUTE_CMS, /* CMS / S/MIME attributes */
143  ATTRIBUTE_LAST /* Last valid attribute type */
144  } ATTRIBUTE_TYPE;
145 
146 /* When checking policy constraints there are several different types of
147  checking that we can apply depending on the presence of other constraints
148  in the issuing certificate(s) and the level of checking that we're
149  performing. Policies can be optional, required, or a specific-policy
150  check that disallows the wildcard anyPolicy as a matching policy */
151 
152 typedef enum { /* Issuer Subject */
153  POLICY_NONE, /* - - */
154  POLICY_NONE_SPECIFIC, /* -, !any -, !any */
155  POLICY_SUBJECT, /* - yes */
156  POLICY_SUBJECT_SPECIFIC, /* - yes, !any */
157  POLICY_BOTH, /* yes yes */
158  POLICY_BOTH_SPECIFIC, /* yes, !any yes, !any */
159  POLICY_LAST /* Last valid policy type */
160  } POLICY_TYPE;
161 
162 /* Selection options when working with DNs/GeneralNames in extensions. These
163  are used internally when handling user get/set/delete DN/GeneralName
164  requests */
165 
166 typedef enum {
167  SELECTION_OPTION_NONE, /* No selection option type */
168  MAY_BE_ABSENT, /* Component may be absent */
169  MUST_BE_PRESENT, /* Component must be present */
170  CREATE_IF_ABSENT, /* Create component if absent */
171  SELECTION_OPTION_LAST /* Last valid selection option type */
173 
174 /* Certificate key check flags, used by checkKeyUsage(). These are:
175 
176  FLAG_NONE: No specific check.
177 
178  FLAG_CA: Certificate must contain a CA key.
179 
180  FLAG_PRIVATEKEY: Check for constraints on the corresponding private
181  key's usage, not just the public key usage.
182 
183  FLAG_GENCHECK: Perform a general check that the key usage details are
184  in order without checking for a particular usage */
185 
186 #define CHECKKEY_FLAG_NONE 0x00 /* No specific checks */
187 #define CHECKKEY_FLAG_CA 0x01 /* Must be CA key */
188 #define CHECKKEY_FLAG_PRIVATEKEY 0x02 /* Check priv.key constraints */
189 #define CHECKKEY_FLAG_GENCHECK 0x04 /* General details check */
190 #define CHECKKEY_FLAG_MAX 0x07 /* Maximum possible flag value */
191 
192 /* Before we encode a certificate object we have to perform various final
193  setup actions and check that the object is ready for encoding. The
194  following setup operations can be requested by the caller via
195  preEncodeCertificate():
196 
197  SET_ISSUERATTR: Copy issuer attributes to subject.
198 
199  SET_ISSUERDN: Copy issuer DN to subject.
200 
201  SET_REVINFO: Set up revocation information.
202 
203  SET_STANDARDATTR: Set up standard extensions/attributes.
204 
205  SET_VALIDITYPERIOD: Constrain subject validity to issuer validity.
206 
207  SET_VALINFO: Set up validity information */
208 
209 #define PRE_SET_NONE 0x0000 /* No setup actions */
210 #define PRE_SET_STANDARDATTR 0x0001 /* Set up standard extensions */
211 #define PRE_SET_ISSUERATTR 0x0002 /* Copy issuer attr.to subject */
212 #define PRE_SET_ISSUERDN 0x0004 /* Copy issuer DN to subject */
213 #define PRE_SET_VALIDITYPERIOD 0x0008 /* Constrain subj.val.to issuer val.*/
214 #define PRE_SET_VALINFO 0x0010 /* Set up validity information */
215 #define PRE_SET_REVINFO 0x0020 /* Set up revocation information */
216 
217 #define PRE_SET_FLAG_NONE 0x0000 /* No setup actions */
218 #define PRE_SET_FLAG_MAX 0x003F /* Maximum possible flag value */
219 
220 /* The following checks can be requested by the caller via
221  preCheckCertificate():
222 
223  CHECK_DN: Full subject DN is present.
224 
225  CHECK_DN_PARTIAL: Partial subject DN is present. This is a DN template
226  so the full DN doesn't have to be present (the CA can fill in the
227  rest later), only the CommonName.
228 
229  CHECK_ISSUERDN: Issuer DN is present.
230 
231  CHECK_ISSUERCERTDN: Issuer certificate's subject DN == subject
232  certificate's issuer DN.
233 
234  CHECK_NONSELFSIGNEDDN: Certificate's subject DN != certificate's issuer
235  DN, which would make it appear to be a self-signed certificate.
236 
237  CHECK_REVENTRIES: At least one revocation entry is present.
238 
239  CHECK_SERIALNO: Serial number is present.
240 
241  CHECK_SPKI: SubjectPublicKeyInfo is present.
242 
243  CHECK_VALENTRIES: At least one validity entry is present */
244 
245 #define PRE_CHECK_NONE 0x0000 /* No check actions */
246 #define PRE_CHECK_SPKI 0x0001 /* SPKI present */
247 #define PRE_CHECK_DN 0x0002 /* Subject DN present */
248 #define PRE_CHECK_DN_PARTIAL 0x0004 /* Partial subject DN present */
249 #define PRE_CHECK_ISSUERDN 0x0008 /* Issuer DN present */
250 #define PRE_CHECK_ISSUERCERTDN 0x0010 /* Issuer cert DN == subj.issuer DN */
251 #define PRE_CHECK_NONSELFSIGNED_DN 0x0020 /* Issuer DN != subject DN */
252 #define PRE_CHECK_SERIALNO 0x0040 /* SerialNo present */
253 #define PRE_CHECK_VALENTRIES 0x0080 /* Validity entries present */
254 #define PRE_CHECK_REVENTRIES 0x0100 /* Revocation entries present */
255 
256 #define PRE_CHECK_FLAG_NONE 0x0000 /* No check actions */
257 #define PRE_CHECK_FLAG_MAX 0x01FF /* Maximum possible flag value */
258 
259 /* Additional flags that control the checking operations indicated above */
260 
261 #define PRE_FLAG_NONE 0x0000 /* No special control options */
262 #define PRE_FLAG_DN_IN_ISSUERCERT 0x0001/* Issuer DN is in issuer cert */
263 #define PRE_FLAG_MAX 0x0001 /* Maximum possible flag value */
264 
265 /* The following checks can be requested by the caller via checkDN() */
266 
267 #define CHECKDN_FLAG_NONE 0x00 /* No DN check */
268 #define CHECKDN_FLAG_COUNTRY 0x01 /* Check DN has C */
269 #define CHECKDN_FLAG_COMMONNAME 0x02 /* Check DN has CN */
270 #define CHECKDN_FLAG_WELLFORMED 0x04 /* Check DN is well-formed */
271 #define CHECKDN_FLAG_MAX 0x0F /* Maximum possible flag value */
272 
273 /****************************************************************************
274 * *
275 * Certificate Element Tags *
276 * *
277 ****************************************************************************/
278 
279 /* Context-specific tags for certificates */
280 
283 
284 /* Context-specific tags for attribute certificates */
285 
289 
290 /* Context-specific tags for certification requests */
291 
293 
294 /* Context-specific tags for CRLs */
295 
297 
298 /* Context-specific tags for CRMF certification requests. The second set of
299  tags is for POP of the private key */
300 
305 
306 /* Context-specific tags for RTCS responses */
307 
309 
310 /* Context-specific tags for OCSP requests. The second set of tags
311  is for each request entry in an overall request */
312 
315 
316 /* Context-specific tags for OCSP responses */
317 
319 
320 /* Context-specific tags for CMS attributes */
321 
323 
324 /****************************************************************************
325 * *
326 * Certificate Data Structures *
327 * *
328 ****************************************************************************/
329 
330 /* Symbolic defines for data types handled in the certificate attribute and
331  DN handling code. The ATTRIBUTE_PTR_STORAGE value is used in debug
332  macros that check that an ATTRIBUTE_PTR points to at least
333  ATTRIBUTE_PTR_STORAGE bytes of readable/writeable memory */
334 
335 #define ATTRIBUTE_PTR void
336 #define ATTRIBUTE_PTR_STORAGE char[ 64 ]
337 #define DN_PTR void
338 #define DN_PTR_STORAGE char[ 32 ]
339 
340 /* The structure to hold information on the current selection of attribute/
341  GeneralName/DN data used when adding/reading/deleting certificate
342  components. The usage of this information is too complex to explain
343  here, see the comments at the start of comp_get.c for more details.
344 
345  Note that the DN pointer stores a pointer to the head of the list of DN
346  elements rather than storing the list head itself since we need to pass
347  it to functions that may modify the list head. So dnPtr may contain
348  (for example) &certInfoPtr->subjectDN so that it can be passed to
349  functions like deleteDnComponent() which may have to modify the list
350  head if that's the entry that they're being asked to delete. Storing a
351  copy of certInfoPtr->subjectDN in dnPtr and then passing &dnPtr to
352  deleteDnComponent() would update dnPtr but leave certInfoPtr->subjectDN
353  with a dangling reference to the new-deleted DN element */
354 
355 typedef struct {
356  DN_PTR **dnPtr; /* Pointer to address of current DN */
358  CRYPT_ATTRIBUTE_TYPE dnComponent; /* Selected component of DN */
359  int dnComponentCount; /* Iterator for DN components */
360  BOOLEAN dnInExtension; /* Whether DN is in extension */
361  BOOLEAN updateCursor; /* Whether to upate attr.cursor */
362  } SELECTION_INFO;
363 
364 #define initSelectionInfo( certInfoPtr ) \
365  memset( &( certInfoPtr )->currentSelection, 0, sizeof( SELECTION_INFO ) ); \
366  ( certInfoPtr )->currentSelection.dnPtr = &( ( certInfoPtr )->subjectName )
367 
368 /* Sometimes we need to manipulate an internal component which is addressed
369  indirectly as a side-effect of some other processing operation. We can't
370  change the selection information for the certificate object since this will
371  affect any future operations that the user performs so we provide the
372  following macros to save and restore the selection state around these
373  operations */
374 
375 typedef struct {
376  int savedChainPos; /* Current cert.chain position */
377  SELECTION_INFO savedSelectionInfo; /* Current DN/GN selection info */
378  ATTRIBUTE_PTR *savedAttributeCursor;/* Atribute cursor pos.*/
379  } SELECTION_STATE;
380 
381 #define saveSelectionState( savedState, certInfoPtr ) \
382  { \
383  memset( &( savedState ), 0, sizeof( SELECTION_STATE ) ); \
384  if( ( certInfoPtr )->type == CRYPT_CERTTYPE_CERTCHAIN ) \
385  ( savedState ).savedChainPos = ( certInfoPtr )->cCertCert->chainPos; \
386  ( savedState ).savedSelectionInfo = ( certInfoPtr )->currentSelection; \
387  ( savedState ).savedAttributeCursor = ( certInfoPtr )->attributeCursor; \
388  }
389 
390 #define restoreSelectionState( savedState, certInfoPtr ) \
391  { \
392  if( ( certInfoPtr )->type == CRYPT_CERTTYPE_CERTCHAIN ) \
393  ( certInfoPtr )->cCertCert->chainPos = ( savedState ).savedChainPos; \
394  ( certInfoPtr )->currentSelection = ( savedState ).savedSelectionInfo; \
395  ( certInfoPtr )->attributeCursor = ( savedState ).savedAttributeCursor; \
396  }
397 
398 /* The structure used to store the current policy set if we're doing full
399  policy checking, enabled for CERTLEVEL_PKIX_FULL. The MAX_POLICY_SIZE
400  value corresponds to MAX_OID_SIZE, unfortunately this define isn't
401  visible at this level so we have to specify the value explicitly (the
402  length is checked on read so there's no chance of an overflow).
403 
404  When we store the policy value (which is just the encoded policy OID) we
405  also store the level in the certificate chain at which it was added
406  (since a policy is only valid below the point at which it was added) and
407  an indication of whether the policy is explicit or mapped, since the
408  latter can be disabled by the inhibitPolicyMapping value */
409 
410 #if defined( USE_CERTLEVEL_PKIX_FULL )
411 
412 #define MAX_POLICIES 16
413 #define MAX_POLICY_SIZE 32
414 
415 typedef struct {
416  BYTE data[ MAX_POLICY_SIZE + 8 ];
417  int length; /* Policy value and length */
418  int level; /* Pos.in chain at which pol.becomes valid */
419  BOOLEAN isMapped; /* Whether this is a mapped policy */
420  } POLICY_DATA;
421 
422 typedef struct {
423  POLICY_DATA policies[ MAX_POLICIES + 4 ];
424  int noPolicies;
425  } POLICY_INFO;
426 #endif /* USE_CERTLEVEL_PKIX_FULL */
427 
428 #ifdef USE_CERTVAL
429 
430 /* The structure to hold a validity information entry */
431 
432 typedef struct VI {
433  /* Certificate ID information */
435  BYTE data[ KEYID_SIZE + 8 ];
436  int dCheck; /* Data checksum for quick match */
437 
438  /* Validity information */
439  BOOLEAN status; /* Valid/not valid */
440  int extStatus; /* Extended validity status */
441  time_t invalidityTime; /* Certificate invalidity time */
442 
443  /* Per-entry attributes. These are a rather ugly special case for the
444  user because unlike the attributes for all other certificate objects
445  where cryptlib can provide the illusion of a flat type<->value
446  mapping there can be multiple sets of identical per-entry attributes
447  present if there are multiple RTCS entries present */
448  ATTRIBUTE_PTR *attributes; /* RTCS entry attributes */
449  int attributeSize; /* Encoded size of attributes */
450 
451  /* The next element in the linked list of elements */
452  struct VI *next;
453  } VALIDITY_INFO;
454 
455 typedef struct {
456  /* A list of RTCS request or response entries and a pointer to the
457  request/response which is currently being accessed */
458  VALIDITY_INFO *validityInfo; /* List of validity info */
459  VALIDITY_INFO *currentValidity; /* Currently selected validity info */
460 
461  /* The URL for the RTCS responder */
462  BUFFER_OPT_FIXED( responderUrlSize ) \
463  char *responderUrl; /* RTCS responder URL */
464  int responderUrlSize;
465 
466  /* Since RTCS allows for a variety of response types, we include an
467  indication of the request/response format */
468  RTCSRESPONSE_TYPE responseType; /* Request/response format */
469  } CERT_VAL_INFO;
470 #endif /* USE_CERTVAL */
471 
472 #ifdef USE_CERTREV
473 
474 /* The structure to hold a revocation information entry, either a CRL entry
475  or OCSP request/response information */
476 
477 typedef struct RI {
478  /* Certificate ID information, either a serial number (for CRLs) or a
479  certificate hash or issuerID (for OCSP requests/responses). In
480  addition this could also be a pre-encoded OCSP certID, which is
481  treated as an opaque blob of type CRYPT_ATTRIBUTE_NONE since it can't
482  be used in any useful way. If we're using OCSP and an alternative ID
483  is supplied as an ESSCertID we point to this value (inside the
484  ESSCertID) in the altIdPtr field. Since we store this as a varstruct
485  whose data is expected to be held in a field called 'value' we define
486  a field of that name alongside the more obvious 'id' and set 'id' to
487  'value' when we initialise the structure */
488  CRYPT_KEYID_TYPE idType; /* ID type */
489  BUFFER_OPT_FIXED( idLength ) \
490  BYTE *id, *value; /* ID information stored in varstruct */
491  int idLength; /* (see comment above for 'value') */
492  int idCheck; /* Data checksum for quick match */
493  CRYPT_KEYID_TYPE altIdType; /* Alt.ID type for OCSP */
495  BYTE altID[ KEYID_SIZE + 8 ]; /* Alt.ID for OCSP */
496 
497  /* Revocation information */
498  int status; /* OCSP revocation status */
499  time_t revocationTime; /* Certificate revocation time */
500 
501  /* Per-entry attributes. These are a rather ugly special case for the
502  user because unlike the attributes for all other certificate objects
503  where cryptlib can provide the illusion of a flat type<->value
504  mapping there can be multiple sets of identical per-entry attributes
505  present if there are multiple CRL/OCSP entries present */
506  ATTRIBUTE_PTR *attributes; /* CRL/OCSP entry attributes */
507  int attributeSize; /* Encoded size of attributes */
508 
509  /* The next element in the linked list of elements */
510  struct RI *next;
511 
512  /* Variable-length storage for the ID information */
514  } REVOCATION_INFO;
515 
516 typedef struct {
517  /* The list of revocations for a CRL or a list of OCSP request or response
518  entries, and a pointer to the revocation/request/response which is
519  currently being accessed */
520  REVOCATION_INFO *revocations; /* List of revocations */
521  REVOCATION_INFO *currentRevocation; /* Currently selected revocation */
522 
523  /* The default revocation time for a CRL, used for if no explicit time
524  is set for a revocation */
525  time_t revocationTime; /* Default certificate revocation time */
526 
527  /* The URL for the OCSP responder */
528  BUFFER_OPT_FIXED( responderUrlSize ) \
529  char *responderUrl;
530  int responderUrlSize; /* OCSP responder URL */
531 
532  /* The hash algorithm used to sign the certificate. Although it's a
533  part of the signature, a second copy of the algorithm ID is embedded
534  inside the signed certificate data because of a theoretical attack
535  that doesn't actually work with any standard signature padding
536  technique. Because of this we have to record the hash algorithm ID
537  when we read/write the certificate so that we can write it again when
538  we re-encode the certificate */
540 
541  /* Signed OCSP requests can include varying levels of detail in the
542  signature. The following value determines how much information is
543  included in the signature */
544  CRYPT_SIGNATURELEVEL_TYPE signatureLevel;
545  } CERT_REV_INFO;
546 #endif /* USE_CERTREV */
547 
548 #ifdef USE_CERTREQ
549 
550 typedef struct {
551  /* The certificate serial number, used when requesting a revocation by
552  issuerAndSerialNumber. This is stored in the buffer if it fits (it
553  almost always does), otherwise in a dynamically-allocated buffer */
555  BYTE serialNumberBuffer[ SERIALNO_BUFSIZE + 8 ];
557  void *serialNumber;
558  int serialNumberLength; /* Certificate serial number */
559 
560  /* The certificate ID of the PKI user or certificate that authorised
561  this request. This is from an external source, supplied when the
562  request is used as part of the CMP protocol */
564  BYTE authCertID[ KEYID_SIZE + 8 ];
565  } CERT_REQ_INFO;
566 #endif /* USE_CERTREQ */
567 
568 #ifdef USE_PKIUSER
569 
570 typedef struct {
571  /* The authenticator used for authenticating certificate issue and
572  revocation requests */
573  BUFFER_FIXED( 16 ) \
574  BYTE pkiIssuePW[ 16 + 8 ];
575  BUFFER_FIXED( 16 ) \
576  BYTE pkiRevPW[ 16 + 8 ];
577  } CERT_PKIUSER_INFO;
578 #endif /* USE_PKIUSER */
579 
580 /* The internal fields in a certificate that hold subtype-specific data for
581  the various certificate object types */
582 
583 typedef struct {
584  /* The certificate serial number. This is stored in the buffer if it
585  fits (it almost always does), otherwise in a dynamically-allocated
586  buffer */
588  BYTE serialNumberBuffer[ SERIALNO_BUFSIZE + 8 ];
590  void *serialNumber;
591  int serialNumberLength; /* Certificate serial number */
592 
593  /* The highest compliance level at which a certificate has been checked.
594  We have to record this high water-mark level because increasing the
595  compliance level may invalidate an earlier check performed at a lower
596  level */
598 
599  /* The allowed usage for a certificate can be further controlled by the
600  user. The trustedUsage value is a mask which is applied to the key
601  usage extension to further constrain usage, alongside this there is
602  an additional implicit trustImplicit value that acts as a boolean
603  flag and indicates whether the user implicitly trusts this
604  certificate (without requiring further checking upstream). This
605  value isn't stored with the certificate since it's a property of any
606  instantiation of the certificate rather than just the current one so
607  when the user queries it it's obtained dynamically from the trust
608  manager */
610 
611  /* Certificate chains are a special variant of standard certificates,
612  being complex container objects that contain further certificates
613  leading up to a CA root certificate. The reason why they're combined
614  with standard certificates is because when we're building a chain
615  from a certificate collection or assembling it from a certificate
616  source we can't tell at the time of certificate creation which
617  certificate will be the leaf certificate so that any certificate
618  potentially has to be able to act as the chain container (another way
619  of looking at this is that all standard certificates are a special
620  case of a chain with a length of one).
621 
622  A possible alternative to this way of handling chains is to make the
623  chain object a pure container object used only to hold pointers to
624  the actual certificates, but this requires an extra level of
625  indirection every time that a certificate chain object is used since
626  in virtually all cases what'll be used is the leaf certificate with
627  which the chain-as-standard-certificate model is the default
628  certificate but with the chain-as-container model requires an extra
629  object dereference to obtain.
630 
631  In theory we should use a linked list to store chains but since the
632  longest chain ever seen in the wild has a length of 4 using a fixed
633  maximum length several times this size shouldn't be a problem. The
634  certificates in the chain are ordered from the parent of the leaf
635  certificate up to the root certificate with the leaf certificate
636  corresponding to the [-1]th entry in the list. We also maintain a
637  current position in the certificate chain that denotes the
638  certificate in the chain that will be accessed by the
639  component-manipulation functions. This is set to CRYPT_ERROR if the
640  current certificate is the leaf certificate */
641  ARRAY( MAX_CHAINLENGTH, chainEnd ) \
643  int chainEnd; /* Length of certificate chain */
644  int chainPos; /* Currently selected certificate in chain */
645 
646  /* The hash algorithm used to sign the certificate. Although it's a
647  part of the signature, a second copy of the algorithm ID is embedded
648  inside the signed certificate data because of a theoretical attack
649  that doesn't actually work with any standard signature padding
650  technique */
652 
653 #ifdef USE_CERT_OBSOLETE
654  /* The (deprecated) X.509v2 unique ID */
655  BUFFER_OPT_FIXED( issuerUniqueIDlength ) \
656  void *issuerUniqueID;
657  BUFFER_OPT_FIXED( subjectUniqueIDlength ) \
658  void *subjectUniqueID;
659  int issuerUniqueIDlength, subjectUniqueIDlength;
660 #endif /* USE_CERT_OBSOLETE */
661  } CERT_CERT_INFO;
662 
663 /* Defines to make access to the union fields less messy */
664 
665 #define cCertCert certInfo.certInfo
666 #define cCertReq certInfo.reqInfo
667 #define cCertRev certInfo.revInfo
668 #define cCertVal certInfo.valInfo
669 #define cCertUser certInfo.pkiUserInfo
670 
671 /* The structure that stores information on a certificate object */
672 
673 typedef struct {
674  /* General certificate information */
675  CRYPT_CERTTYPE_TYPE type; /* Certificate type */
676  int flags; /* Certificate flags */
677  int version; /* Certificate format version */
678 
679  /* Certificate type-specific information */
680  union {
682 #ifdef USE_CERTREQ
683  CERT_REQ_INFO *reqInfo;
684 #endif /* USE_CERTREQ */
685 #ifdef USE_CERTREV
686  CERT_REV_INFO *revInfo;
687 #endif /* USE_CERTREV */
688 #ifdef USE_CERTVAL
689  CERT_VAL_INFO *valInfo;
690 #endif /* USE_CERTVAL */
691 #ifdef USE_PKIUSER
692  CERT_PKIUSER_INFO *pkiUserInfo;
693 #endif /* USE_PKIUSER */
694  } certInfo;
695 
696  /* The encoded certificate object. We save this when we import it
697  because there are many different interpretations of how a certificate
698  should be encoded and if we parse and then try to re-encode the
699  object the signature check would most likely fail */
700  BUFFER_OPT_FIXED( certificateSize ) \
701  void *certificate;
703 
704  /* The public key associated with the certificate. When the
705  certificate is in the low (unsigned state) this consists of the
706  encoded public-key data and associated attributes. When the
707  certificate is in the high (signed) state, either by being imported
708  from an external source or by being signed by cryptlib, this consists
709  of a public-key context. In addition some certificates are imported
710  as data-only certificates, denoted by CERT_FLAG_DATAONLY being set.
711  These constitute a container object that contain no public-key context
712  and are used for certificate chains (when read from a trusted source)
713  and to store certificate information associated with a private-key
714  context. Since it's not known during the import stage whether a
715  certificate in a chain will be a data-only or standard certificate
716  (it's not known which certificate is the leaf certificate until the
717  entire chain has been processed) certificate chains from a trusted
718  source are imported as data-only certificates and then the leaf has
719  its context instantiated */
720  CRYPT_CONTEXT iPubkeyContext; /* Public-key context */
721  CRYPT_ALGO_TYPE publicKeyAlgo; /* Key algorithm */
722  int publicKeyFeatures; /* Key features flags */
723  BUFFER_OPT_FIXED( publicKeyInfoSize ) \
724  void *publicKeyInfo; /* Encoded key information */
727  BYTE publicKeyID[ KEYID_SIZE + 8 ]; /* Key ID */
728 
729  /* General certificate object information */
730  DN_PTR *issuerName; /* Issuer name */
731  DN_PTR *subjectName; /* Subject name */
732  time_t startTime; /* Validity start or update time */
733  time_t endTime; /* Validity end or next update time */
734 
735  /* In theory we can just copy the subject DN of a CA certificate into
736  the issuer DN of a subject certificate, however due to broken
737  implementations this will break chaining if we correct any problems
738  in the DN. Because of this we need to preserve a copy of the
739  certificate's subject DN so that we can write it as a blob to the
740  issuer DN field of any certificates that it signs. We also need to
741  remember the encoded issuer DN so that we can chain upwards. The
742  following fields identify the size and location of the encoded DNs
743  inside the encoded certificate object */
744  BUFFER_OPT_FIXED( subjectDNsize ) \
745  void *subjectDNptr;
746  BUFFER_OPT_FIXED( issuerDNsize ) \
747  void *issuerDNptr; /* Pointer to encoded DN blobs */
748  int subjectDNsize, issuerDNsize; /* Size of encoded DN blobs */
749 
750  /* For some objects the public key and/or subject DN and/or issuer DN are
751  copied in from an external source before the object is signed so we
752  can't just point the issuerDNptr at the encoded object, we have to
753  allocate a separate data area to copy the DN into. This is used in
754  cases where we don't copy in a full subject/issuerName but only use
755  an encoded DN blob for the reasons described above */
756  BUFFER_OPT_FIXED( publicKeyInfoSize ) \
757  void *publicKeyData;
758  BUFFER_OPT_FIXED( subjectDNsize ) \
759  void *subjectDNdata;
760  BUFFER_OPT_FIXED( issuerDNsize ) \
761  void *issuerDNdata;
762 
763  /* The certificate hash/fingerprint/oobCertID/thumbprint/whatever. This
764  is used so frequently that it's cached here for future re-use */
766  BYTE certHash[ KEYID_SIZE + 8 ];/* Cached certificate hash */
767  BOOLEAN certHashSet; /* Whether hash has been set */
768 
769  /* Certificate object attributes and a cursor into the attribute list.
770  This can be moved by the user on a per-attribute, per-field, and per-
771  component basis */
772  ATTRIBUTE_PTR *attributes, *attributeCursor;
773 
774  /* The currently selected GeneralName and DN. A certificate can contain
775  multiple GeneralNames and DNs that can be selected by their field
776  types after which adding DN components will affected the currently
777  selected DN. This value contains the details of the currently
778  selected GeneralName and DN */
780 
781  /* Save area for the currently selected GeneralName and DN, and position
782  in the certificate chain. The current values are saved to this area
783  when the object receives a lock object message and restored when the
784  object receives the corresponding unlock message. This guarantees
785  that any changes made during processing while the certificate is
786  locked don't get reflected back to external users */
788 
789  /* Error information */
791  CRYPT_ERRTYPE_TYPE errorType; /* Error type */
792 
793  /* The object's handle and the handle of the user who owns this object.
794  The former is used when sending messages to the object when only the
795  xxx_INFO is available, the latter is used to avoid having to fetch the
796  same information from the system object table */
799 
800  /* Variable-length storage for the type-specific data */
802  } CERT_INFO;
803 
804 /* Certificate read/write methods for the different format types.
805  Specifying input ranges for the process gets a bit complicated because
806  the functions are polymorphic so we have to use the lowest common
807  denominator of all of the functions */
808 
810  int ( *READCERT_FUNCTION )( INOUT STREAM *stream,
812 typedef CHECK_RETVAL_FNPTR STDC_NONNULL_ARG( ( 1, 2 ) ) \
813  int ( *WRITECERT_FUNCTION )( INOUT STREAM *stream,
816  IN_HANDLE_OPT \
818 
819 CHECK_RETVAL_PTR \
820 READCERT_FUNCTION getCertReadFunction( IN_ENUM( CRYPT_CERTTYPE ) \
822 CHECK_RETVAL_PTR \
823 WRITECERT_FUNCTION getCertWriteFunction( IN_ENUM( CRYPT_CERTTYPE ) \
825 
826 /****************************************************************************
827 * *
828 * Attribute Selection Macros *
829 * *
830 ****************************************************************************/
831 
832 /* Determine whether a component which is being added to a certificate is a
833  special-case DN selection component that selects the current DN without
834  changing the certificate itself or a GeneralName selection component.
835  The latter is sufficiently complex (GeneralNames are used almost
836  everywhere in certificates where a basic text string would do) that we
837  break it out into a custom function */
838 
839 #define isDNSelectionComponent( certInfoType ) \
840  ( ( certInfoType ) == CRYPT_CERTINFO_ISSUERNAME || \
841  ( certInfoType ) == CRYPT_CERTINFO_SUBJECTNAME || \
842  ( certInfoType ) == CRYPT_CERTINFO_DIRECTORYNAME )
843 
844 CHECK_RETVAL_BOOL \
847 
848 /* Determine whether a component which is being added is a DN or GeneralName
849  component */
850 
851 #define isDNComponent( certInfoType ) \
852  ( ( certInfoType ) >= CRYPT_CERTINFO_FIRST_DN && \
853  ( certInfoType ) <= CRYPT_CERTINFO_LAST_DN )
854 
855 #define isGeneralNameComponent( certInfoType ) \
856  ( ( certInfoType ) >= CRYPT_CERTINFO_FIRST_GENERALNAME && \
857  ( certInfoType ) <= CRYPT_CERTINFO_LAST_GENERALNAME )
858 
859 /* Determine whether a component which is being added is pseudo-information
860  that corresponds to certificate control information rather than a normal
861  certificate attribute */
862 
863 #define isPseudoInformation( certInfoType ) \
864  ( ( certInfoType ) >= CRYPT_CERTINFO_FIRST_PSEUDOINFO && \
865  ( certInfoType ) <= CRYPT_CERTINFO_LAST_PSEUDOINFO )
866 
867 /* Determine whether a component which is being added to a validity/
868  revocation check request/response is a standard attribute or a per-entry
869  attribute */
870 
871 #define isRevocationEntryComponent( certInfoType ) \
872  ( ( certInfoType ) == CRYPT_CERTINFO_CRLREASON || \
873  ( certInfoType ) == CRYPT_CERTINFO_HOLDINSTRUCTIONCODE || \
874  ( certInfoType ) == CRYPT_CERTINFO_INVALIDITYDATE )
875 
876 /* Check whether an entry in an attribute list is valid. This checks
877  whether the entry has a non-zero attribute ID, denoting a non blob-type
878  attribute */
879 
880 #define isValidAttributeField( attributePtr ) \
881  ( ( attributePtr )->attributeID > 0 )
882 
883 /****************************************************************************
884 * *
885 * Certificate Functions *
886 * *
887 ****************************************************************************/
888 
889 /* The huge complexity of the certificate management code means that there
890  are a sufficient number of functions required that we confine the
891  prototypes to their own file */
892 
893 #if defined( INC_ALL )
894  #include "certfn.h"
895 #else
896  #include "cert/certfn.h"
897 #endif /* Compiler-specific includes */
898 
899 #endif /* _CERT_DEFINED */