1 /****************************************************************************
2 *																			*
3 *				cryptlib Data Size and Crypto-related Constants 			*
4 *						Copyright Peter Gutmann 1992-2012					*
5 *																			*
6 ****************************************************************************/
7 
8 #ifndef _CONSTS_DEFINED
9 
10 #define _CONSTS_DEFINED
11 
12 /* The maximum length that can be safely handled using an integer.  We don't
13    quite allow the maximum possible length since most data/message formats
14    impose some extra overhead themselves.
15 
16    In addition to the maximum-possible length we also define a shorter
17    length defined as a generally sensible upper bound for values that
18    shouldn't require arbitrary-length data quantities */
19 
20 #ifdef SYSTEM_16BIT
21   #define MAX_INTLENGTH_DELTA	8192
22 #else
23   #define MAX_INTLENGTH_DELTA	1048576
24 #endif /* 16- vs. 32/64-bit systems */
25 #define MAX_INTLENGTH			( INT_MAX - MAX_INTLENGTH_DELTA )
26 #define MAX_INTLENGTH_SHORT		16384
27 
28 /* The size of a cryptlib key ID, an SHA-1 hash of the SubjectPublicKeyInfo,
29    and the PGP key ID */
30 
31 #define KEYID_SIZE				20
32 #define	PGP_KEYID_SIZE			8
33 
34 /* The minimum and maximum private key data size.  This is used when
35    buffering the encrypted private key from a keyset during decryption and
36    is equal to the overall size of the total number of possible PKC
37    parameters in an encryption context, plus a little extra for encoding and
38    encryption */
39 
40 #define MIN_PRIVATE_KEYSIZE		18	/* For DLP keys */
41 #define MAX_PRIVATE_KEYSIZE		( ( CRYPT_MAX_PKCSIZE * 8 ) + 256 )
42 
43 /* The minimum and maximum working conventional key size in bits.  In order
44    to avoid problems with space inside PKC-encrypted blocks when MIN_PKCSIZE
45    is less than 1024 bits, we limit the total keysize to 256 bits, which is
46    adequate for all purposes - the limiting factor is AES-256 */
47 
48 #define MIN_KEYSIZE				bitsToBytes( 64 )
49 #define MAX_WORKING_KEYSIZE		bitsToBytes( 256 )
50 
51 /* The minimum public key size (c.f. CRYPT_MAX_PKCSIZE).  This is a bit less
52    than the actual size because keygen specifics can lead to keys that are
53    slightly shorter than the nominal size, and signatures and wrapped keys
54    can also be shorter (1/256 will be one byte shorter, 1/64K will be two
55    bytes shorter, and so on).  In addition we have to have a special value
56    for ECC keys, for which key sizes work differently that conventional
57    PKCs */
58 
59 #define MIN_PKCSIZE				( bitsToBytes( 1024 ) - 2 )
60 #define MIN_PKCSIZE_ECC			( bitsToBytes( 256 ) - 2 )
61 
62 /* When we read a public key, a value that's too short to be even vaguely
63    sensible is reported as CRYPT_ERROR_BADDATA, but if it's at least
64    vaguely sensible but too short to be secure it's reported as
65    CRYPT_ERROR_NOSECURE.  The following value defines the cutoff point
66    between "obviously invalid" and "theoretically valid but not secure",
67    so that 0...MIN_PKCSIZE_THRESHOLD - 1 is rejected with
68    CRYPT_ERROR_BADDATA, MIN_PKCSIZE_THRESHOLD... MIN_PKCSIZE - 1 is rejected
69    with CRYPT_ERROR_NOSECURE, and MIN_PKCSIZE...CRYPT_MAX_PKCSIZE is
70    accepted */
71 
72 #define MIN_PKCSIZE_THRESHOLD	( bitsToBytes( 504 ) )
73 #define MIN_PKCSIZE_ECC_THRESHOLD ( bitsToBytes( 120 ) )
74 
75 /* ECC points present special problems of their own since they're encoded
76    by stuffing them into byte strings with a type indicator at the start
77    which leads to a length that bears no relation to the actual key size */
78 
79 #define MIN_PKCSIZE_ECCPOINT	( 1 + ( MIN_PKCSIZE_ECC * 2 ) )
80 #define MIN_PKCSIZE_ECCPOINT_THRESHOLD \
81 								( 1 + ( MIN_PKCSIZE_ECC_THRESHOLD * 2 ) )
82 #define MAX_PKCSIZE_ECCPOINT	( 1 + ( CRYPT_MAX_PKCSIZE_ECC * 2 ) )
83 
84 /* The size of the largest public-key wrapped value, corresponding to an
85    ASN.1-encoded Elgamal-encrypted key.  If we're not using Elgamal it's
86    the same as CRYPT_MAX_PKCSIZE */
87 
88 #ifdef USE_ELGAMAL
89   #define MAX_PKCENCRYPTED_SIZE	( 16 + ( CRYPT_MAX_PKCSIZE * 2 ) )
90 #else
91   #define MAX_PKCENCRYPTED_SIZE	CRYPT_MAX_PKCSIZE
92 #endif /* USE_ELGAMAL */
93 
94 /* The maximum public-key object size.  This is used to allocate temporary
95    buffers when working with signatures and PKC-encrypted keys.  The size
96    estimate is somewhat crude and involves a fair safety margin, it usually
97    contains a single PKC object (signature or encrypted key) along with
98    algorithm and key ID information */
99 
100 #define MAX_PKC_OBJECTSIZE		( CRYPT_MAX_PKCSIZE * 2 )
101 
102 /* The minimum size of an encoded signature or exported key object.  This is
103    used by the pointer-check macros (for the OSes that support this) to
104    check that the pointers to objects that are passed to functions point to
105    the minimal amount of valid memory required for an object, and also to
106    zero the buffer for the object to ensure that the caller gets invalid
107    data if the function fails */
108 
109 #define MIN_CRYPT_OBJECTSIZE	64
110 
111 /* The minimum size of a certificate.  This is used by the pointer-check
112    macros (for the OSes that support this) to check that the pointers being
113    passed to these functions point to the minimal amount of valid memory
114    required for an object */
115 
116 #define MIN_CERTSIZE			256
117 
118 /* The maximum size of an object attribute.  In theory this can be any size,
119    but in practice we limit it to the following maximum to stop people
120    creating things like certs containing MPEGs of themselves playing with
121    their cat */
122 
123 #define MAX_ATTRIBUTE_SIZE		1024
124 
125 /* Some objects contain internal buffers used to process data whose size can
126    be specified by the user, the following is the minimum and maximum size
127    allowed for these buffers.  We don't use MAX_INTLENGTH for this both
128    because it's a peculiarly high value (using all addressable memory as a
129    buffer is a bit odd) and because using a fraction of the full INT_MAX
130    range makes it safe to perform range-based comparisons, 'value1 +
131    value2 < value3', without the risk of integer overflow */
132 
133 #define MIN_BUFFER_SIZE			8192
134 #define MAX_BUFFER_SIZE			( INT_MAX / 4 )
135 
136 /* The minimum allowed length for (typically human-readable) object names
137    (keysets, devices, users, etc).  In theory this could be a single
138    character, but by default we make it 2 chars to make things more
139    resistant to off-by-one errors in lengths, particularly since it applies
140    to external objects outside cryptlib's control.  Alongside this we also
141    define a minimum length for generic binary IDs */
142 
143 #ifdef UNICODE_CHARS
144   #define MIN_NAME_LENGTH		( 2 * sizeof( wchar_t ) )
145 #else
146   #define MIN_NAME_LENGTH		2
147 #endif /* Unicode vs. ASCII environments */
148 #define MIN_ID_LENGTH			2
149 
150 /* The minimum time value that's regarded as being a valid time (we have to
151    allow dates slightly before the current time because of things like
152    backdated cert revocations, as a rule of thumb we allow a date up to two
153    years in the past), an approximation of the current time (with the
154    constraint that it's not after the current date, unfortunately we can't
155    use any preprocessor macros for this since __DATE__ and __TIME__ are text
156    strings rather than timestamps), and a somewhat more relaxed minimum time
157    value used when reading stored data like private keys, which can contain
158    associated certificates that have been hanging around for years.  This
159    can't safely be set to after about 1995 because there are mid-90s CA root
160    certificates that are still in use today */
161 
162 #define YEARS_TO_SECONDS( years ) ( ( years ) * 365 * 86400L )
163 #define CURRENT_TIME_VALUE		( YEARS_TO_SECONDS( 2016 - 1970 ) )
164 #define MIN_TIME_VALUE			( CURRENT_TIME_VALUE - YEARS_TO_SECONDS( 2 ) )
165 #define MIN_STORED_TIME_VALUE	( YEARS_TO_SECONDS( 1995 - 1970 ) )
166 
167 /* The minimum and maximum network port numbers.  Note that we allow ports
168    down to 21 (= FTP) rather than the more obvious 22 (= SSH) provided by
169    cryptlib sessions because the URL-handling code is also used for general-
170    purpose URI parsing for which the lowest-numbered one that we'd normally
171    run into is FTP.  We set the upper bound at the end of the non-ephemeral
172    port range, 49152-65535 is for ephemeral ports that are only valid for
173    the duration of a TCP session */
174 
175 #define MIN_PORT_NUMBER			21
176 #define MAX_PORT_NUMBER			49151L
177 
178 /* Some object types interact with exteral services that can return detailed
179    error messages when problems occur, the following is the maximum length
180    error string that we store.  Anything beyond this size is truncated */
181 
182 #define MAX_ERRMSG_SIZE			512
183 
184 /* The maximum number of iterations that we allow for an iterated key setup
185    such as a hashed password.  This is used to prevent DoS attacks from data
186    containing excessive iteration counts */
187 
188 #define MAX_KEYSETUP_ITERATIONS	min( INT_MAX, 50000L )
189 
190 /* PGP's S2K uses a bizarre processing-complexity specifier that specifies,
191    in a very roundabout manner, the number of bytes hashed rather than the
192    iteration count.  In addition a number of PGP implementations specify
193    ridiculous levels of hashing that make them more akin to a DoS attack
194    than any legitimate security measure.  In theory we could recalculate the
195    above define for an assumption of an 8-byte hash salt and and 8-byte
196    password to get a value of ( ( MAX_KEYSETUP_ITERATIONS * 16 ) / 64 ),
197    with the '/ 64' term being present because what's specified is the value
198    without an additional * 64 multiplier that's added by the S2K mechanism
199    code, so we divide by 64 to account for this later scaling.  However in
200    2011 GPG raised its default hash specifier count from 64K to over 2M
201    (while still defaulting to the 15-year-old CAST5 for its block cipher, so
202    it may use an obsolete 64-bit crypto algorithm but at least it iterates
203    the password hashing enough to perform a DoS on anyone with an older
204    machine) and some configurations go even further and set it at 3407872.
205    This means that using any kind of anti-DoS check would prevent us from
206    reading newer GPG keyrings, so instead of trying to use a sane value as
207    the upper limit we hardcode in the smallest value that'll still allow us
208    to read these keyrings */
209 
210 #define MAX_KEYSETUP_HASHSPECIFIER	min( INT_MAX, ( 3407872L / 64 ) )
211 
212 /* The maximum certificate compliance level */
213 
214 #if defined( USE_CERTLEVEL_PKIX_FULL )
215   #define MAX_COMPLIANCE_LEVEL	CRYPT_COMPLIANCELEVEL_PKIX_FULL
216 #elif defined( USE_CERTLEVEL_PKIX_PARTIAL )
217   #define MAX_COMPLIANCE_LEVEL	CRYPT_COMPLIANCELEVEL_PKIX_PARTIAL
218 #else
219   #define MAX_COMPLIANCE_LEVEL	CRYPT_COMPLIANCELEVEL_STANDARD
220 #endif /* Maximum compliance level */
221 
222 /* All non-constant loops contain a guard to prevent excessive looping.
223    This is a generalisation of the programming practice that when looping on
224    externally-supplied data, we should perform a sanity check on loop
225    iterations to prevent DoS attacks due to malformed data.  The exception
226    to the guard-condition requirement is pointer-chasing loops, for which
227    (if the pointers become corrupted so the loop doesn't terminate as it
228    should) we'd segfault long before the guard would ever be reached.
229 
230    Apart from the data safety checking, this checking catches two things:
231 
232 	1. Running off the end of a lookup table.
233 
234 	2. A loop that uses a function as its terminating condition and doesn't
235 	   exit at the expected point:
236 
237 		do {
238 			term = foo();
239 		   }
240 		while( !term );
241 
242 		for( ptr = listHead; ptr != NULL; ptr = getNextValue( ptr ) );
243 
244    The following bounds on loop iterations apply:
245 
246 	FAILSAFE_SMALL: Expect 1 but can have a few more.
247 	FAILSAFE_MED: Expect 10-20 but can have a few more.
248 	FAILSAFE_LARGE: Expect many, but not too many.
249 
250   In addition to these values there's a special value FAILSAFE_MAX which
251   is equivalent to the ASN.1 (1...MAX) construct in setting an upper bound
252   on loop iterations without necessarily setting any specific limit:
253 
254 	FAILSAFE_MAX: A value that's unlikely to be reached during normal
255 				  operation, but that also won't result in an excessive
256 				  stall if it's exceeded */
257 
258 #define FAILSAFE_ITERATIONS_SMALL	10
259 #define FAILSAFE_ITERATIONS_MED		50
260 #define FAILSAFE_ITERATIONS_LARGE	1000
261 #define FAILSAFE_ITERATIONS_MAX		min( INT_MAX, 100000L )
262 
263 /* Pseudo-constants used for array bounds-checking.  These provide a more
264    precise limit than the FAILSAFE_ITERATIONS_xxx values above.  We subtract
265    one from the total count because static arrays are always overallocated
266    with two extra dummy elements at the end */
267 
268 #define FAILSAFE_ARRAYSIZE( array, elementType ) \
269 		( ( sizeof( array ) / sizeof( elementType ) ) - 1 )
270 
271 /* The minimum and maximum size of various Internet-related values, used for
272    range checking */
273 
274 #define MIN_DNS_SIZE			4			/* x.com */
275 #define MAX_DNS_SIZE			255			/* Max hostname size */
276 #define MIN_RFC822_SIZE			7			/* x@yy.zz */
277 #define MAX_RFC822_SIZE			255
278 #define MIN_URL_SIZE			12			/* http://x.com */
279 #define MAX_URL_SIZE			MAX_DNS_SIZE
280 
281 /* The HMAC input and output padding values.  These are defined here rather
282    than in context.h because they're needed by some PRF mechanisms that
283    synthesise HMAC operations from low-level hash operations */
284 
285 #define HMAC_IPAD				0x36
286 #define HMAC_OPAD				0x5C
287 
288 /* Padding in order to defeat traffic analysis is extremely problematic.
289    The simplistic approach of adding random padding provides little more
290    than warm fuzzies since it falls almost trivially to statistical
291    classifiers like Bayesian or support vector machines.  In fact almost any
292    attempt to defeat traffic analysis with low overhead, including random
293    padding, linear padding (padding to the nearest 128 bytes), exponential
294    padding (padding to the nearest power of two), mice/elephant padding
295    (padding short packets to 128 bytes and long ones to the MTU), straight
296    padding to the MTU, and padding by a random multiple of 8 or 16 bytes,
297    doesn't work (see "Peek-a-Book, I Still See You: Why Efficient Traffic
298    Analysis Countermeasures Fail" by Dyer, Coult, Ristenpart and Shrimpton).
299 
300    It's only when quite complex traffic morphing, sending fixed-length
301    packets at fixed intervals and the like, is applied and reaches an
302    overhead of 400% that things start getting tricky for an attacker, or at
303    least an attacker using a straightforward Bayesian or SVM classifier.
304 
305    This doesn't leave much choice in the way of padding, since no matter
306    what we do it won't be terribly effective.  The best option is to choose
307    the variant with the lowest overhead and use that, since it has at least
308    a small amount of effect.  This is linear padding, but we pad to 32 bytes
309    instead of 128 because we're typically used in embedded environments
310    which both use shorter messages and often have bandwidth constraints.
311 
312    Note that this value can't be set to more than 256 bytes (or in some
313    cases 255 due to one byte being needed for the length) because most
314    padding schemes only allow a single-byte pad length value */
315 
316 #define MESSAGE_PADDING_SIZE	32
317 
318 /* Generic error return code/invalid value code */
319 
320 #define CRYPT_ERROR				-1
321 
322 /* Sometimes compilers get confused about whether a variable has been
323    initialised or not and report a used-before-initialised error when there
324    isn't one.  This happens most frequently when the variable is initialised
325    as part of a conditional expression where the developer knows the control
326    flow will result in an initialisation but the compiler doesn't.  To get
327    around this we perform a dummy initialisation of the variable with a
328    symbolic value to get rid of the false positive */
329 
330 #define DUMMY_INIT				= 0
331 #define DUMMY_INIT_PTR			= NULL
332 #define DUMMY_INIT_STRUCT		= { 0 }
333 
334 /* A special return code to indicate that everything went OK but there's
335    some special action to perform.  This is generally used when a lower-level
336    routine wants to return a CRYPT_OK with some condition attached, typically
337    that the calling routine not update state information since it's already
338    been done by the returning routine or because the returning routine has
339    more work to do on a later call.  The parentheses are to catch potential
340    erroneous use in an expression */
341 
342 #define OK_SPECIAL				( -123 )
343 
344 /* When parameters get passed in messages, their mapping to parameters passed
345    to the calling function gets lost.  The following error codes are used to
346    denote errors in message parameters that are mapped to function parameter
347    error codes by the caller.  For a message call:
348 
349 	krnlSendMessage( object, {args}, MESSAGE_TYPE, value );
350 
351    we have the following possible error codes.  The parentheses are to catch
352    potential erroneous use in an expression */
353 
354 #define CRYPT_ARGERROR_OBJECT	( -100 )	/* Error in object being sent msg.*/
355 #define CRYPT_ARGERROR_VALUE	( -101 )	/* Error in message value */
356 #define CRYPT_ARGERROR_STR1		( -102 )	/* Error in first string arg */
357 #define CRYPT_ARGERROR_STR2		( -103 )	/* Error in second string arg */
358 #define CRYPT_ARGERROR_NUM1		( -104 )	/* Error in first numeric arg */
359 #define CRYPT_ARGERROR_NUM2		( -105 )	/* Error in second numeric arg */
360 
361 #define cryptArgError( status )	\
362 		( ( status ) >= CRYPT_ARGERROR_NUM2 && ( status ) <= CRYPT_ARGERROR_OBJECT )
363 #define cryptStandardError( status ) \
364 		( ( status ) >= CRYPT_ENVELOPE_RESOURCE && ( status ) <= CRYPT_OK )
365 
366 /* Network I/O is government by all sorts of timeouts.  The following are
367    the default timeout values used for network I/O, unless overridden by the
368    user */
369 
370 #define	NET_TIMEOUT_CONNECT		30
371 #define NET_TIMEOUT_READ		15
372 #define NET_TIMEOUT_WRITE		5
373 
374 /* The data formats for reading/writing public keys */
375 
376 typedef enum {
377 	KEYFORMAT_NONE,		/* No key format */
378 	KEYFORMAT_CERT,		/* X.509 SubjectPublicKeyInfo */
379 	KEYFORMAT_SSH,		/* SSHv2 public key */
380 	KEYFORMAT_SSL,		/* SSL public key */
381 	KEYFORMAT_PGP,		/* PGP public key */
382 	KEYFORMAT_PRIVATE,	/* Private key */
383 	KEYFORMAT_PRIVATE_OLD,	/* Older format for backwards-compatibility */
384 	KEYFORMAT_LAST		/* Last possible key format type */
385 	} KEYFORMAT_TYPE;
386 
387 /* The different types of actions that can be signalled to the management
388    function for each object class.  This instructs the management function
389    to initialise or shut down any object-class-specific information that it
390    may maintain */
391 
392 typedef enum {
393 	MANAGEMENT_ACTION_NONE,				/* No management action */
394 	MANAGEMENT_ACTION_PRE_INIT,			/* Pre-initialisation */
395 	MANAGEMENT_ACTION_INIT,				/* Initialisation */
396 	MANAGEMENT_ACTION_PRE_SHUTDOWN,		/* Pre-shutdown */
397 	MANAGEMENT_ACTION_SHUTDOWN,			/* Shutdown */
398 	MANAGEMENT_ACTION_LAST				/* Last possible management action */
399 	} MANAGEMENT_ACTION_TYPE;
400 
401 /* Certificate key usage types.  SIGN is for data signing and CA is for
402    certificate signing.  we don't include CRYPT_KEYUSAGE_DATAENCIPHERMENT in
403    KEYUSAGE_CRYPT since this is more or less never what's actually meant */
404 
405 #define KEYUSAGE_SIGN			( CRYPT_KEYUSAGE_DIGITALSIGNATURE | \
406 								  CRYPT_KEYUSAGE_NONREPUDIATION )
407 #define KEYUSAGE_CA				( CRYPT_KEYUSAGE_KEYCERTSIGN | \
408 								  CRYPT_KEYUSAGE_CRLSIGN )
409 #define KEYUSAGE_CRYPT			( CRYPT_KEYUSAGE_KEYENCIPHERMENT )
410 #define KEYUSAGE_KEYAGREEMENT	( CRYPT_KEYUSAGE_KEYAGREEMENT | \
411 								  CRYPT_KEYUSAGE_ENCIPHERONLY | \
412 								  CRYPT_KEYUSAGE_DECIPHERONLY )
413 
414 #endif /* _CONSTS_DEFINED */
415