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