1 /****************************************************************************
2 *																			*
3 *						cryptlib Test Routines Header File					*
4 *						Copyright Peter Gutmann 1995-2015					*
5 *																			*
6 ****************************************************************************/
7 
8 /* Define the following to enable/disable various blocks of tests.  Note
9    that the self-test uses a sizeable amount of automatic data, on 16-bit
10    systems it'll probably be necessary to run each test individually rather
11    than in groups as arranged below */
12 
13 #if 1
14 #define TEST_SELFTEST		/* Perform internal self-test */
15 #define TEST_LOWLEVEL		/* Test low-level functions */
16 #define TEST_RANDOM			/* Test randomness functions */
17 #define TEST_CONFIG			/* Test configuration functions */
18 #define TEST_MIDLEVEL		/* Test high-level encr/sig.functions */
19 #endif /* 0 */
20 #if 1
21 #define TEST_CERT			/* Test certificate management functions */
22 #define TEST_KEYSET			/* Test keyset read functions */
23 #define TEST_CERTPROCESS	/* Test certificate handling/CA management */
24 #endif /* 0 */
25 #if 1
26 #define TEST_HIGHLEVEL		/* Test high-level encr/sig.functions */
27 #define TEST_ENVELOPE		/* Test enveloping functions */
28 #endif /* 0 */
29 #if 1
30 #define TEST_SESSION		/* Test session functions */
31 #define TEST_SESSION_LOOPBACK/* Test session functions via local loopback */
32 /*#define TEST_USER			// Test user management functions */
33 #endif /* 0 */
34 
35 /* The crypto device tests are disabled by default since relatively few users
36    will have a crypto device set up so leaving them enabled by default would
37    just produce a cascade of device-not-present warnings */
38 
39 /* #define TEST_DEVICE /**/
40 #if defined( TEST_DEVICE )
41   #ifndef TEST_LOWLEVEL
42 	#define TEST_LOWLEVEL
43   #endif /* TEST_LOWLEVEL */
44   #ifndef TEST_ENVELOPE
45 	#define TEST_ENVELOPE
46   #endif /* TEST_ENVELOPE */
47 #endif /* Low-level and envelope tests are called by the device tests */
48 
49 /* Some of the device tests can be rather slow, the following defines disable
50    these tests for speed reasons.  Note that the Fortezza test can be further
51    cut down by not performing the CAW test (which erases any existing data on
52    the card), this is turned off by default in testdev.c */
53 
54 /* #define TEST_DEVICE_FORTEZZA */
55 
56 /* DH and KEA can't be tested because they use cryptlib-internal mechanisms,
57    however by using a custom-modified cryptlib it's possible to test at
58    least part of the DH implementation.  If the following is defined, the
59    DH key load will be tested */
60 
61 /* #define TEST_DH */
62 
63 /* To test the code under Windows CE:
64 
65 	- If PB can't start the emulator, start it manually via Tools | Configure
66 	  Platform Manager | StandardSDK Emulator | Properties | Test.
67 	- Before running the self-test for the first time, from the emulator
68 	  select Folder Sharing, share the test subdirectory, which will appear
69 	  as \\Storage Card\ (sharing it while an app is running may crash the
70 	  emulator).
71 	- If eVC++ can't connect to the emulator, enable the WCE Config toolbar,
72 	  frob all the settings (which have only one option anyway).  VC++ will
73 	  rebuild everything (with exactly the same settings as before), and
74 	  then it'll work.
75 	- Only cl32ce.dll can be run in the debugger, test32ce.exe fails with
76 	  some unknown error code.
77 	- To test the randomness polling in the emulated environment, first run
78 	  the Remote Kernel Tracker, which installs the ToolHelp DLL (this isn't
79 	  installed by default) */
80 
81 /* When commenting out code for testing, the following macro displays a
82    warning that the behaviour has been changed as well as the location of
83    the change */
84 
85 #if defined( __MVS__ ) || defined( __VMCMS__ ) || defined( __ILEC400__ )
86   #define KLUDGE_WARN( str )	\
87 			{ \
88 			char fileName[ 1000 ]; \
89 			strncpy( fileName, __FILE__, 1000 ); \
90 			fileName[ 999 ] = '\0'; \
91 			__atoe( fileName ); \
92 			fprintf( outputStream, "Kludging " str ", file %s, line %d.\n", \
93 					 fileName, __LINE__ ); \
94 			}
95 #else
96   #define KLUDGE_WARN( str )	\
97 			fprintf( outputStream, "Kludging " str ", file " __FILE__ ", \
98 					 line %d.\n", __LINE__ );
99 #endif /* ASCII vs.EBCDIC strings */
100 
101 /* Include universally-needed headers */
102 
103 #if defined( _WIN32_WCE ) && _WIN32_WCE < 400
104   #define assert( x )
105 #else
106   #include <assert.h>
107 #endif /* Systems without assert() */
108 #include <stdio.h>
109 #include <stdlib.h>
110 #include <string.h>
111 #include <time.h>
112 
113 /* Various useful types */
114 
115 #define BOOLEAN	int
116 #define BYTE	unsigned char
117 #ifndef TRUE
118   #define FALSE	0
119   #define TRUE	!FALSE
120 #endif /* TRUE */
121 
122 /* Sentinel value used to denote non-data/non-values */
123 
124 #define SENTINEL		-1000
125 
126 /* A dummy initialistion value used to deal with false-positive compiler
127    warnings */
128 
129 #ifndef DUMMY_INIT
130   #define DUMMY_INIT	= 0
131 #endif /* DUMMY_INIT */
132 
133 /* There are a few OSes broken enough not to define the standard exit codes
134    (SunOS springs to mind) so we define some sort of equivalent here just
135    in case */
136 
137 #ifndef EXIT_SUCCESS
138   #define EXIT_SUCCESS	0
139   #define EXIT_FAILURE	!EXIT_SUCCESS
140 #endif /* EXIT_SUCCESS */
141 
142 /* Although min() and max() aren't in the ANSI standard, most compilers have
143    them in one form or another, but just enough don't that we need to define
144    them ourselves in some cases */
145 
146 #if !defined( min )
147   #ifdef MIN
148 	#define min		MIN
149 	#define max		MAX
150   #else
151 	#define min( a, b )	( ( ( a ) < ( b ) ) ? ( a ) : ( b ) )
152 	#define max( a, b )	( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
153   #endif /* Various min/max macros */
154 #endif /* !min/max */
155 
156 /* If we're using a 16-bit compiler, record this */
157 
158 #if defined( __MSDOS__ ) && !defined( __MSDOS32__ )
159   #define __MSDOS16__
160 #endif /* 16-bit DOS */
161 #if defined( _MSC_VER ) && ( _MSC_VER <= 800 )
162   #define __WIN16__
163 #endif /* 16-bit Windows */
164 
165 /* It's useful to know if we're running under Windows to enable Windows-
166    specific processing */
167 
168 #if defined( _WINDOWS ) || defined( WIN32 ) || defined( _WIN32 ) || \
169 	defined( _WIN32_WCE )
170   #define __WINDOWS__
171 #endif /* _WINDOWS || WIN32 || _WIN32 */
172 
173 /* If we're running in an environment with a Unicode API, we have to be able
174    to function with both Unicode and ASCII strings */
175 
176 #ifdef __WINDOWS__
177   #if defined( _WIN32_WCE )
178 	#undef TEXT
179 	#define TEXT( x )				L ## x
180 	#define paramStrlen( x )		( wcslen( x ) * sizeof( wchar_t ) )
181 	#define paramStrcmp( x, y )		wcscmp( x, y )
182 	#define UNICODE_STRINGS
183   #elif ( defined( WIN32 ) || defined( _WIN32 ) ) && 0
184 	/* Facility to test WinCE Unicode handling under Win32 */
185 	#undef TEXT
186 	#define TEXT( x )				L ## x
187 	#define paramStrlen( x )		( wcslen( x ) * sizeof( wchar_t ) )
188 	#define paramStrcmp( x, y )		wcscmp( x, y )
189 	#define UNICODE_STRINGS
190   #else
191 	#undef TEXT						/* Already defined in windows.h */
192 	#define TEXT( x )				x
193 	#define paramStrlen( x )		strlen( x )
194 	#define paramStrcmp( x, y )		strcmp( x, y )
195   #endif /* Windows variants */
196 #else
197   #define TEXT( x )					x
198   #define paramStrlen( x )			strlen( x )
199   #define paramStrcmp( x, y )		strcmp( x, y )
200 #endif /* Unicode vs. ASCII API */
201 
202 /* In certain memory-starved environments we have to kludge things to help
203    the compiler along.  The following define tells the compiler to move BSS
204    data outside the default data segment */
205 
206 #if defined( _MSC_VER ) && ( _MSC_VER <= 800 )
207   #define FAR_BSS			far
208 #else
209   #define FAR_BSS
210 #endif /* Win16 */
211 
212 /* VS 2005 and newer warn if we use non-TR 24731 stdlib functions, since
213    this is only for the test code we disable the warnings.  In addition
214    VS in 64-bit mode warns about size_t (e.g. from calling strlen()) <->
215    int conversion */
216 
217 #if defined( _MSC_VER ) && ( _MSC_VER >= 1400 )
218   #pragma warning( disable: 4267 )	/* int <-> size_t */
219   #pragma warning( disable: 4996 )	/* Non-TR 24731 stdlib use */
220 #endif /* VC++ 2005 or newer */
221 
222 /* Format specifiers for printing time_t's */
223 
224 #if defined( _MSC_VER ) && defined( _M_X64 )
225   /* Win64, time_t is 64 bits */
226   #define TIMET_FORMAT	"%lld"
227 #elif defined( _MSC_VER ) && ( _MSC_VER >= 1700 )
228   /* VS 2012 and newer, time_t is 64 bits */
229   #define TIMET_FORMAT	"%lld"
230 #else
231   #define TIMET_FORMAT	"%ld"
232 #endif /* Environment-specific time_t size */
233 
234 /* Generic buffer size and dynamically-allocated file I/O buffer size.  The
235    generic buffer has to be of a reasonable size so that we can handle
236    S/MIME signature chains, the file buffer should be less than the 16-bit
237    INT_MAX for testing on 16-bit machines and less than 32K for testing on
238    the (16-bit DOS-derived) Watcom C 10 */
239 
240 #if defined( __MSDOS16__ ) || defined( __WIN16__ )
241   #define BUFFER_SIZE			4096
242   #define FILEBUFFER_SIZE		30000
243 #elif defined( __QNX__ ) && defined( __WATCOMC__ ) && ( __WATCOMC__ < 1100 )
244   #define BUFFER_SIZE			8192
245   #define FILEBUFFER_SIZE		30000
246 #else
247   #define BUFFER_SIZE			16384
248   #define FILEBUFFER_SIZE		40960
249 #endif /* __MSDOS__ && __TURBOC__ */
250 #define FILENAME_BUFFER_SIZE	512
251 
252 /* Explicit includes needed by Palm OS, see the comment in crypt.h for more
253    details */
254 
255 #ifdef __PALMSOURCE__
256   #include <ctype.h>
257   #include <string.h>
258 #endif /* __PALMSOURCE__ */
259 
260 /* The ability to get rid of annoying warnings via the project file in BC++
261    5.0x is completely broken, the only way to do this is via pragmas in the
262    source code */
263 
264 #if defined( __BORLANDC__ ) && ( __BORLANDC__ < 0x550 )
265   #pragma warn -ucp						/* Signed/unsigned char assignment */
266 #endif /* Broken BC++ 5.0x warning handling */
267 
268 /* Helper function to make tracking down errors on systems with no console a
269    bit less painful */
270 
271 #ifdef _WIN32_WCE
272   #define printf	wcPrintf
273   #define puts		wcPuts
274 
275   void wcPrintf( const char *format, ... );
276   void wcPuts( const char *string );
277 #endif /* Console-less environments */
278 
279 /* Try and detect OSes that have threading support, this is needed for some
280    operations like sleep calls */
281 
282 #if( ( defined( _AIX ) || defined( __APPLE__ ) || (defined( __FreeBSD__ )||defined(__DragonFly__)) || \
283 	   defined( __NetBSD__ ) || defined( __linux__ ) || \
284 	   ( defined( sun ) && ( OSVERSION > 4 ) ) ) && !defined( NO_THREADS ) )
285   #define UNIX_THREADS
286 
287   /* We need to include pthread.h at this point because any number of other
288      include files perform all sorts of peculiar and unnatural acts in order
289      to make their functions (transparently) thread-safe, triggered by the
290      detection of values defined in pthread.h.  Because of this we need to
291      include it here as a rubber chicken before other files are pulled in
292      even though it's not explicitly needed */
293   #include <pthread.h>
294 #endif /* AIX || OS/X || Linux || Slowaris */
295 #if ( defined( WIN32 ) || defined( _WIN32 ) ) && !defined( _WIN32_WCE )
296   /* We don't test the loopback functionality under WinCE because the
297 	 _beginthreadx() vs. CreateThread() issue (normally hidden in
298 	 cryptos.h) causes all sorts of problems */
299   #define WINDOWS_THREADS
300   #include <process.h>
301 #endif /* Win32 */
302 #if defined( __IBMC__ ) && defined( __OS2__ )
303   #define OS2_THREADS
304 #endif /* OS/2 */
305 
306 /* The loopback sessions require threading support so we only enable their
307    use if this is present */
308 
309 #if defined( TEST_SESSION_LOOPBACK ) && !defined( WINDOWS_THREADS )
310   #undef TEST_SESSION_LOOPBACK
311 #endif /* OSes with threading support */
312 
313 /* Define various portable data types and functions needed for the threaded
314    loopback tests */
315 
316 #if defined( WINDOWS_THREADS )
317   #define THREAD_HANDLE		HANDLE
318   #define THREAD_EXIT()		_endthreadex( 0 ); return( 0 )
319   #define THREAD_SELF()		GetCurrentThreadId()
320   typedef unsigned ( __stdcall *THREAD_FUNC )( void *arg );
321 #elif defined( UNIX_THREADS )
322   #define THREAD_HANDLE		pthread_t
323   #define THREAD_EXIT()		pthread_exit( ( void * ) 0 ); return( 0 )
324   #define THREAD_SELF()		pthread_self()
325   typedef void * ( *THREAD_FUNC )( void *arg );
326 #else
327   #define THREAD_HANDLE		int
328   #define THREAD_EXIT()
329   #define THREAD_SELF()		0
330   typedef void ( *THREAD_FUNC )( void *arg );
331 #endif /* OS-specific threading functions */
332 
333 /* The maximum number of threads that we can fire up in the multithreaded
334    tests */
335 
336 #define MAX_NO_THREADS		10
337 
338 /* Try and detect OSes that have widechar support */
339 
340 #if ( defined( __WINDOWS__ ) && \
341 	  !( defined( __WIN16__ ) || defined( __BORLANDC__ ) ) )
342   #define HAS_WIDECHAR
343 #endif /* Windows with widechar support */
344 #if defined( __linux__ ) || \
345 	( defined( sun ) && ( OSVERSION > 4 ) ) || defined( __osf__ )
346   #include <wchar.h>
347   #define HAS_WIDECHAR
348 #endif /* Unix with widechar support */
349 
350 /* If we're running on an EBCDIC system, ensure that we're compiled in
351    EBCDIC mode to test the conversion of character strings */
352 
353 #if defined( __MVS__ ) || defined( __VMCMS__ )
354   #pragma convlit( suspend )
355 #endif /* IBM big iron */
356 #if defined( __ILEC400__ )
357   #pragma convert( 0 )
358 #endif /* IBM medium iron */
359 
360 /* If we're compiling under QNX, make enums a fixed size rather than using
361    the variable-length values that the Watcom compiler defaults to */
362 
363 #if defined( __QNX__ ) && defined( __WATCOMC__ )
364   #pragma enum int
365 #endif /* QNX and Watcom C */
366 
367 /* In some cases we may want to disable the displaying of output, for example
368    if we're wrapping a lower-level test in a higher-level one.  The following
369    variable is used to control where output is sent */
370 
371 extern FILE *outputStream;
372 
373 /* Since the handling of filenames can get unwieldy when we have large
374    numbers of similar files, we use a function to map a filename template
375    and number into an actual filename rather the having to use huge
376    numbers of defines */
377 
378 #ifdef UNICODE_STRINGS
379   void filenameFromTemplate( char *buffer, const wchar_t *fileTemplate,
380 							 const int count );
381   void filenameParamFromTemplate( wchar_t *buffer,
382 								  const wchar_t *fileTemplate,
383 								  const int count );
384   const char *convertFileName( const C_STR fileName );
385 #else
386   #define filenameFromTemplate( buffer, fileTemplate, count ) \
387 		  sprintf( buffer, fileTemplate, count )
388   #define filenameParamFromTemplate( buffer, fileTemplate, count ) \
389 		  sprintf( buffer, fileTemplate, count )
390   #define convertFileName( fileName )	fileName
391 #endif /* Unicode vs. ASCII */
392 
393 /* Helper functions for limited environments that are missing full stdlib
394    support */
395 
396 #if defined( _WIN32_WCE ) && _WIN32_WCE < 500
397   int remove( const char *pathname );
398 #endif /* WinCE < 5.x */
399 
400 /* A structure that allows us to specify a collection of extension
401    components.  This is used when adding a collection of extensions to a
402    cert */
403 
404 typedef enum { IS_VOID, IS_NUMERIC, IS_STRING, IS_WCSTRING,
405 			   IS_TIME } COMPONENT_TYPE;
406 
407 typedef struct {
408 	const CRYPT_ATTRIBUTE_TYPE type;/* Extension component ID */
409 	const COMPONENT_TYPE componentType;	/* Component type */
410 	const int numericValue;			/* Value if numeric */
411 	const void *stringValue;		/* Value if string */
412 	const time_t timeValue;			/* Value if time */
413 	} CERT_DATA;
414 
415 /****************************************************************************
416 *																			*
417 *									Naming									*
418 *																			*
419 ****************************************************************************/
420 
421 /* Pull in the OS-specific file names for the test data */
422 
423 #ifdef _MSC_VER
424   #include "filename.h"
425 #else
426   #include "test/filename.h"
427 #endif /* Braindamaged MSC include handling */
428 
429 /* When we're using common code to handle a variety of key file types for
430    key read/encryption/signing tests, we need to distinguish between the
431    different key files to use.  The following types are handled in the test
432    code */
433 
434 typedef enum { KEYFILE_NONE, KEYFILE_X509, KEYFILE_X509_ALT, KEYFILE_PGP,
435 			   KEYFILE_PGP_SPECIAL, KEYFILE_OPENPGP_HASH,
436 			   KEYFILE_OPENPGP_AES, KEYFILE_OPENPGP_CAST,
437 			   KEYFILE_OPENPGP_RSA, KEYFILE_OPENPGP_MULT, KEYFILE_NAIPGP,
438 			   KEYFILE_OPENPGP_PARTIAL, KEYFILE_OPENPGP_BOUNCYCASTLE,
439 			   KEYFILE_OPENPGP_ECC
440 			 } KEYFILE_TYPE;
441 
442 /* When we're testing certificate chain handling, we need to deal with
443    various test certificates.  The following types define which test
444    certificate we're using */
445 
446 typedef enum {
447 	CHAINTEST_NOCERT,			/* No certificate */
448 	CHAINTEST_LEAF,				/* Leaf certificate */
449 	CHAINTEST_ISSUER,			/* Issuer of leaf (= intermed.CA) */
450 	CHAINTEST_ROOT,				/* Root certificate */
451 	CHAINTEST_CHAIN,			/* Full certificate chain */
452 	CHAINTEST_CHAIN_NOROOT,		/* Chain without root certificate */
453 	CHAINTEST_CHAIN_NOLEAF		/* Chain without leaf certificate */
454 	} CHAINTEST_CERT_TYPE;
455 
456 /* The generic password used for password-based encryption, and another one
457    for private key storage */
458 
459 #define TEST_PASSWORD			TEXT( "password" )
460 #define TEST_PRIVKEY_PASSWORD	TEXT( "test" )
461 
462 /* The database keyset type and name.  Under Windoze we use ODBC, for
463    anything else we use the first database which is enabled by a preprocessor
464    define, defaulting to an internal plugin (which doesn't have to be
465    available, if it's not present we continue after printing a warning) */
466 
467 #if defined( _MSC_VER )
468   #define DATABASE_KEYSET_TYPE	CRYPT_KEYSET_ODBC
469   #define CERTSTORE_KEYSET_TYPE	CRYPT_KEYSET_ODBC_STORE
470 #elif defined( DBX_DATABASE )
471   #define DATABASE_KEYSET_TYPE	CRYPT_KEYSET_DATABASE
472   #define CERTSTORE_KEYSET_TYPE	CRYPT_KEYSET_DATABASE_STORE
473 #elif defined( DBX_PLUGIN )
474   #define DATABASE_KEYSET_TYPE	CRYPT_KEYSET_PLUGIN
475   #define CERTSTORE_KEYSET_TYPE	CRYPT_KEYSET_PLUGIN_STORE
476 #else
477   #define DATABASE_KEYSET_TYPE	CRYPT_KEYSET_DATABASE
478   #define CERTSTORE_KEYSET_TYPE	CRYPT_KEYSET_DATABASE_STORE
479 #endif /* Various database backends */
480 #define DATABASE_KEYSET_NAME		TEXT( "testkeys" )
481 #define DATABASE_KEYSET_NAME_ASCII	"testkeys"
482 #define CERTSTORE_KEYSET_NAME		TEXT( "testcertstore" )
483 #define CERTSTORE_KEYSET_NAME_ASCII	"testcertstore"
484 #define DATABASE_PLUGIN_KEYSET_NAME	TEXT( "localhost:6500" )
485 #define DATABASE_PLUGIN_KEYSET_NAME_ASCII	"localhost:6500"
486 
487 /* The HTTP keyset names (actually URLs for pages containing a cert and
488    CRL).  We can't get either Verisign or Thawte root certs because both
489    require you to provide all sorts of personal information and click on a
490    legal agreement before you can download them (!!!), so we use the CAcert
491    root instead */
492 
493 #define HTTP_KEYSET_CERT_NAME	TEXT( "www.cacert.org/certs/root.der" )
494 #define HTTP_KEYSET_CRL_NAME	TEXT( "crl.verisign.com/Class1Individual.crl" )
495 #define HTTP_KEYSET_HUGECRL_NAME TEXT( "crl.verisign.com/RSASecureServer.crl" )
496 
497 /* Assorted default server names and authentication information, and the PKI
498    SRV server (redirecting to mail.cryptoapps.com:8080).  There are so many
499    TSP, OCSP, and CMP servers, and they never stay around for long, that we
500    allow remapping in the functions where the secure session tests are
501    performed */
502 
503 #define SSH_USER_NAME			TEXT( "ssh_test_user" )
504 #define SSH_PASSWORD			TEXT( "ssh_test_password" )
505 #define SSL_USER_NAME			TEXT( "ssl_test_user" )
506 #define SSL_PASSWORD			TEXT( "ssl_test_password" )
507 #define PKI_SRV_NAME			TEXT( "_pkiboot._tcp.cryptoapps.com" )
508 #define TSP_DEFAULTSERVER_NAME	TEXT( "http://timestamping.edelweb.fr/service/tsp" )
509 
510 /* Labels for the various public-key objects.  These are needed when the
511    underlying implementation creates persistent objects (eg keys held in PKCS
512    #11 tokens) that need to be identified */
513 
514 #define RSA_PUBKEY_LABEL		TEXT( "Test RSA public key" )
515 #define RSA_PRIVKEY_LABEL		TEXT( "Test RSA private key" )
516 #define RSA_BIG_PRIVKEY_LABEL	TEXT( "Test RSA big private key" )
517 #define DSA_PUBKEY_LABEL		TEXT( "Test DSA sigcheck key" )
518 #define DSA_PRIVKEY_LABEL		TEXT( "Test DSA signing key" )
519 #define ELGAMAL_PUBKEY_LABEL	TEXT( "Test Elgamal public key" )
520 #define ELGAMAL_PRIVKEY_LABEL	TEXT( "Test Elgamal private key" )
521 #define DH_KEY1_LABEL			TEXT( "Test DH key #1" )
522 #define DH_KEY2_LABEL			TEXT( "Test DH key #2" )
523 #define ECDSA_PUBKEY_LABEL		TEXT( "Test ECDSA sigcheck key" )
524 #define ECDSA_PRIVKEY_LABEL		TEXT( "Test ECDSA signing key" )
525 #define CA_PRIVKEY_LABEL		TEXT( "Test RSA private key" )
526 #define USER_PRIVKEY_LABEL		TEXT( "Test user key" )
527 #define USER_EMAIL				TEXT( "dave@wetaburgers.com" )
528 #define DUAL_SIGNKEY_LABEL		TEXT( "Test signing key" )
529 #define DUAL_ENCRYPTKEY_LABEL	TEXT( "Test encryption key" )
530 #define SYMMETRIC_KEY_LABEL		TEXT( "Test symmetric key" )
531 
532 /* The loopback address, used so that we don't inadvertently open up outside
533    ports.  In order to allow testing against non-cryptlib-loopback and/or
534    outside clients we optionally allow it to be set to an explicit address.
535    This can be either an explicit IPv4 localhost (since Windows 7 will bind
536    to both IPv4 and IPv6 INADDR_ANY addresses when given "localhost" as an
537    argument and refuses connections on the IPv4 interface, only connecting
538    on the IPv6 one), or an explicit address for external clients */
539 
540 #ifdef UNICODE_STRINGS
541   #define LOCAL_HOST_NAME			"localhost"
542   #define NATIVE_LOCAL_HOST_NAME	L"localhost"
543 #else
544   #define LOCAL_HOST_NAME			"localhost"
545   #define NATIVE_LOCAL_HOST_NAME	LOCAL_HOST_NAME
546 #endif /* UNICODE_STRINGS */
547 #if 0
548   #undef LOCAL_HOST_NAME
549   #define LOCAL_HOST_NAME			"127.0.0.1"
550 #endif /* 0 */
551 #if 0
552   #undef LOCAL_HOST_NAME
553   #define LOCAL_HOST_NAME			"192.168.1.45"
554 #endif /* 0 */
555 
556 /****************************************************************************
557 *																			*
558 *								Utility Functions							*
559 *																			*
560 ****************************************************************************/
561 
562 /* Prototypes for functions in utils.c */
563 
564 #if defined( UNIX_THREADS ) || defined( WINDOWS_THREADS ) || defined( OS2_THREADS )
565   void delayThread( const int seconds );
566 #else
567   #define delayThread( x )
568 #endif /* Systems with threading support */
569 CRYPT_ALGO_TYPE selectCipher( const CRYPT_ALGO_TYPE algorithm );
570 void printHex( const char *prefix, const BYTE *value, const int length );
571 const C_STR getKeyfileName( const KEYFILE_TYPE type,
572 							const BOOLEAN isPrivKey );
573 const C_STR getKeyfilePassword( const KEYFILE_TYPE type );
574 const C_STR getKeyfileUserID( const KEYFILE_TYPE type,
575 							  const BOOLEAN isPrivKey );
576 void printErrorAttributeInfo( const CRYPT_CERTIFICATE certificate );
577 int displayAttributes( const CRYPT_HANDLE cryptHandle );
578 int printCertInfo( const CRYPT_CERTIFICATE certificate );
579 int printCertChainInfo( const CRYPT_CERTIFICATE certChain );
580 void printExtError( const CRYPT_HANDLE cryptHandle,
581 					const char *functionName, const int functionStatus,
582 					const int lineNo );
583 int readFileData( const char *fileName, const char *description,
584 				  BYTE *buffer, const int bufSize, const int minFileSize,
585 				  const BOOLEAN silent );
586 int importCertFile( CRYPT_CERTIFICATE *cryptCert, const C_STR fileName );
587 int importCertFromTemplate( CRYPT_CERTIFICATE *cryptCert,
588 							const C_STR fileTemplate, const int number );
589 int exportCertFile( const char *fileName,
590 					const CRYPT_CERTIFICATE certificate,
591 					const CRYPT_CERTFORMAT_TYPE formatType );
592 int addCertFields( const CRYPT_CERTIFICATE certificate,
593 				   const CERT_DATA *certData, const int lineNo );
594 int checkFileAccess( void );
595 int checkNetworkAccess( void );
596 int compareData( const void *origData, const int origDataLength,
597 				 const void *recovData, const int recovDataLength );
598 int getPublicKey( CRYPT_CONTEXT *cryptContext, const C_STR keysetName,
599 				  const C_STR keyName );
600 int getPrivateKey( CRYPT_CONTEXT *cryptContext, const C_STR keysetName,
601 				   const C_STR keyName, const C_STR password );
602 void debugDump( const char *fileName, const void *data,
603 				const int dataLength );
604 int printConnectInfo( const CRYPT_SESSION cryptSession );
605 int printSecurityInfo( const CRYPT_SESSION cryptSession,
606 					   const BOOLEAN isServer,
607 					   const BOOLEAN showFingerprint,
608 					   const BOOLEAN showServerKeyInfo,
609 					   const BOOLEAN showClientCertInfo );
610 int printFingerprint( const CRYPT_SESSION cryptSession,
611 					  const BOOLEAN isServer );
612 BOOLEAN setLocalConnect( const CRYPT_SESSION cryptSession, const int port );
613 BOOLEAN isServerDown( const CRYPT_SESSION cryptSession,
614 					  const int errorStatus );
615 int activatePersistentServerSession( const CRYPT_SESSION cryptSession,
616 									 const BOOLEAN showOperationType );
617 
618 /* Threading support functions, in utils.c */
619 
620 void createMutex( void );
621 void acquireMutex( void );
622 void releaseMutex( void );
623 int waitMutex( void );
624 void destroyMutex( void );
625 #if defined( WINDOWS_THREADS )
626   void waitForThread( const HANDLE hThread );
627 #elif defined( UNIX_THREADS )
628   void waitForThread( const pthread_t hThread );
629 #else
630   void waitForThread( const int hThread );
631 #endif /* Systems with threading support */
632 int multiThreadDispatch( THREAD_FUNC clientFunction,
633 						 THREAD_FUNC serverFunction, const int noThreads );
634 
635 /* Exit with an error message, in utils.c.  attrErrorExit() prints the
636    locus and type, extErrorExit() prints the extended error code and
637    message */
638 
639 BOOLEAN attrErrorExit( const CRYPT_HANDLE cryptHandle,
640 					   const char *functionName, const int errorCode,
641 					   const int lineNumber );
642 BOOLEAN extErrorExit( const CRYPT_HANDLE cryptHandle,
643 					  const char *functionName, const int errorCode,
644 					  const int lineNumber );
645 
646 /* Prototypes for functions in certs.c */
647 
648 BOOLEAN certErrorExit( const CRYPT_HANDLE cryptHandle,
649 					   const char *functionName, const int errorCode,
650 					   const int lineNumber );
651 int setRootTrust( const CRYPT_CERTIFICATE cryptCertChain,
652 				  BOOLEAN *oldTrustValue, const BOOLEAN newTrustValue );
653 
654 /* Prototypes for functions in lowlvl.c */
655 
656 BOOLEAN loadDHKey( const CRYPT_DEVICE cryptDevice,
657 				   CRYPT_CONTEXT *cryptContext );
658 BOOLEAN loadRSAContextsEx( const CRYPT_DEVICE cryptDevice,
659 						   CRYPT_CONTEXT *cryptContext,
660 						   CRYPT_CONTEXT *decryptContext,
661 						   const C_STR cryptContextLabel,
662 						   const C_STR decryptContextLabel,
663 						   const BOOLEAN useLargeKey,
664 						   const BOOLEAN useMinimalKey );
665 BOOLEAN loadRSAContexts( const CRYPT_DEVICE cryptDevice,
666 						 CRYPT_CONTEXT *cryptContext,
667 						 CRYPT_CONTEXT *decryptContext );
668 BOOLEAN loadRSAContextsLarge( const CRYPT_DEVICE cryptDevice,
669 							  CRYPT_CONTEXT *cryptContext,
670 							  CRYPT_CONTEXT *decryptContext );
671 BOOLEAN loadDSAContextsEx( const CRYPT_DEVICE cryptDevice,
672 						   CRYPT_CONTEXT *sigCheckContext,
673 						   CRYPT_CONTEXT *signContext,
674 						   const C_STR sigCheckContextLabel,
675 						   const C_STR signContextLabel );
676 BOOLEAN loadDSAContexts( const CRYPT_DEVICE cryptDevice,
677 						 CRYPT_CONTEXT *sigCheckContext,
678 						 CRYPT_CONTEXT *signContext );
679 BOOLEAN loadElgamalContexts( CRYPT_CONTEXT *cryptContext,
680 							 CRYPT_CONTEXT *decryptContext );
681 BOOLEAN loadDHContexts( const CRYPT_DEVICE cryptDevice,
682 						CRYPT_CONTEXT *cryptContext1,
683 						CRYPT_CONTEXT *cryptContext2 );
684 BOOLEAN loadECDSAContexts( const CRYPT_DEVICE cryptDevice,
685 						   CRYPT_CONTEXT *sigCheckContext,
686 						   CRYPT_CONTEXT *signContext );
687 BOOLEAN loadECDSAContextsEx( const CRYPT_DEVICE cryptDevice,
688 							 CRYPT_CONTEXT *sigCheckContext,
689 							 CRYPT_CONTEXT *signContext,
690 							 const C_STR sigCheckContextLabel,
691 							 const C_STR signContextLabel );
692 void destroyContexts( const CRYPT_DEVICE cryptDevice,
693 					  CRYPT_CONTEXT cryptContext,
694 					  CRYPT_CONTEXT decryptContext );
695 int testLowlevel( const CRYPT_DEVICE cryptDevice,
696 				  const CRYPT_ALGO_TYPE cryptAlgo,
697 				  const BOOLEAN checkOnly );
698 int testCrypt( CRYPT_CONTEXT cryptContext, CRYPT_CONTEXT decryptContext,
699 			   const CRYPT_ALGO_TYPE cryptAlgo, BYTE *buffer,
700 			   const BOOLEAN isDevice, const BOOLEAN noWarnFail );
701 int testRSAMinimalKey( void );
702 
703 /* Prototypes for functions in envelope.c */
704 
705 int testEnvelopePKCCryptEx( const CRYPT_CONTEXT cryptContext,
706 							const CRYPT_HANDLE decryptKeyset );
707 int testCMSEnvelopeSignEx( const CRYPT_CONTEXT signContext );
708 int testCMSEnvelopePKCCryptEx( const CRYPT_HANDLE encryptContext,
709 							   const CRYPT_HANDLE decryptKeyset,
710 							   const C_STR password, const C_STR recipient );
711 
712 /* Prototypes for functions in sreqresp.c */
713 
714 int testSessionTSPServerEx( const CRYPT_CONTEXT privKeyContext );
715 
716 /* Prototypes for functions in s_scep.c */
717 
718 int pkiGetUserInfo( C_STR userID, C_STR issuePW, C_STR revPW,
719 					const C_STR userName );
720 int pkiServerInit( CRYPT_CONTEXT *cryptPrivateKey,
721 				   CRYPT_KEYSET *cryptCertStore, const C_STR keyFileName,
722 				   const C_STR keyLabel, const CERT_DATA *pkiUserData,
723 				   const CERT_DATA *pkiUserAltData,
724 				   const CERT_DATA *pkiUserCAData,
725 				   const CERT_DATA *pkiUserRAData,
726 				   const char *protocolName );
727 
728 /* Function used for testing, in cryptapi.c */
729 
730 #ifndef NDEBUG
731 
732 C_RET cryptSetFaultType( C_IN int type );
733 C_RET cryptSetMemFaultCount( C_IN int number );
734 C_RET cryptFuzzInit( C_IN CRYPT_SESSION cryptSession,
735 					 C_IN CRYPT_CONTEXT cryptContext );
736 C_RET cryptSetFuzzData( C_IN CRYPT_SESSION cryptSession,
737 						C_IN void *data, C_IN int dataLength );
738 C_RET cryptFuzzSpecial( C_IN CRYPT_CONTEXT cryptContext,
739 						C_IN void *data, C_IN int dataLength,
740 						C_IN int isServer );
741 #endif /* NDEBUG */
742 
743 /****************************************************************************
744 *																			*
745 *								Timing Support								*
746 *																			*
747 ****************************************************************************/
748 
749 /* Since high-precision timing is rather OS-dependent, we only enable this
750    under Windows or Unix where we've got guaranteed high-res timer access */
751 
752 #if ( defined( __WINDOWS__ ) && defined( _MSC_VER ) ) || \
753 	( defined( __UNIX__ ) && defined( __GNUC__ ) )
754 
755 #define USE_TIMING
756 
757 /* Normally we use 32-bit time values, however there's also (partial)
758    support for 64-bit signed values on systems that support this.  This
759    isn't normally needed though because timeDiff() deals with overflow/
760    wraparound */
761 
762 #define USE_32BIT_TIME
763 
764 #if defined( USE_32BIT_TIME )
765   typedef unsigned long HIRES_TIME;
766   #define HIRES_FORMAT_SPECIFIER	"%lX"
767 #elif defined( _MSC_VER )
768   typedef __int64 HIRES_TIME;
769   #define HIRES_FORMAT_SPECIFIER	"%llX"
770 #elif defined( __GNUC__ )
771   typedef long long HIRES_TIME;
772   #define HIRES_FORMAT_SPECIFIER	"%llX"
773 #else
774   typedef unsigned long HIRES_TIME;
775   #define HIRES_FORMAT_SPECIFIER	"%lX"
776 #endif /* 32/64-bit time values */
777 
778 /* Timing support functions.  Call as:
779 
780 	HIRES_TIME timeVal;
781 
782 	timeVal = timeDiff( 0 );
783 	function_to_time();
784 	result = ( int ) timeDiff( timeVal ); */
785 
786 HIRES_TIME timeDiff( HIRES_TIME startTime );
787 int timeDisplay( HIRES_TIME time );
788 
789 #endif /* Windows with MSVC or Unix with gcc */
790 
791 /****************************************************************************
792 *																			*
793 *								Test Functions								*
794 *																			*
795 ****************************************************************************/
796 
797 /* Prototypes for functions in highlvl.c */
798 
799 int testLargeBufferEncrypt( void );
800 int testDeriveKey( void );
801 int testRandomRoutines( void );
802 int testConventionalExportImport( void );
803 int testMACExportImport( void );
804 int testKeyExportImport( void );
805 int testSignData( void );
806 int testKeygen( void );
807 int testKeyExportImportCMS( void );
808 int testSignDataCMS( void );
809 
810 /* Prototypes for functions in devices.c */
811 
812 int testDevices( void );
813 int testUser( void );
814 
815 /* Prototypes for functions in keyfile.c */
816 
817 int testGetPGPPublicKey( void );
818 int testGetPGPPrivateKey( void );
819 int testReadWriteFileKey( void );
820 int testReadWriteAltFileKey( void );
821 int testReadWritePGPFileKey( void );
822 int testImportFileKey( void );
823 int testReadFilePublicKey( void );
824 int testAddTrustedCert( void );
825 int testAddGloballyTrustedCert( void );
826 int testDeleteFileKey( void );
827 int testChangeFileKeyPassword( void );
828 int testUpdateFileCert( void );
829 int testWriteFileCertChain( void );
830 int testWriteFileLongCertChain( void );
831 int testReadFileCert( void );
832 int testReadFileCertPrivkey( void );
833 int testReadFileCertChain( void );
834 int testReadCorruptedKey( void );
835 int testSingleStepFileCert( void );
836 int testSingleStepAltFileCert( void );
837 int testDoubleCertFile( void );
838 int testRenewedCertFile( void );
839 int testReadAltFileKey( void );
840 int testReadMiscFile( void );
841 
842 /* Prototypes for functions in keydbx.c */
843 
844 int testWriteCert( void );
845 int testReadCert( void );
846 int testKeysetQuery( void );
847 int testWriteCertDbx( void );
848 int testWriteCertLDAP( void );
849 int testReadCertLDAP( void );
850 int testReadCertURL( void );
851 int testReadCertHTTP( void );
852 
853 /* Prototypes for functions in envelope.c */
854 
855 int testEnvelopeData( void );
856 int testEnvelopeDataLargeBuffer( void );
857 int testEnvelopeCompress( void );
858 int testPGPEnvelopeCompressedDataImport( void );
859 int testEnvelopeSessionCrypt( void );
860 int testEnvelopeSessionCryptLargeBuffer( void );
861 int testEnvelopeCrypt( void );
862 int testEnvelopePasswordCrypt( void );
863 int testEnvelopePasswordCryptBoundary( void );
864 int testEnvelopePasswordCryptImport( void );
865 int testPGPEnvelopePasswordCryptImport( void );
866 int testEnvelopePKCCrypt( void );
867 int testEnvelopePKCCryptAlgo( void );
868 int testEnvelopePKCCryptMulti( void );
869 int testEnvelopePKCIterated( void );
870 int testPGPEnvelopePKCCryptImport( void );
871 int testEnvelopeSign( void );
872 int testEnvelopeSignAlgos( void );
873 int testEnvelopeSignHashUpgrade( void );
874 int testEnvelopeSignOverflow( void );
875 int testEnvelopeSignIndef( void );
876 int testPGPEnvelopeSignedDataImport( void );
877 int testEnvelopeAuthenticate( void );
878 int testEnvelopeAuthEnc( void );
879 int testCMSEnvelopePKCCrypt( void );
880 int testCMSEnvelopePKCCryptDoubleCert( void );
881 int testCMSEnvelopePKCCryptImport( void );
882 int testCMSEnvelopeSign( void );
883 int testCMSEnvelopeDualSign( void );
884 int testCMSEnvelopeDetachedSig( void );
885 int testCMSEnvelopeRefCount( void );
886 int testCMSEnvelopeSignedDataImport( void );
887 
888 /* Prototypes for functions in certs.c */
889 
890 int testBasicCert( void );
891 int testCACert( void );
892 int testXyzzyCert( void );
893 int testTextStringCert( void );
894 int testComplexCert( void );
895 int testCertExtension( void );
896 int testCustomDNCert( void );
897 int testCertAttributeHandling( void );
898 int testSETCert( void );
899 int testAttributeCert( void );
900 int testCRL( void );
901 int testComplexCRL( void );
902 int testCertChain( void );
903 int testCertRequest( void );
904 int testCertRequestAttrib( void );
905 int testComplexCertRequest( void );
906 int testCRMFRequest( void );
907 int testComplexCRMFRequest( void );
908 int testRevRequest( void );
909 int testCMSAttributes( void );
910 int testRTCSReqResp( void );
911 int testOCSPReqResp( void );
912 int testPKIUser( void );
913 int testCertImport( void );
914 int testCertImportECC( void );
915 int testCertReqImport( void );
916 int testCRLImport( void );
917 int testCertChainImport( void );
918 int testOCSPImport( void );
919 int testBase64CertImport( void );
920 int testBase64CertChainImport( void );
921 int testMiscImport( void );
922 int testNonchainCert( void );
923 int testCertComplianceLevel( void );
924 int testCertChainHandling( void );
925 int testPathProcessing( void );
926 int testPKCS1Padding( void );
927 int testCertProcess( void );
928 int testCertManagement( void );
929 
930 /* Prototypes for functions in scert.c (the EnvTSP one is actually in with
931    the enveloping code because the only way to fully exercise the TS
932    functionality is by using it to timestamp an S/MIME signature) */
933 
934 int testSessionSCEP( void );
935 int testSessionSCEPCACert( void );
936 int testSessionSCEPServer( void );
937 int testSessionCMP( void );
938 int testSessionCMPServer( void );
939 int testSessionPNPPKI( void );
940 int testSessionEnvTSP( void );
941 
942 /* Prototypes for functions in sreqresp.c */
943 
944 int testSessionHTTPCertstoreServer( void );
945 int testSessionRTCS( void );
946 int testSessionRTCSServer( void );
947 int testSessionOCSP( void );
948 int testSessionOCSPServer( void );
949 int testSessionTSP( void );
950 int testSessionTSPServer( void );
951 
952 /* Prototypes for functions in ssh.c */
953 
954 int testSessionUrlParse( void );
955 int testSessionAttributes( void );
956 int testSessionSSH( void );
957 int testSessionSSHClientCert( void );
958 int testSessionSSHPortforward( void );
959 int testSessionSSHExec( void );
960 int testSessionSSH_SFTP( void );
961 int testSessionSSHServer( void );
962 int testSessionSSH_SFTPServer( void );
963 
964 /* Prototypes for functions in ssl.c */
965 
966 int testSessionSSL( void );
967 int testSessionSSLLocalSocket( void );
968 int testSessionSSLClientCert( void );
969 int testSessionSSLServer( void );
970 int testSessionSSLServerCached( void );
971 int testSessionSSLServerClientCert( void );
972 int testSessionTLS( void );
973 int testSessionTLSLocalSocket( void );
974 int testSessionTLSSharedKey( void );
975 int testSessionTLSServer( void );
976 int testSessionTLSServerSharedKey( void );
977 int testSessionTLS11( void );
978 int testSessionTLS11Server( void );
979 int testSessionTLS12( void );
980 int testSessionTLS12Server( void );
981 int testSessionTLS12ClientCert( void );
982 int testSessionTLS12ServerClientCertManual( void );
983 
984 /* Functions to test local client/server sessions.  These require threading
985    support since they run the client and server in different threads */
986 
987 #ifdef TEST_SESSION_LOOPBACK
988   int testSessionSSHClientServer( void );
989   int testSessionSSHClientServerDsaKey( void );
990   int testSessionSSHClientServerEccKey( void );
991   int testSessionSSHClientServerFingerprint( void );
992   int testSessionSSHClientServerSFTP( void );
993   int testSessionSSHClientServerPortForward( void );
994   int testSessionSSHClientServerExec( void );
995   int testSessionSSHClientServerMultichannel( void );
996   int testSessionSSHClientServerDualThread( void );
997   int testSessionSSHClientServerMultiThread( void );
998   int testSessionSSHClientServerDebugCheck( void );
999   int testSessionSSLClientServer( void );
1000   int testSessionSSLClientCertClientServer( void );
1001   int testSessionTLSClientServer( void );
1002   int testSessionTLSSharedKeyClientServer( void );
1003   int testSessionTLSNoSharedKeyClientServer( void );
1004   int testSessionTLSBulkTransferClientServer( void );
1005   int testSessionTLS11ClientServer( void );
1006   int testSessionTLS11ClientCertClientServer( void );
1007   int testSessionTLS11ResumeClientServer( void );
1008   int testSessionTLS12ClientServer( void );
1009   int testSessionTLS12ClientServerEccKey( void );
1010   int testSessionTLS12ClientServerEcc384Key( void );
1011   int testSessionTLS12ClientCertClientServer( void );
1012   int testSessionTLS12ClientCertManualClientServer( void );
1013   int testSessionTLSClientServerDualThread( void );
1014   int testSessionTLSClientServerMultiThread( void );
1015   int testSessionSSLClientServerDebugCheck( void );
1016   int testSessionHTTPCertstoreClientServer( void );
1017   int testSessionRTCSClientServer( void );
1018   int testSessionOCSPClientServer( void );
1019   int testSessionOCSPMulticertClientServer( void );
1020   int testSessionTSPClientServer( void );
1021   int testSessionTSPClientServerPersistent( void );
1022   int testSessionSCEPClientServer( void );
1023   int testSessionSCEPSHA2ClientServer( void );
1024   int testSessionSCEPCACertClientServer( void );
1025   int testSessionSCEPRenewClientServer( void );
1026   int testSessionCMPClientServer( void );
1027   int testSessionCMPSHA2ClientServer( void );
1028   int testSessionCMPPKIBootClientServer( void );
1029   int testSessionCMPRAClientServer( void );
1030   int testSessionCMPFailClientServer( void );
1031   int testSessionPNPPKIClientServer( void );
1032   int testSessionPNPPKIDeviceClientServer( void );
1033   int testSessionPNPPKICAClientServer( void );
1034   int testSessionPNPPKIIntermedCAClientServer( void );
1035   int testSessionSuiteBClientServer( void );
1036 #endif /* TEST_SESSION_LOOPBACK */
1037 
1038 /* Umbrella tests for the above functions */
1039 
1040 BOOLEAN testSelfTest( void );
1041 BOOLEAN testLowLevel( void );
1042 BOOLEAN testRandom( void );
1043 BOOLEAN testConfig( void );
1044 BOOLEAN testDevice( void );
1045 BOOLEAN testMidLevel( void );
1046 BOOLEAN testHighLevel( void );
1047 BOOLEAN testCert( void );
1048 BOOLEAN testCertMgmt( void );
1049 BOOLEAN testKeysetFile( void );
1050 BOOLEAN testKeysetDatabase( void );
1051 BOOLEAN testEnveloping( void );
1052 BOOLEAN testSessions( void );
1053 BOOLEAN testSessionsLoopback( void );
1054 BOOLEAN testUsers( void );
1055 
1056 #if defined( __MVS__ ) || defined( __VMCMS__ )
1057   #pragma convlit( resume )
1058 #endif /* IBM big iron */
1059 #if defined( __ILEC400__ )
1060   #pragma convert( 819 )
1061 #endif /* IBM medium iron */
1062