1 /****************************************************************************
2 *																			*
3 *							cryptlib SSL/TLS Routines						*
4 *						Copyright Peter Gutmann 1998-2014					*
5 *																			*
6 ****************************************************************************/
7 
8 #include "cryptlib.h"
9 #include "test/test.h"
10 
11 #if defined( __MVS__ ) || defined( __VMCMS__ )
12   /* Suspend conversion of literals to ASCII. */
13   #pragma convlit( suspend )
14 #endif /* IBM big iron */
15 #if defined( __ILEC400__ )
16   #pragma convert( 0 )
17 #endif /* IBM medium iron */
18 #ifdef __WINDOWS__
19   /* For checking for debug-only capabilities */
20   #define _OSSPEC_DEFINED
21   #define VC_16BIT( version )		( version <= 800 )
22   #define VC_LE_VC6( version )		( version <= 1200 )
23   #define VC_LT_2005( version )		( version < 1400 )
24   #define VC_GE_2005( version )		( version >= 1400 )
25   #define VC_GE_2010( version )		( version >= 1600 )
26 #else
27   #define VC_16BIT( version )		0
28   #define VC_LE_VC6( version )		0
29   #define VC_LT_2005( version )		0
30   #define VC_GE_2005( version )		0
31   #define VC_GE_2010( version )		0
32 #endif /* __WINDOWS__ */
33 #ifndef NDEBUG
34   #include "misc/analyse.h"		/* Needed for fault.h */
35   #include "misc/fault.h"
36 #endif /* !NDEBUG */
37 
38 /* SSL/TLS gets a bit complicated because in the presence of the session
39    cache every session after the first one will be a resumed session.  To
40    deal with this, the VC++ 6 debug build disables the client-side session
41    cache, while every other version just ends up going through a series
42    of session resumes.
43 
44    Note that changing the follow requires an equivalent change in
45    session/ssl_cli.c */
46 
47 #if defined( __WINDOWS__ ) && defined( _MSC_VER ) && ( _MSC_VER == 1200 ) && \
48 	!defined( NDEBUG ) && 1
49   #define NO_SESSION_CACHE
50 #endif /* VC++ 6.0 debug build */
51 
52 /* We can run the SSL/TLS self-test with a large variety of options, rather
53    than using dozens of boolean option flags to control them all we define
54    various test classes that exercise each option type.
55 
56    Two of the tests aren't run as part of the normal self-test since their
57    use of random threads results in somewhat nondeterministic behaviour that
58    would require extensive extra locking to resolve.  SSL_TEST_DUALTHREAD
59    starts the SSL server with one thread and has the server session return
60    control to the caller for the password check.  The initial server thread
61    then exits and a second thread takes over for the rest of the connect.
62 
63    SSL_TEST_MULTITHREAD is just a multithreaded client and server test.
64    This is even more nondeterministic, with thread pileups possible due to
65    the lack of extensive locking on the client side.
66 
67    For SSL_TEST_CLIENTCERT against the Windows interop server, the test
68    server client-auth key needs to be converted to PKCS #15 format since it
69    uses a too-short password in the original Microsoft-provided file.  To do
70    this, in mechs/mech_drv.c, initDSP() add the following kludge:
71 
72 	*( ( int * ) &keyLength ) = 1;
73 
74    and then use the following code:
75 
76 	{
77 	CRYPT_KEYSET cryptKeyset;
78 	CRYPT_CONTEXT cryptContext;
79 
80 	cryptKeysetOpen( &cryptKeyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE,
81 					 "r:/woodgrove.p12", CRYPT_KEYOPT_READONLY );
82 	cryptGetPrivateKey( cryptKeyset, &cryptContext, CRYPT_KEYID_NAME,
83  						TEXT( "test" ), TEXT( "11" ) );
84 	cryptKeysetClose( cryptKeyset );
85 	cryptKeysetOpen( &cryptKeyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE,
86 					 TEST_PRIVKEY_TMP_FILE, CRYPT_KEYOPT_CREATE );
87 	cryptAddPrivateKey( cryptKeyset, cryptContext, TEST_PRIVKEY_PASSWORD );
88 	cryptKeysetClose( cryptKeyset );
89 	cryptDestroyContext( cryptContext );
90 	} */
91 
92 typedef enum {
93 	SSL_TEST_NORMAL,			/* Standard SSL/TLS test */
94 	SSL_TEST_BULKTRANSER,		/* Bulk data transfer */
95 	SSL_TEST_CLIENTCERT,		/* User auth.with client certificate */
96 	SSL_TEST_CLIENTCERT_MANUAL,	/* User auth.client certificate manual verif.*/
97 	SSL_TEST_PSK,				/* User auth.with shared key */
98 	SSL_TEST_PSK_SVRONLY,		/* Client = no PSK, server = TLS-PSK */
99 	SSL_TEST_PSK_CLIONLY,		/* Client = TLS-PSK, server = no PSK */
100 	SSL_TEST_PSK_WRONGKEY,		/* User auth.with incorrect shared key */
101 	SSL_TEST_ECC,				/* Use ECC instead of RSA/DH */
102 	SSL_TEST_ECC_P384,			/* Use ECC P384 instead of P256 */
103 	SSL_TEST_STARTTLS,			/* STARTTLS/STLS/AUTH TLS */
104 	SSL_TEST_RESUME,			/* Session resumption */
105 	SSL_TEST_DUALTHREAD,		/* Two-phase connect via different threads */
106 	SSL_TEST_MULTITHREAD,		/* Multiple server threads */
107 	SSL_TEST_CORRUPT_HANDSHAKE,	/* Detect corruption of handshake data */
108 	SSL_TEST_CORRUPT_DATA,		/* Detect corruption of payload data */
109 	SSL_TEST_WRONGCERT,			/* Detect wrong key for server */
110 	SSL_TEST_BADSIG_HASH,		/* Detect corruption of signed DH params */
111 	SSL_TEST_BADSIG_DATA		/* Detect corruption of signed DH params */
112 	} SSL_TEST_TYPE;
113 
114 #if defined( TEST_SESSION ) || defined( TEST_SESSION_LOOPBACK )
115 
116 /****************************************************************************
117 *																			*
118 *								SSL/TLS Routines Test						*
119 *																			*
120 ****************************************************************************/
121 
122 /* If we're using local sockets, we have to pull in the winsock defines */
123 
124 #if defined( __WINDOWS__ ) && !defined( _WIN32_WCE )
125   #include <winsock.h>
126 #endif /* __WINDOWS__ && !_WIN32_WCE */
127 
128 /* There are various servers running that we can use for testing, the
129    following remapping allows us to switch between them.  Notes:
130 
131 	Server 1: Local loopback.
132 	Server 2-4: Generic test servers at google.com (formerly amazon.com),
133 			  paypal.com, redhat.com.  There have to be three distinct
134 			  servers in order to force a full handshake rather than just
135 			  pulling a previous session out of the session cache.  In late
136 			  2014 Amazon disabled SSLv3 on all of its servers and Paypal
137 			  disabled it in early 2015, so we have to use google.com
138 			  instead of amazon.com since they currently still have it
139 			  enabled.  In addition as part of the deprecation of SHA-1 in
140 			  early 2016 Comodo, used by the Red Hat server, switched its
141 			  CA certs to SHA-384, so we need to enable the use of the
142 			  extended SHA-2 hash functions to deal with this.
143 	Server 5: ~40K data returned.  Returns an incorrect certificate for the
144 			  server when using SSL, although when accessed from a web
145 			  browser it works as expected.
146 	Server 6: Sends zero-length blocks (actually a POP server).  This server
147 			  is accessible under two names, pop.web.de and pop3.web.de,
148 			  but the certificate is for pop3.web.de.  In addition the
149 			  certificate has the host name in both the CN and
150 			  altName.domainName, allowing both code paths to be tested.
151 	Server 7: Novell GroupWise, requires CRYPT_OPTION_CERT_COMPLIANCELEVEL =
152 			  CRYPT_COMPLIANCELEVEL_OBLIVIOUS due to b0rken certs.
153 	Server 8: (Causes MAC failure during handshake when called from PMail,
154 			   works OK when called here).
155 	Server 9: Can only do crippled crypto (not even conventional crippled
156 			  crypto but RC4-56) and instead of sending an alert for this
157 			  just drops the connection (this may be caused by the NetApp
158 			  NetCache it's using).  This site is also running an Apache
159 			  server that claims it's optimised for MSIE, and that the page
160 			  won't work properly for non-MSIE browsers.  The mind
161 			  boggles...
162 	Server 10: Server ("Hitachi Web Server 02-00") can only do SSL, when
163 			   cryptlib is set to perform a TLS handshake (i.e. cryptlib is
164 			   told to expect TLS but falls back to SSL), goes through the
165 			   full handshake, then returns a handshake failure alert.  The
166 			   same occurs for other apps (e.g. MSIE) when TLS is enabled.
167 	Server 11: Buggy older IIS that can only do crippled crypto and drops
168 			   the connection as soon as it sees the client hello
169 			   advertising strong crypto only.
170 	Server 12: Newer IIS (certificate is actually for akamai.net, so the SSL
171 			   may not be Microsoft's at all).
172 	Server 13: IBM (Websphere?).
173 	Server 14: Server is running TLS with SSL disabled, drops connection
174 			   when it sees an SSL handshake.  MSIE in its default config
175 			   (TLS disabled) can't connect to this server.
176 	Server 15: GnuTLS.
177 	Server 16: GnuTLS test server with TLS 1.1.
178 	Server 17: Can only do SSLv2, server hangs when sent an SSLv3 handshake.
179 	Server 18: Can't handle TLS 1.1 handshake (drops connection).  In
180 			   addition the server returns a certificate chain leading up
181 			   to a Verisign MD2 root that gets rejected due to the use of
182 			   MD2.
183 	Server 19: Can't handle TLS 1.1 handshake (drops connection).  Both of
184 			   these servers are sitting behind NetApp NetCaches (see also
185 			   server #9), which could be the cause of the problem.
186 	Server 20: Generic OpenSSL server.
187 	Server 21: Crippled crypto using NS Server 3.6.
188 	Server 22: Apache with Thawte certs, requires
189 			   CRYPT_OPTION_CERT_COMPLIANCELEVEL =
190 			   CRYPT_COMPLIANCELEVEL_REDUCED due to b0rken certs.
191 	Server 23: Supports TLS-ext, max-fragment-size extension, session
192 			   tickets, TLS 1.2, and assorted other odds and ends, but
193 			   not ECC or GSM, reports info on connect in handy text
194 			   format.  Will also perform client-auth verification if the
195 			   client sends a client-auth message, accepting any cert and
196 			   using it to verify the handshake-data signature.
197 	Server 24: GnuTLS server supporting all sorts of oddities (PGP certs,
198 			   SRP, compression, TLS-ext, and others, see
199 			   http://www.gnu.org/software/gnutls/server.html for details),
200 			   reports info on connect in HTML table format.  Note that this
201 			   server claims to support TLS 1.2 but returns a TLS 1.1 server
202 			   hello in response to a TLS 1.2 handshake request for several
203 			   different TLS 1.2 client implementations.
204 	Server 25: Supports SNI extension and reports info on connect, can
205 			   connect to either alice.sni.velox.ch or carol.sni.velox.ch.
206 			   A connect to the default sni.velox.ch will return a
207 			   certificate-mismatch error.
208 	Server 26: Certicom server using ECDSA P256.  Returns a server cert with
209 			   a bizarro X9.62 OID with implied sub-parameters that can't be
210 			   handled (at least in a sane manner) by the AlgoID read code.
211 	Server 27: RedHat server using NSS for ECC support for ECDSA P256.  This
212 			   server doesn't support any non-ECC suites, making it useful
213 			   for testing handling of the ECC-only case.
214 	Server 28: Certicom umbrella server (see #26) that also does TLS 1.2
215 			   under very restricted circumstances (see below) and GCM.
216 			   Details at https://tls.secg.org/, transaction log at
217 			   https://tls.secg.org/index1.php?action=https_log (this log
218 			   rolls over fairly quickly, requiring opening the last several
219 			   entries and matching cipher suites to see which one was
220 			   yours).  Note that this server claims to support TLS 1.2 but
221 			   returns a TLS 1.1 server hello in response to a TLS 1.2
222 			   handshake request unless you report DHE_DSS as your only
223 			   available cipher suite.  A more standard combination like
224 			   RSA or DHE_RSA results in the server returning a TLS 1.1
225 			   response, and an attempt to force matters with a TLS 1.2-only
226 			   cipher suite like DHE_AES_GCM returns an alert message with
227 			   the version number set to SSLv3, i.e. { 3, 0 }.  This server
228 			   also has a certificate in which the CN is a combination of
229 			   the server FQDN and further text, requiring a match on the
230 			   altName even though the first part of the DN would also
231 			   match.
232 	Server 29: Microsoft interop test server that does TLS 1.2, ECC, and
233 			   unlike GnuTLS and Certicom/SECG it actually really does TLS
234 			   1.2.  This is the generic interface with all cipher suites,
235 			   see Server #30 and #31 for variants.  This server also claims
236 			   to support GCM (although only with ECC, not with RSA/DSA) but
237 			   in practice closes the connection when sent a client hello
238 			   with this cipher suite.
239 	Server 30: As Server #29 but restricted to 256-bit ECC only, this server
240 			   does actually support GCM.  Requires
241 			   CRYPT_OPTION_CERT_COMPLIANCELEVEL =
242 			   CRYPT_COMPLIANCELEVEL_OBLIVIOUS due to b0rken certs.
243 	Server 31: As server #29 but restricted to 384-bit ECC only, however it
244 			   closes the connection when sent a SHA-384 cipher suite.
245 	Server 32: As Server #29 but tests rehandshake handling.  This is
246 			   actually meant to test RSA client authentication, i.e.
247 			   SSL_TEST_CLIENTCERT, but Windows implements this by
248 			   performning a standard handshake without client-auth and then
249 			   immediately performing a rehandshake with client-auth, which
250 			   can be used to test the ability to handle a rehandshake
251 			   request.  In practice the Windows server hangs waiting for
252 			   the rehandshake, so eventually we exit with a read timeout
253 			   error.
254 	Server 33: RSA interop server, this requires a complex pre-approval
255 			   application process to enable access which makes it not worth
256 			   the bother, it's only listed here for completeness.
257 	Server 34: Encrypt-then-MAC extension support.
258 	Server 35: DHE-PSK support via PolarSSL, name = gutman,
259 			   PSK = 0x0123456789abcdef.
260 	Server 36: Returns a certificate with "outlook.com" in the CN, requires
261 			   matching the altName to find "smtp.office365.com".
262 	Server 37: Returns (deliberately) invalid DH parameters to test whether
263 			   clients check these.
264 	Server 38: As #37, 768-bit DH.
265 	Server 39: As #37, but valid 2048-bit DH.
266 	Server 40: As #37, but valid 2048-bit DH with 2048-bit DSA.
267 	Server 41: As #37, but valid 2048-bit DH with 1024-bit DSA.
268 	Server 42: As #37, but invalid (non-prime) 1024-bit DH.
269 	Server 43: Checks for SKIP-TLS vulnerability.
270 	Server 44: MiTLS reference implementation, but doesn't seem to implement
271 			   much out of the ordinary */
272 
273 #define SSL_SERVER_NO	2
274 #define TLS_SERVER_NO	3
275 #define TLS11_SERVER_NO	4	/* Use #27 for ECC, otherwise #4 */
276 #define TLS12_SERVER_NO	23	/* Options = #23, #24, #28, #29/30/31
277 							   (but see above for #24, #28, and some of
278 							   #29) */
279 #if ( SSL_SERVER_NO == TLS_SERVER_NO ) || \
280 	( SSL_SERVER_NO == TLS11_SERVER_NO ) || \
281 	( TLS_SERVER_NO == TLS11_SERVER_NO )
282   #error SSL/TLS/TLS11 servers must be distinct to avoid tests being skipped due to session cacheing
283 #endif /* Make sure that servers are distinct */
284 
285 #if ( TLS_SERVER_NO == 35 )
286   #undef SSL_USER_NAME
287   #undef SSL_PASSWORD
288   #define SSL_USER_NAME		"gutman"
289   #define SSL_PASSWORD		"\x01\x23\x45\x67\x89\xab\xcd\xef"
290 #endif /* DHE-PSK test server */
291 
292 static const struct {
293 	const C_STR name;
294 	const C_STR path;
295 	} FAR_BSS sslInfo[] = {
296 	{ NULL, NULL },
297 	/*  1 */ { TEXT( "localhost" ), "/" },
298 	/*  2 */ { TEXT( "https://www.google.com" ), "/" },
299 	/*  3 */ { TEXT( "https://www.paypal.com" ), "/" },
300 	/*  4 */ { TEXT( "https://www.redhat.com" ), "/" },
301 	/*  5 */ { TEXT( "https://www.cs.berkeley.edu" ), "/~daw/people/crypto.html" },
302 	/*  6 */ { TEXT( "pop.web.de:995" ), "/" },
303 	/*  7 */ { TEXT( "imap4-gw.uni-regensburg.de:993" ), "/" },
304 	/*  8 */ { TEXT( "securepop.t-online.de:995" ), "/" },
305 	/*  9 */ { TEXT( "https://homedir.wlv.ac.uk" ), "/" },
306 	/* 10 */ { TEXT( "https://www.horaso.com:20443" ), "/" },
307 	/* 11 */ { TEXT( "https://homedir.wlv.ac.uk" ), "/" },
308 	/* 12 */ { TEXT( "https://www.microsoft.com" ), "/" },
309 	/* 13 */ { TEXT( "https://alphaworks.ibm.com/" ), "/" },
310 	/* 14 */ { TEXT( "https://webmount.turbulent.ca/" ), "/" },
311 	/* 15 */ { TEXT( "https://www.gnutls.org/" ), "/" },
312 	/* 16 */ { TEXT( "https://www.gnutls.org:5555/" ), "/" },
313 	/* 17 */ { TEXT( "https://www.networksolutions.com/" ), "/" },
314 	/* 18 */ { TEXT( "https://olb.westpac.com.au/" ), "/" },
315 	/* 19 */ { TEXT( "https://www.hertz.com/" ), "/" },
316 	/* 20 */ { TEXT( "https://www.openssl.org/" ), "/" },
317 	/* 21 */ { TEXT( "https://secureads.ft.com/" ), "/" },
318 	/* 22 */ { TEXT( "https://mail.maine.edu/" ), "/" },
319 	/* 23 */ { TEXT( "https://www.mikestoolbox.net/" ), "/" },
320 	/* 24 */ { TEXT( "https://test.gnutls.org:5556/" ), "/" },
321 	/* 25 */ { TEXT( "https://sni.velox.ch/" ), "/" },
322 	/* 26 */ { TEXT( "https://tls.secg.org:40023/connect.php" ), "/" },
323 	/* 27 */ { TEXT( "https://ecc.fedora.redhat.com" ), "/" },
324 	/* 28 */ { TEXT( "https://tls.secg.org/" ), "/" },
325 	/* 29 */ { TEXT( "https://tls.woodgrovebank.com:25000/" ), "/" },
326 	/* 30 */ { TEXT( "https://tls.woodgrovebank.com:25002/" ), "/" },
327 	/* 31 */ { TEXT( "https://tls.woodgrovebank.com:25003/" ), "/" },
328 	/* 32 */ { TEXT( "https://tls.woodgrovebank.com:25005/" ), "/" },
329 	/* 33 */ { TEXT( "https://203.166.62.199/" ), "/" },
330 	/* 34 */ { TEXT( "https://eid.vx4.net" ), "/" },
331 	/* 35 */ { TEXT( "https://beta.polarssl.org:4433" ), "/" },
332 	/* 36 */ { TEXT( "https://smtp.office365.com" ), "/" },
333 	/* 37 */ { TEXT( "https://demo.cmrg.net/" ), "/" },
334 	/* 38 */ { TEXT( "https://dh768.tlsfun.de/" ), "/" },
335 	/* 39 */ { TEXT( "https://dh2048.tlsfun.de/" ), "/" },
336 	/* 40 */ { TEXT( "https://dh2048-dsa.tlsfun.de/" ), "/" },
337 	/* 41 */ { TEXT( "https://dh2048-dsa1024.tlsfun.de/" ), "/" },
338 	/* 42 */ { TEXT( "https://dh1024nop.tlsfun.de/" ), "/" },
339 	/* 43 */ { TEXT( "https://ht.vc:6443" ), "/" },
340 	/* 44 */ { TEXT( "https://mitls.org/" ), "/" },
341 	{ NULL, NULL }
342 	};
343 
344 /* Various servers used for STARTTLS/STLS/AUTH TLS testing.  Notes:
345 
346 	Server 1: SMTP: mailbox.ucsd.edu:25 (132.239.1.57) requires a client
347 			  certificate.
348 	Server 2: POP: pop.cae.wisc.edu:1110 (144.92.12.50) OK.
349 	Server 3: SMTP: smtpauth.cae.wisc.edu:25 (144.92.12.93) requires a
350 			  client certificate.
351 	Server 4: SMTP: send.columbia.edu:25 (128.59.59.23) returns invalid
352 			  certificate (lower compliance level to fix).
353 	Server 5: POP: pop3.myrealbox.com:110 (192.108.102.201) returns invalid
354 			  certificate (lower compliance level to fix).
355 	Server 6: Encrypted POP: securepop.t-online.de:995 (194.25.134.46)
356 			  direct SSL connect.
357 	Server 7: FTP: ftp.windsorchapel.net:21 (68.38.166.195) sends redundant
358 			  client certificate request with invalid length.
359 	Server 8: POP: webmail.chm.tu-dresden.de:110 (141.30.198.37), another
360 			  GroupWise server (see the server comments above) with b0rken
361 			  certs.
362 
363 			  To test FTP with SSL/TLS manually: Disable auto-login with
364 			  FTP, then send an RFC 2389 FEAT command to check security
365 			  facilities.  If this is supported, one of the responses will
366 			  be either AUTH SSL or AUTH TLS, use this to turn on SSL/TLS.
367 			  If FEAT isn't supported, AUTH TLS should usually work:
368 
369 				ftp -n ftp.windsorchapel.net
370 				quote feat
371 				quote auth ssl
372 
373 			  or just:
374 
375 				telnet ftp.windsorchapel.net 21
376 				auth ssl
377 
378 	Server 9: SMTP: mailer.gwdg.de:25 (134.76.10.26), sends each SSL message
379 			  as a discrete packet, providing a nice test of cryptlib's on-
380 			  demand buffer refill.
381 	Server 10: Encrypted POP: mrdo.vosn.net:995 (209.151.91.6), direct SSL
382 			   connect, sends a CA certificate which is also used for
383 			   encryption, but with no keyUsage flags set.
384 	Server 11: POP: pop.gmail.com:995 (74.125.28.109).
385 	Server 12: POP: mail.rochester.edu:995 (128.151.31.4), direct SSL
386 			   connect (also sends zero-length packets as a kludge for pre-
387 			   TLS 1.1 chosen-IV attacks).
388 	Server 13: SMTP: smtp.umn.edu:465 (134.84.119.35), direct SSL connect.
389 	Server 14: POP3: pop3.live.com:995 (65.55.172.253), direct SSL connect,
390 			   returns a malformed certificate.  Can also be accessed via
391 			   smtp.live.com, port 25 or 587 */
392 
393 #define STARTTLS_SERVER_NO	2
394 
395 typedef enum { PROTOCOL_NONE, PROTOCOL_SMTP, PROTOCOL_SMTP_DIRECT,
396 			   PROTOCOL_POP, PROTOCOL_IMAP, PROTOCOL_POP_DIRECT,
397 			   PROTOCOL_FTP
398 			 } PROTOCOL_TYPE;
399 
400 static const struct {
401 	const C_STR name;
402 	const int port;
403 	PROTOCOL_TYPE protocol;
404 	} FAR_BSS starttlsInfo[] = {
405 	{ NULL, 0 },
406 	/*  1 */ { TEXT( "132.239.1.57" ), 25, PROTOCOL_SMTP },
407 	/*  2 */ { TEXT( "144.92.12.50" ), 1110, PROTOCOL_POP },
408 	/*  3 */ { TEXT( "144.92.12.93" ), 25, PROTOCOL_SMTP },
409 	/*  4 */ { TEXT( "128.59.59.23" ), 25, PROTOCOL_SMTP },
410 	/*  5 */ { TEXT( "192.108.102.201" ), 110, PROTOCOL_POP },
411 	/*  6 */ { TEXT( "194.25.134.46" ), 995, PROTOCOL_POP_DIRECT },
412 	/*  7 */ { TEXT( "68.38.166.195" ), 21, PROTOCOL_FTP },
413 	/*  8 */ { TEXT( "141.30.198.37" ), 110, PROTOCOL_POP },
414 	/*  9 */ { TEXT( "134.76.10.26" ), 25, PROTOCOL_SMTP },
415 	/* 10 */ { TEXT( "209.151.91.6" ), 995, PROTOCOL_POP_DIRECT },
416 	/* 11 */ { TEXT( "74.125.28.109" ), 995, PROTOCOL_POP },
417 	/* 12 */ { TEXT( "128.151.31.4" ), 995, PROTOCOL_POP_DIRECT },
418 	/* 13 */ { TEXT( "134.84.119.35" ), 465, PROTOCOL_SMTP_DIRECT },
419 	/* 14 */ { TEXT( "65.55.172.253" ), 995, PROTOCOL_POP_DIRECT },
420 	{ NULL, 0 }
421 	};
422 
423 /* Special-case handling for buggy/broken/odd servers */
424 
425 #if ( SSL_SERVER_NO == 7 ) || ( TLS12_SERVER_NO == 30 ) || \
426 	( TLS12_SERVER_NO == 31 ) || ( STARTTLS_SERVER_NO == 8 )
427   #define BROKEN_SERVER_INVALID_CERT
428   #if defined( _MSC_VER ) || defined( __GNUC__ )
429  	#pragma message( "  Building with reduced compliance level for buggy SSL/TLS server." )
430   #endif /* Warn about special features enabled */
431 #endif /* Broken servers */
432 #if ( SSL_SERVER_NO == 3 )
433   #define IS_HIGHVOLUME_SERVER
434 #endif /* Servers with high result volume */
435 
436 /* If we're testing dual-thread handling of sessions, we need to provide a
437    forward declaration of the threading function since it's called from
438    within the SSL connect code */
439 
440 #ifdef WINDOWS_THREADS
441   unsigned __stdcall tlsServerDualThread2( void *dummy );
442 #endif /* WINDOWS_THREADS */
443 
444 /* Large buffer size to test bulk data transfer capability for secure
445    sessions */
446 
447 #if defined( __MSDOS16__ ) || defined( __WIN16__ )
448   #define BULKDATA_BUFFER_SIZE	20000
449 #elif defined( __WINDOWS__ ) && defined( _MSC_VER ) && ( _MSC_VER == 1200 ) && \
450 	  !defined( NDEBUG ) && 1
451   #define BULKDATA_BUFFER_SIZE	300000L
452   #define USE_TIMING			/* Report data-transfer time */
453 #else
454   #define BULKDATA_BUFFER_SIZE	300000L
455 #endif /* 16-bit VC++ */
456 
checksumData(const void * data,const int dataLength)457 static int checksumData( const void *data, const int dataLength )
458 	{
459 	const BYTE *dataPtr = data;
460 	int sum1 = 0, sum2 = 0, i;
461 
462 	/* Calculate a 16-bit Fletcher-like checksum of the data (it doesn't
463 	   really matter if it's not exactly right, as long as the behaviour is
464 	   the same for all data) */
465 	for( i = 0; i < dataLength; i++ )
466 		{
467 		sum1 += dataPtr[ i ];
468 		sum2 += sum1;
469 		}
470 
471 	return( sum2 & 0xFFFF );
472 	}
473 
handleBulkBuffer(BYTE * buffer,const BOOLEAN isInit)474 static BOOLEAN handleBulkBuffer( BYTE *buffer, const BOOLEAN isInit )
475 	{
476 	int checkSum, i;
477 
478 	/* If we're initialising the buffer, fill it with [0...256]* followed by
479 	   a checksum of the buffer contents */
480 	if( isInit )
481 		{
482 		for( i = 0; i < BULKDATA_BUFFER_SIZE - 2; i++ )
483 			buffer[ i ] = i & 0xFF;
484 		checkSum = checksumData( buffer, BULKDATA_BUFFER_SIZE - 2 );
485 		buffer[ BULKDATA_BUFFER_SIZE - 2 ] = ( checkSum >> 8 ) & 0xFF;
486 		buffer[ BULKDATA_BUFFER_SIZE - 1 ] = checkSum & 0xFF;
487 
488 		return( TRUE );
489 		}
490 
491 	/* We're being sent an initialised buffer, make sure that it's OK */
492 	for( i = 0; i < BULKDATA_BUFFER_SIZE - 2; i++ )
493 		{
494 		if( buffer[ i ] != ( i & 0xFF )	)
495 			return( FALSE );
496 		}
497 	checkSum = checksumData( buffer, BULKDATA_BUFFER_SIZE - 2 );
498 	if( buffer[ BULKDATA_BUFFER_SIZE - 2 ] != ( ( checkSum >> 8 ) & 0xFF ) || \
499 		buffer[ BULKDATA_BUFFER_SIZE - 1 ] != ( checkSum & 0xFF ) )
500 		return( FALSE );
501 
502 	return( TRUE );
503 	}
504 
505 /* Negotiate through a STARTTLS */
506 
507 #if defined( __WINDOWS__ ) && !( defined( __WIN16__ ) || defined( _WIN32_WCE ) )
508 
readLine(SOCKET netSocket,char * buffer)509 static int readLine( SOCKET netSocket, char *buffer )
510 	{
511 	int bufPos, status = CRYPT_OK;
512 
513 	for( bufPos = 0; \
514 		 status >= 0 && bufPos < 1024 && \
515 			( bufPos < 1 || buffer[ bufPos -1 ] != '\n' );
516 		 bufPos++ )
517 		status = recv( netSocket, buffer + bufPos, 1, 0 );
518 	while( bufPos > 1 && isspace( buffer[ bufPos - 1 ] ) )
519 		bufPos--;
520 	if( bufPos >= 3 )
521 		{
522 		while( bufPos > 1 && isspace( buffer[ bufPos - 1 ] ) )
523 			bufPos--;
524 		buffer[ min( bufPos, 56 ) ] = '\0';
525 		}
526 	return( bufPos );
527 	}
528 
negotiateSTARTTLS(int * protocol)529 static SOCKET negotiateSTARTTLS( int *protocol )
530 	{
531 	SOCKET netSocket;
532 	struct sockaddr_in serverAddr;
533 	char buffer[ 1024 ];
534 	int bufPos, status;
535 
536 	puts( "Negotiating SMTP/POP/IMAP/FTP session through to TLS start..." );
537 	*protocol = starttlsInfo[ STARTTLS_SERVER_NO ].protocol;
538 
539 	/* Connect to a generally-available server to test STARTTLS/STLS
540 	   functionality */
541 	memset( &serverAddr, 0, sizeof( struct sockaddr_in ) );
542 	serverAddr.sin_family = AF_INET;
543 	serverAddr.sin_port = htons( ( u_short ) starttlsInfo[ STARTTLS_SERVER_NO ].port );
544 	serverAddr.sin_addr.s_addr = inet_addr( starttlsInfo[ STARTTLS_SERVER_NO ].name );
545 	netSocket = socket( PF_INET, SOCK_STREAM, 0 );
546 	if( netSocket == INVALID_SOCKET )
547 		{
548 		printf( "Couldn't create socket, line %d.\n", __LINE__ );
549 		return( CRYPT_ERROR_FAILED );
550 		}
551 	status = connect( netSocket, ( struct sockaddr * ) &serverAddr,
552 					  sizeof( struct sockaddr_in ) );
553 	if( status == SOCKET_ERROR )
554 		{
555 		closesocket( netSocket );
556 		printf( "Couldn't connect socket, line %d.\n", __LINE__ );
557 		return( CRYPT_OK );		/* Signal non-fatal error */
558 		}
559 
560 	/* If it's a direct connect, there's nothing left to do */
561 	if( *protocol == PROTOCOL_POP_DIRECT )
562 		{
563 		*protocol = PROTOCOL_POP;
564 		return( netSocket );
565 		}
566 	if( *protocol == PROTOCOL_SMTP_DIRECT )
567 		{
568 		*protocol = PROTOCOL_SMTP;
569 		return( netSocket );
570 		}
571 
572 	/* Perform (very crude) SMTP/POP/IMAP negotiation to switch to TLS */
573 	bufPos = readLine( netSocket, buffer );
574 	if( bufPos < 3 || ( strncmp( buffer, "220", 3 ) && \
575 						strncmp( buffer, "+OK", 3 ) && \
576 						strncmp( buffer, "OK", 2 ) ) )
577 		{
578 		closesocket( netSocket );
579 		printf( "Got response '%s', line %d.\n", buffer, __LINE__ );
580 		return( CRYPT_OK );		/* Signal non-fatal error */
581 		}
582 	printf( "  Server said: '%s'\n", buffer );
583 	assert( ( *protocol == PROTOCOL_SMTP && !strncmp( buffer, "220", 3 ) ) || \
584 			( *protocol == PROTOCOL_POP && !strncmp( buffer, "+OK", 3 ) ) || \
585 			( *protocol == PROTOCOL_IMAP && !strncmp( buffer, "OK", 2 ) ) || \
586 			( *protocol == PROTOCOL_FTP && !strncmp( buffer, "220", 3 ) ) || \
587 			*protocol == PROTOCOL_NONE );
588 	switch( *protocol )
589 		{
590 		case PROTOCOL_POP:
591 			send( netSocket, "STLS\r\n", 6, 0 );
592 			puts( "  We said: 'STLS'" );
593 			break;
594 
595 		case PROTOCOL_IMAP:
596 			/* It's possible for some servers that we may need to explicitly
597 			   send a CAPABILITY command first to enable STARTTLS:
598 				a001 CAPABILITY
599 				> CAPABILITY IMAP4rev1 STARTTLS LOGINDISABLED
600 				> OK CAPABILITY completed */
601 			send( netSocket, "a001 STARTTLS\r\n", 15, 0 );
602 			puts( "  We said: 'STARTTLS'" );
603 			break;
604 
605 		case PROTOCOL_SMTP:
606 			send( netSocket, "EHLO foo.bar.com\r\n", 18, 0 );
607 			puts( "  We said: 'EHLO foo.bar.com'" );
608 			do
609 				{
610 				bufPos = readLine( netSocket, buffer );
611 				if( bufPos < 3 || strncmp( buffer, "250", 3 ) )
612 					{
613 					closesocket( netSocket );
614 					printf( "Got response '%s', line %d.\n", buffer,
615 							__LINE__ );
616 					return( CRYPT_OK );		/* Signal non-fatal error */
617 					}
618 				printf( "  Server said: '%s'\n", buffer );
619 				}
620 			while( !strncmp( buffer, "250-", 4 ) );
621 			send( netSocket, "STARTTLS\r\n", 10, 0 );
622 			puts( "  We said: 'STARTTLS'" );
623 			break;
624 
625 		case PROTOCOL_FTP:
626 			send( netSocket, "AUTH TLS\r\n", 10, 0 );
627 			puts( "  We said: 'AUTH TLS'" );
628 			break;
629 
630 		default:
631 			assert( FALSE );
632 		}
633 	bufPos = readLine( netSocket, buffer );
634 	if( bufPos < 3 || ( strncmp( buffer, "220", 3 ) && \
635 						strncmp( buffer, "+OK", 3 ) && \
636 						strncmp( buffer, "OK", 2 ) && \
637 						strncmp( buffer, "234", 3 ) ) )
638 		{
639 		printf( "Got response '%s', line %d.\n", buffer, __LINE__ );
640 		return( CRYPT_OK );		/* Signal non-fatal error */
641 		}
642 	printf( "  Server said: '%s'\n", buffer );
643 	return( netSocket );
644 	}
645 #endif /* Win32 */
646 
647 /* Establish an SSL/TLS session */
648 
connectSSLTLS(const CRYPT_SESSION_TYPE sessionType,const SSL_TEST_TYPE testType,const int version,const int sessionID,const BOOLEAN localSession)649 static int connectSSLTLS( const CRYPT_SESSION_TYPE sessionType,
650 						  const SSL_TEST_TYPE testType, const int version,
651 						  const int sessionID, const BOOLEAN localSession )
652 	{
653 	CRYPT_SESSION cryptSession;
654 	const BOOLEAN isServer = ( sessionType == CRYPT_SESSION_SSL_SERVER ) ? \
655 							   TRUE : FALSE;
656 	const BOOLEAN isErrorTest = ( testType >= SSL_TEST_CORRUPT_HANDSHAKE && \
657 								  testType <= SSL_TEST_BADSIG_DATA ) ? \
658 								  TRUE : FALSE;
659 	const char *versionStr[] = { "SSLv3", "TLS 1.0", "TLS 1.1", "TLS 1.2", "TLS 1.3" };
660 	const C_STR serverName = ( testType == SSL_TEST_STARTTLS ) ? \
661 								starttlsInfo[ STARTTLS_SERVER_NO ].name : \
662 							 ( version == 0 ) ? \
663 								sslInfo[ SSL_SERVER_NO ].name : \
664 							 ( version == 1 ) ? \
665 								sslInfo[ TLS_SERVER_NO ].name : \
666 							 ( version == 2 ) ? \
667 								sslInfo[ TLS11_SERVER_NO ].name : \
668 								sslInfo[ TLS12_SERVER_NO ].name;
669 	BYTE *bulkBuffer = NULL;	/* Needed for bogus uninit-value warnings */
670 #if defined( __WINDOWS__ ) && !( defined( __WIN16__ ) || defined( _WIN32_WCE ) )
671 	SOCKET netSocket;
672 #endif /* Win32 */
673 #ifdef USE_TIMING
674 	HIRES_TIME timeVal;
675 #endif /* USE_TIMING */
676 	char buffer[ FILEBUFFER_SIZE ];
677 #ifdef BROKEN_SERVER_INVALID_CERT
678 	int complianceLevel;
679 #endif /* SSL servers with b0rken certs */
680 	int bytesCopied, protocol = PROTOCOL_SMTP, status;
681 
682 	/* If this is a local session, synchronise the client and server */
683 	if( localSession )
684 		{
685 		if( isServer )
686 			{
687 			/* Acquire the init mutex */
688 			acquireMutex();
689 			}
690 		else
691 			{
692 			/* We're the client, wait for the server to finish initialising */
693 			if( waitMutex() == CRYPT_ERROR_TIMEOUT )
694 				{
695 				printf( "Timed out waiting for server to initialise, "
696 						"line %d.\n", __LINE__ );
697 				return( FALSE );
698 				}
699 			}
700 		}
701 
702 	/* If this is the dual-thread server test and we're the second server
703 	   thread, skip the portions that have already been handled by the first
704 	   thread */
705 #ifdef WINDOWS_THREADS
706 	if( isServer && testType == SSL_TEST_DUALTHREAD && sessionID == 0 )
707 		goto dualThreadContinue;
708 #endif /* WINDOWS_THREADS */
709 
710 	if( sessionID != CRYPT_UNUSED )
711 		printf( "%02d: ", sessionID );
712 	printf( "%sTesting %s%s session%s...\n", isServer ? "SVR: " : "",
713 			localSession ? "local " : "", versionStr[ version ],
714 			( testType == SSL_TEST_CLIENTCERT ) ? " with client certs" : \
715 			( testType == SSL_TEST_CLIENTCERT_MANUAL ) ? " with manual verification of client cert" : \
716 			( testType == SSL_TEST_STARTTLS ) ? " with local socket" : \
717 			( testType == SSL_TEST_BULKTRANSER ) ? " for bulk data transfer" : \
718 			( testType == SSL_TEST_PSK ) ? " with shared key" : \
719 			( testType == SSL_TEST_PSK_CLIONLY ) ? " with client-only PSK" : \
720 			( testType == SSL_TEST_PSK_SVRONLY ) ? " with server-only PSK" : \
721 			( testType == SSL_TEST_ECC ) ? " with P256 ECC crypto" : \
722 			( testType == SSL_TEST_ECC_P384 ) ? " with P384 ECC crypto" : \
723 			isErrorTest ? " with checking for error handling" : "" );
724 	if( !isServer && !localSession )
725 		printf( "  Remote host: %s.\n", serverName );
726 
727 	/* Create the SSL/TLS session */
728 	status = cryptCreateSession( &cryptSession, CRYPT_UNUSED, sessionType );
729 	if( status == CRYPT_ERROR_PARAM3 )	/* SSL/TLS session access not available */
730 		return( CRYPT_ERROR_NOTAVAIL );
731 	if( cryptStatusError( status ) )
732 		{
733 		printf( "cryptCreateSession() failed with error code %d, line %d.\n",
734 				status, __LINE__ );
735 		return( FALSE );
736 		}
737 	status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_VERSION,
738 								version );
739 	if( cryptStatusError( status ) )
740 		{
741 		cryptDestroySession( cryptSession );
742 		if( version == 0 )
743 			{
744 			puts( "  (Couldn't enable use of SSLv3, continuing on the "
745 				  "assumption that it's\n   disabled in this build)." );
746 			return( TRUE );
747 			}
748 		printf( "cryptSetAttribute() failed with error code %d, line %d.\n",
749 				status, __LINE__ );
750 		return( FALSE );
751 		}
752 #ifndef NDEBUG
753 	if( isServer && isErrorTest )
754 		{
755 		cryptSetFaultType( ( testType == SSL_TEST_CORRUPT_HANDSHAKE ) ? \
756 							 FAULT_SESSION_CORRUPT_HANDSHAKE : \
757 						   ( testType == SSL_TEST_CORRUPT_DATA ) ? \
758 							 FAULT_SESSION_CORRUPT_DATA : \
759 						   ( testType == SSL_TEST_WRONGCERT ) ? \
760 							 FAULT_SESSION_WRONGCERT : \
761 						   ( testType == SSL_TEST_BADSIG_HASH ) ? \
762 							 FAULT_SESSION_BADSIG_HASH : \
763 						   ( testType == SSL_TEST_BADSIG_DATA ) ? \
764 							 FAULT_SESSION_BADSIG_DATA : FAULT_NONE );
765 		}
766 #endif /* !NDEBUG */
767 
768 	/* If we're doing a bulk data transfer, set up the necessary buffer */
769 	if( testType == SSL_TEST_BULKTRANSER )
770 		{
771 		if( ( bulkBuffer = malloc( BULKDATA_BUFFER_SIZE ) ) == NULL )
772 			{
773 			printf( "Failed to allocated %ld bytes, line %d.\n",
774 					BULKDATA_BUFFER_SIZE, __LINE__ );
775 			return( FALSE );
776 			}
777 		if( isServer )
778 			handleBulkBuffer( bulkBuffer, TRUE );
779 		}
780 
781 	/* Set up the server information and activate the session */
782 	if( isServer )
783 		{
784 		CRYPT_CONTEXT privateKey;
785 
786 		if( !setLocalConnect( cryptSession, 443 ) )
787 			return( FALSE );
788 		if( testType != SSL_TEST_PSK && \
789 			testType != SSL_TEST_PSK_SVRONLY && \
790 			testType != SSL_TEST_DUALTHREAD )
791 			{
792 			char filenameBuffer[ FILENAME_BUFFER_SIZE ];
793 #ifdef UNICODE_STRINGS
794 			wchar_t wcBuffer[ FILENAME_BUFFER_SIZE ];
795 #endif /* UNICODE_STRINGS */
796 			void *fileNamePtr = filenameBuffer;
797 
798 			/* We don't add a private key if we're doing TLS-PSK, to test
799 			   TLS-PSK's abiltiy to work without a PKC */
800 			if( testType == SSL_TEST_ECC || testType == SSL_TEST_ECC_P384 )
801 				{
802 				filenameFromTemplate( filenameBuffer,
803 									  SERVER_ECPRIVKEY_FILE_TEMPLATE,
804 									  ( testType == SSL_TEST_ECC_P384 ) ? \
805 										384 : 256 );
806 				}
807 			else
808 				{
809 				filenameFromTemplate( filenameBuffer,
810 									  SERVER_PRIVKEY_FILE_TEMPLATE, 1 );
811 				}
812 #ifdef UNICODE_STRINGS
813 			mbstowcs( wcBuffer, filenameBuffer,
814 					  strlen( filenameBuffer ) + 1 );
815 			fileNamePtr = wcBuffer;
816 #endif /* UNICODE_STRINGS */
817 			status = getPrivateKey( &privateKey, fileNamePtr,
818 									USER_PRIVKEY_LABEL,
819 									TEST_PRIVKEY_PASSWORD );
820 			if( cryptStatusOK( status ) )
821 				{
822 				status = cryptSetAttribute( cryptSession,
823 											CRYPT_SESSINFO_PRIVATEKEY,
824 											privateKey );
825 				cryptDestroyContext( privateKey );
826 				}
827 			}
828 		if( cryptStatusOK( status ) && testType == SSL_TEST_CLIENTCERT )
829 			{
830 			CRYPT_KEYSET cryptKeyset;
831 
832 			status = cryptKeysetOpen( &cryptKeyset, CRYPT_UNUSED,
833 								DATABASE_KEYSET_TYPE, DATABASE_KEYSET_NAME,
834 								CRYPT_KEYOPT_READONLY );
835 			if( cryptStatusError( status ) )
836 				{
837 				printf( "SVR: Client certificate keyset open failed with error "
838 						"code %d, line %d.\n", status, __LINE__ );
839 				return( FALSE );
840 				}
841 			status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_KEYSET,
842 										cryptKeyset );
843 			cryptKeysetClose( cryptKeyset );
844 			}
845 		if( cryptStatusOK( status ) && testType == SSL_TEST_CLIENTCERT_MANUAL )
846 			{
847 			status = cryptSetAttribute( cryptSession,
848 										CRYPT_SESSINFO_SSL_OPTIONS,
849 										CRYPT_SSLOPTION_MANUAL_CERTCHECK );
850 			}
851 		}
852 	else
853 		{
854 		/* We're the client */
855 		if( testType == SSL_TEST_STARTTLS )
856 			{
857 			/* Testing this fully requires a lot of OS-specific juggling so
858 			   unless we're running under Windows we just supply the handle
859 			   to stdin, which will return a read/write error during the
860 			   connect.  This checks that the handle has been assigned
861 			   corectly without requiring a lot of OS-specific socket
862 			   handling code.  Under Windows, we use a (very cut-down) set
863 			   of socket calls to set up a minimal socket.  Since there's
864 			   very little error-checking done, we don't treat a failure
865 			   as fatal */
866 #if defined( __WINDOWS__ ) && !( defined( __WIN16__ ) || defined( _WIN32_WCE ) )
867 			WSADATA wsaData;
868 
869 			if( WSAStartup( 2, &wsaData ) )
870 				{
871 				printf( "Couldn't initialise sockets interface, line %d.\n",
872 						__LINE__ );
873 				return( FALSE );
874 				}
875 
876 			/* Try and negotiate a STARTTLS session.  Since the socket type
877 			   can be unsigned, we have to force it to signed to perform the
878 			   error check on it.
879 
880 			   We don't treat most types of failure as fatal since there are
881 			   a great many minor things that can go wrong that we don't
882 			   want to have to handle without writing half an MUA */
883 			netSocket = negotiateSTARTTLS( &protocol );
884 			if( ( signed ) netSocket <= 0 )
885 				{
886 				cryptDestroySession( cryptSession );
887 				WSACleanup();
888 				if( netSocket == CRYPT_OK )
889 					{
890 					puts( "This is a nonfatal error (a great many other "
891 						  "things can go wrong while\nnegotiating through "
892 						  "to the TLS upgrade).\n" );
893 					return( TRUE );
894 					}
895 				if( testType == SSL_TEST_BULKTRANSER )
896 					free( bulkBuffer );
897 				return( FALSE );
898 				}
899 
900 			/* Hand the socket to cryptlib */
901   #if defined( _MSC_VER ) && defined( _M_X64 )
902 			status = cryptSetAttribute( cryptSession,
903 							CRYPT_SESSINFO_NETWORKSOCKET, ( int ) netSocket );
904   #else
905 			status = cryptSetAttribute( cryptSession,
906 							CRYPT_SESSINFO_NETWORKSOCKET, netSocket );
907   #endif /* 32- vs. 64-bit Windows */
908 #elif defined( DDNAME_IO )
909 			/* The fileno() function doesn't work for DDNAMEs */
910 			status = cryptSetAttribute( cryptSession,
911 							CRYPT_SESSINFO_NETWORKSOCKET, 0 );
912 #elif defined( __WIN16__ ) || defined( _WIN32_WCE )
913 			status = cryptSetAttribute( cryptSession,
914 							CRYPT_SESSINFO_NETWORKSOCKET, 1 );
915 #else
916 			status = cryptSetAttribute( cryptSession,
917 							CRYPT_SESSINFO_NETWORKSOCKET, fileno( stdin ) );
918 #endif /* OS-specific local socket handling */
919 			}
920 		else
921 			{
922 			if( localSession )
923 				{
924 				if( !setLocalConnect( cryptSession, 443 ) )
925 					{
926 					if( testType == SSL_TEST_BULKTRANSER )
927 						free( bulkBuffer );
928 					return( FALSE );
929 					}
930 				if( LOCAL_HOST_NAME[ 0 ] != 'l' )
931 					{
932 					/* We're performing a connect to the local host under a
933 					   name other than "localhost", disable host-name
934 					   verification */
935 					cryptSetAttribute( cryptSession, CRYPT_SESSINFO_SSL_OPTIONS,
936 									   CRYPT_SSLOPTION_DISABLE_NAMEVERIFY );
937 					}
938 				}
939 			else
940 				{
941 				status = cryptSetAttributeString( cryptSession,
942 								CRYPT_SESSINFO_SERVER_NAME, serverName,
943 								paramStrlen( serverName ) );
944 				}
945 			}
946 		if( cryptStatusOK( status ) && \
947 			( testType == SSL_TEST_CLIENTCERT || \
948 			  testType == SSL_TEST_CLIENTCERT_MANUAL ) )
949 			{
950 			CRYPT_CONTEXT privateKey;
951 
952 			/* Depending on which server we're testing against we need to
953 			   use different private keys */
954 #if ( TLS12_SERVER_NO == 30 && 0 )
955 			getPrivateKey( &privateKey, SSL_CLI_PRIVKEY_FILE,
956 				"cc47650c403654f6fe439e5c88a2e6c2_66335081-ee61-4aa8-862d-a423d58",
957 				TEST_PRIVKEY_PASSWORD );
958 #else
959 			status = getPrivateKey( &privateKey, USER_PRIVKEY_FILE,
960 								USER_PRIVKEY_LABEL, TEST_PRIVKEY_PASSWORD );
961 #endif /* Different keys for different servers */
962 			if( cryptStatusOK( status ) )
963 				{
964 				CRYPT_KEYSET cryptKeyset;
965 				int localStatus;
966 
967 				status = cryptSetAttribute( cryptSession,
968 								CRYPT_SESSINFO_PRIVATEKEY, privateKey );
969 
970 				/* In addition to adding the key to the session, we also try
971 				   adding it to the server's key database in case it's not
972 				   present yet */
973 				localStatus = cryptKeysetOpen( &cryptKeyset, CRYPT_UNUSED,
974 								DATABASE_KEYSET_TYPE, DATABASE_KEYSET_NAME,
975 								CRYPT_KEYOPT_NONE );
976 				if( cryptStatusOK( localStatus ) )
977 					{
978 					localStatus = cryptAddPublicKey( cryptKeyset,
979 													 privateKey );
980 					cryptKeysetClose( cryptKeyset );
981 					if( cryptStatusError( localStatus ) && \
982 						localStatus != CRYPT_ERROR_DUPLICATE )
983 						{
984 						/* The key isn't already present (or we'd get a
985 						   CRYPT_ERROR_DUPLICATE), but also couldn't be
986 						   added, there's some sort of problem */
987 						printf( "Attempt to add client certificate to server "
988 								"access-control database failed\n  with "
989 								"error code %d, line %d.\n", localStatus,
990 								__LINE__ );
991 						return( FALSE );
992 						}
993 					}
994 				cryptDestroyContext( privateKey );
995 				}
996 			}
997 #if 0	/* Optional proxy for net access */
998 		status = cryptSetAttributeString( CRYPT_UNUSED,
999 								CRYPT_OPTION_NET_HTTP_PROXY, "[Autodetect]",
1000 								12 );
1001 #endif /* 0 */
1002 		}
1003 	if( cryptStatusOK( status ) && \
1004 		( testType == SSL_TEST_PSK || \
1005 		  ( isServer && testType == SSL_TEST_PSK_SVRONLY ) || \
1006 		  ( !isServer && testType == SSL_TEST_PSK_CLIONLY ) ) )
1007 		{
1008 		/* If we're testing the no-PSK handling, only the server is
1009 		   expecting TLS-PSK, so the client isn't supplied with a
1010 		   password */
1011 		if( cryptStatusOK( status ) && isServer && testType == SSL_TEST_PSK )
1012 			{
1013 			/* If we're testing PSK, add several preceding usernames and
1014 			   passwords */
1015 			cryptSetAttributeString( cryptSession,
1016 								CRYPT_SESSINFO_USERNAME, TEXT( "before1" ),
1017 								paramStrlen( TEXT( "before1" ) ) );
1018 			cryptSetAttributeString( cryptSession,
1019 								CRYPT_SESSINFO_PASSWORD, TEXT( "before1" ),
1020 								paramStrlen( TEXT( "before1" ) ) );
1021 			cryptSetAttributeString( cryptSession,
1022 								CRYPT_SESSINFO_USERNAME, TEXT( "before2" ),
1023 								paramStrlen( TEXT( "before2" ) ) );
1024 			cryptSetAttributeString( cryptSession,
1025 								CRYPT_SESSINFO_PASSWORD, TEXT( "before2" ),
1026 								paramStrlen( TEXT( "before2" ) ) );
1027 			}
1028 		status = cryptSetAttributeString( cryptSession,
1029 								CRYPT_SESSINFO_USERNAME, SSL_USER_NAME,
1030 								paramStrlen( SSL_USER_NAME ) );
1031 		if( cryptStatusOK( status ) )
1032 			{
1033 			status = cryptSetAttributeString( cryptSession,
1034 								CRYPT_SESSINFO_PASSWORD, SSL_PASSWORD,
1035 								paramStrlen( SSL_PASSWORD ) );
1036 			}
1037 		if( cryptStatusOK( status ) && isServer && testType == SSL_TEST_PSK )
1038 			{
1039 			/* If we're testing PSK, add several succeeding usernames and
1040 			   passwords */
1041 			cryptSetAttributeString( cryptSession,
1042 								CRYPT_SESSINFO_USERNAME, TEXT( "after1" ),
1043 								paramStrlen( TEXT( "after1" ) ) );
1044 			cryptSetAttributeString( cryptSession,
1045 								CRYPT_SESSINFO_PASSWORD, TEXT( "after1" ),
1046 								paramStrlen( TEXT( "after1" ) ) );
1047 			cryptSetAttributeString( cryptSession,
1048 								CRYPT_SESSINFO_USERNAME, TEXT( "after2" ),
1049 								paramStrlen( TEXT( "after2" ) ) );
1050 			cryptSetAttributeString( cryptSession,
1051 								CRYPT_SESSINFO_PASSWORD, TEXT( "after2" ),
1052 								paramStrlen( TEXT( "after2" ) ) );
1053 			}
1054 		}
1055 	if( cryptStatusError( status ) )
1056 		{
1057 		if( testType == SSL_TEST_STARTTLS )
1058 			{
1059 #if defined( __WINDOWS__ ) && !( defined( __WIN16__ ) || defined( _WIN32_WCE ) )
1060 			closesocket( netSocket );
1061 			WSACleanup();
1062 #else
1063 			/* Creating a socket in a portable manner is too difficult so
1064 			   we've passed in a stdio handle, this should return an error
1065 			   since it's not a blocking socket */
1066 			return( TRUE );
1067 #endif /* __WINDOWS__ && !_WIN32_WCE */
1068 			}
1069 		printf( "cryptSetAttribute/AttributeString() failed with error code "
1070 				"%d, line %d.\n", status, __LINE__ );
1071 		if( testType == SSL_TEST_BULKTRANSER )
1072 			free( bulkBuffer );
1073 		return( FALSE );
1074 		}
1075 #ifdef BROKEN_SERVER_INVALID_CERT
1076 	puts( "(Setting certificate compliance level to oblivious to deal with "
1077 		  "broken server)." );
1078 	cryptGetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL,
1079 					   &complianceLevel );
1080 	cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL,
1081 					   CRYPT_COMPLIANCELEVEL_OBLIVIOUS );
1082 #endif /* SSL servers with b0rken certs */
1083 #ifdef BROKEN_SERVER_WRONG_CERT
1084 	puts( "(Disabling certificate name checking to deal with broken "
1085 		  "server)." );
1086 	cryptSetAttribute( cryptSession, CRYPT_SESSINFO_SSL_OPTIONS,
1087 					   CRYPT_SSLOPTION_DISABLE_NAMEVERIFY );
1088 #endif /* SSL servers with the wrong cert for the domain */
1089 	if( localSession )
1090 		{
1091 		/* If we're running a local loopback test, display additional
1092 		   information indicating when the session is activated, since
1093 		   the multithreaded tests may not get to this point until long
1094 		   after the threads are started */
1095 		if( sessionID != CRYPT_UNUSED )
1096 			printf( "%02d: ", sessionID );
1097 		printf( "%sActivating %s session...\n", isServer ? "SVR: " : "",
1098 				versionStr[ version ] );
1099 
1100 		/* For the loopback test we also increase the connection timeout to
1101 		   a higher-than-normal level, since this gives us more time for
1102 		   tracing through the code when debugging */
1103 		cryptSetAttribute( cryptSession, CRYPT_OPTION_NET_CONNECTTIMEOUT,
1104 						   120 );
1105 		}
1106 	if( localSession && isServer )
1107 		{
1108 		/* Tell the client that we're ready to go */
1109 		releaseMutex();
1110 		}
1111 	status = cryptSetAttribute( cryptSession, CRYPT_SESSINFO_ACTIVE, TRUE );
1112 #ifdef BROKEN_SERVER_INVALID_CERT
1113 	cryptSetAttribute( CRYPT_UNUSED, CRYPT_OPTION_CERT_COMPLIANCELEVEL,
1114 					   complianceLevel );
1115 #endif /* SSL server with b0rken certs */
1116 	if( isServer && testType != SSL_TEST_PSK_CLIONLY && \
1117 					testType != SSL_TEST_PSK_SVRONLY )
1118 		{
1119 		/* We don't check the return status for this since the session may
1120 		   be disconnected before we get the client info, which would cause
1121 		   us to bail out before we display the error info */
1122 		if( sessionID != CRYPT_UNUSED )
1123 			printf( "%02d: ", sessionID );
1124 		printConnectInfo( cryptSession );
1125 		}
1126 	if( isServer && testType == SSL_TEST_CLIENTCERT_MANUAL && \
1127 		status == CRYPT_ENVELOPE_RESOURCE )
1128 		{
1129 		CRYPT_CERTIFICATE cryptCertChain;
1130 
1131 		/* Allow the auth.and complete the handshake */
1132 		puts( "SVR: Manually verifying client certificate..." );
1133 		status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_RESPONSE,
1134 									&cryptCertChain );
1135 		if( cryptStatusOK( status ) )
1136 			{
1137 			/* In a real-world situation we'd check the certificate at this
1138 			   point, for now we just destroy it again and tell the server
1139 			   to continue */
1140 			cryptDestroyCert( cryptCertChain );
1141 			status = cryptSetAttribute( cryptSession,
1142 										CRYPT_SESSINFO_AUTHRESPONSE, TRUE );
1143 			}
1144 		if( cryptStatusOK( status ) )
1145 			status = cryptSetAttribute( cryptSession,
1146 										CRYPT_SESSINFO_ACTIVE, TRUE );
1147 		}
1148 #ifdef WINDOWS_THREADS
1149 	if( isServer && testType == SSL_TEST_DUALTHREAD && \
1150 		status == CRYPT_ENVELOPE_RESOURCE )
1151 		{
1152 		static CRYPT_SESSION localCryptSession = 0;
1153 		unsigned threadID;
1154 
1155 		/* Start a second thread to complete the handshake and exit */
1156 		localCryptSession = cryptSession;
1157 		_beginthreadex( NULL, 0, tlsServerDualThread2, NULL, 0, &threadID );
1158 		return( TRUE );
1159 
1160 		/* The second thread continues from here */
1161 dualThreadContinue:
1162 		assert( localSession > 0 );
1163 		cryptSession = localCryptSession;
1164 
1165 		/* Allow the auth.and complete the handshake */
1166 		puts( "SVR: Confirming authentication to client..." );
1167 		status = cryptSetAttribute( cryptSession,
1168 									CRYPT_SESSINFO_AUTHRESPONSE, TRUE );
1169 		if( cryptStatusOK( status ) )
1170 			status = cryptSetAttribute( cryptSession,
1171 										CRYPT_SESSINFO_ACTIVE, TRUE );
1172 		}
1173 #endif /* WINDOWS_THREADS */
1174 	if( cryptStatusError( status ) )
1175 		{
1176 		char strBuffer[ 128 ];
1177 
1178 		if( testType == SSL_TEST_STARTTLS )
1179 			{
1180 #if defined( __WINDOWS__ ) && !defined( _WIN32_WCE )
1181 			closesocket( netSocket );
1182 			WSACleanup();
1183 #else
1184 			/* If we're using a dummy local socket, we'll get a R/W error at
1185 			   this point since it's not connected to anything, so we
1186 			   intercept it before it gets any further */
1187 			if( status == CRYPT_ERROR_READ || status == CRYPT_ERROR_WRITE )
1188 				{
1189 				cryptDestroySession( cryptSession );
1190 				return( TRUE );
1191 				}
1192 #endif /* __WINDOWS__ && !_WIN32_WCE */
1193 			}
1194 		if( sessionID != CRYPT_UNUSED )
1195 			printf( "%02d: ", sessionID );
1196 		sprintf( strBuffer, "%sAttempt to activate %s%s session",
1197 				 isServer ? "SVR: " : "", localSession ? "local " : "",
1198 				 versionStr[ version ] );
1199 		printExtError( cryptSession, strBuffer, status, __LINE__ );
1200 		if( testType == SSL_TEST_BULKTRANSER )
1201 			free( bulkBuffer );
1202 		if( !isServer && isServerDown( cryptSession, status ) )
1203 			{
1204 			puts( "  (Server could be down, faking it and continuing...)\n" );
1205 			cryptDestroySession( cryptSession );
1206 			return( CRYPT_ERROR_FAILED );
1207 			}
1208 		cryptDestroySession( cryptSession );
1209 #ifndef NDEBUG
1210 		if( isErrorTest || testType == SSL_TEST_PSK_CLIONLY || \
1211 			testType == SSL_TEST_PSK_SVRONLY )
1212 			{
1213 			if( isErrorTest )
1214 				{
1215 				if( isServer )
1216 					{
1217 					/* The corrupt-handshake test is detcted by the server
1218 					   before the client even though the server has sent out
1219 					   a corrupted message because the client sends their
1220 					   Finished message first, and that contains the overall
1221 					   handshake MAC which is different for the client.  In
1222 					   addition this can be reported as a CRYPT_ERROR_BADDATA
1223 					   depending on where the corruption is caught */
1224 					if( testType == SSL_TEST_CORRUPT_HANDSHAKE && \
1225 						status != CRYPT_ERROR_SIGNATURE && \
1226 						status != CRYPT_ERROR_BADDATA )
1227 						{
1228 						printf( "Test returned status %d, should have been "
1229 								"%d.\n", status, CRYPT_ERROR_SIGNATURE );
1230 						return( FALSE );
1231 						}
1232 					}
1233 				else
1234 					{
1235 					if( testType != SSL_TEST_CORRUPT_HANDSHAKE && \
1236 						status != CRYPT_ERROR_SIGNATURE && \
1237 						status != CRYPT_ERROR_BADDATA )
1238 						{
1239 						printf( "Test returned status %d, should have been "
1240 								"%d.\n", status, CRYPT_ERROR_SIGNATURE );
1241 						return( FALSE );
1242 						}
1243 					}
1244 				}
1245 
1246 			/* These tests are supposed to fail, so if this happens then the
1247 			   overall test has succeeded */
1248 			puts( "  (This test checks error handling, so the failure "
1249 				  "response is correct).\n" );
1250 			return( TRUE );
1251 			}
1252 #endif /* !NDEBUG */
1253 		return( FALSE );
1254 		}
1255 
1256 #ifndef NDEBUG
1257 	/* The error tests should cause handshake failures, so getting to this
1258 	   point is an error */
1259 	if( isErrorTest && testType != SSL_TEST_CORRUPT_DATA )
1260 		{
1261 		cryptDestroySession( cryptSession );
1262 		puts( "  (This test should have led to a handshake failure but "
1263 			  "didn't, test has\n   failed).\n" );
1264 		return( FALSE );
1265 		}
1266 #endif /* !NDEBUG */
1267 
1268 	/* The CLIONLY/SVRONLY test is supposed to fail, if this doesn't happen
1269 	   then there's a problem */
1270 #ifdef NO_SESSION_CACHE
1271 	if( testType == SSL_TEST_PSK_CLIONLY || \
1272 		testType == SSL_TEST_PSK_SVRONLY )
1273 		{
1274 		printf( "%sTLS-PSK handshake without password should have "
1275 				"failed but succeeded,\nline %d.\n",
1276 				isServer ? "SVR: " : "", __LINE__  );
1277 		return( FALSE );
1278 		}
1279 #endif /* NO_SESSION_CACHE */
1280 
1281 	/* If we're testing session resumption and there's a server key present
1282 	   then we didn't actually resume the session */
1283 #ifndef NO_SESSION_CACHE
1284 	if( testType == SSL_TEST_RESUME )
1285 		{
1286 		CRYPT_CONTEXT serverKey;
1287 
1288 		status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_RESPONSE,
1289 									&serverKey );
1290 		if( cryptStatusOK( status ) )
1291 			{
1292 			cryptDestroyContext( serverKey );
1293 			printf( "%sSession resumption didn't actually resume a previous "
1294 					"session, line %d.\n", isServer ? "SVR: " : "",
1295 					__LINE__  );
1296 			return( FALSE );
1297 			}
1298 		}
1299 #endif /* !NO_SESSION_CACHE */
1300 
1301 	/* Report the session security info */
1302 	if( testType != SSL_TEST_MULTITHREAD )
1303 		{
1304 		const BOOLEAN isFirstSession = \
1305 			( testType == SSL_TEST_NORMAL && version == 0 ) ? TRUE : FALSE;
1306 		int actualVersion;
1307 
1308 #ifdef NO_SESSION_CACHE
1309 		if( !printSecurityInfo( cryptSession, isServer,
1310 				( testType != SSL_TEST_PSK && testType != SSL_TEST_RESUME ),
1311 				( !isServer && testType != SSL_TEST_PSK && \
1312 							   testType != SSL_TEST_RESUME ),
1313 				( isServer && ( testType == SSL_TEST_CLIENTCERT || \
1314 								testType == SSL_TEST_CLIENTCERT_MANUAL ) ) ) )
1315 			{
1316 			if( testType == SSL_TEST_BULKTRANSER )
1317 				free( bulkBuffer );
1318 			return( FALSE );
1319 			}
1320 #else
1321 		if( !printSecurityInfo( cryptSession, isServer, isFirstSession,
1322 								!isServer && isFirstSession, FALSE ) )
1323 			{
1324 			if( testType == SSL_TEST_BULKTRANSER )
1325 				free( bulkBuffer );
1326 			return( FALSE );
1327 			}
1328 #endif /* NO_SESSION_CACHE */
1329 		status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_VERSION,
1330 									&actualVersion );
1331 		if( cryptStatusOK( status ) && actualVersion != version )
1332 			{
1333 			printf( "Warning: Expected to connect using %s but only "
1334 					"connected using %s.\n", versionStr[ version ],
1335 					versionStr[ actualVersion ] );
1336 			}
1337 		}
1338 #ifdef NO_SESSION_CACHE
1339 	if( ( !localSession && !isServer && testType != SSL_TEST_PSK ) ||
1340 		( localSession && isServer && \
1341 		  ( testType == SSL_TEST_CLIENTCERT || \
1342 			testType == SSL_TEST_CLIENTCERT_MANUAL ) ) )
1343 #else
1344 	if( !localSession && !isServer && testType != SSL_TEST_PSK )
1345 #endif /* NO_SESSION_CACHE */
1346 		{
1347 		CRYPT_CERTIFICATE cryptCertificate;
1348 
1349 		status = cryptGetAttribute( cryptSession, CRYPT_SESSINFO_RESPONSE,
1350 									&cryptCertificate );
1351 		if( cryptStatusError( status ) )
1352 			{
1353 			printf( "%sCouldn't get %s certificate, status %d, line %d.\n",
1354 					isServer ? "SVR: " : "", isServer ? "client" : "server",
1355 					status, __LINE__ );
1356 			if( testType == SSL_TEST_BULKTRANSER )
1357 				free( bulkBuffer );
1358 			return( FALSE );
1359 			}
1360 		puts( localSession ? "SVR: Client certificate details are:" : \
1361 							 "Server certificate details are:" );
1362 		printCertChainInfo( cryptCertificate );
1363 		cryptDestroyCert( cryptCertificate );
1364 		}
1365 	if( isServer && testType == SSL_TEST_PSK )
1366 		{
1367 		C_CHR userNameBuffer[ CRYPT_MAX_TEXTSIZE + 1 ];
1368 		int length;
1369 
1370 		status = cryptGetAttributeString( cryptSession,
1371 										  CRYPT_SESSINFO_USERNAME,
1372 										  userNameBuffer, &length );
1373 		if( cryptStatusError( status ) )
1374 			{
1375 			printf( "SVR: Couldn't read client user name, status %d, line "
1376 					"%d.\n", status, __LINE__ );
1377 			return( FALSE );
1378 			}
1379 #ifdef UNICODE_STRINGS
1380 		userNameBuffer[ length / sizeof( wchar_t ) ] = TEXT( '\0' );
1381 		printf( "SVR: Client user name = '%S'.\n", userNameBuffer );
1382 #else
1383 		userNameBuffer[ length ] = '\0';
1384 		printf( "SVR: Client user name = '%s'.\n", userNameBuffer );
1385 #endif /* UNICODE_STRINGS */
1386 		if( length != ( int ) paramStrlen( SSL_USER_NAME ) || \
1387 			memcmp( userNameBuffer, SSL_USER_NAME, \
1388 					paramStrlen( SSL_USER_NAME ) ) )
1389 			{
1390 			printf( "SVR: User name was '%s', should have been '%s', line "
1391 					"%d.\n", userNameBuffer, SSL_USER_NAME, __LINE__ );
1392 			return( FALSE );
1393 			}
1394 		}
1395 
1396 	/* Send data over the SSL/TLS link.  If we're doing a bulk transfer
1397 	   we use fully asynchronous I/O to verify the timeout handling in
1398 	   the session code */
1399 #if defined( IS_HIGHVOLUME_SERVER )
1400 	/* This server has a large amount of data on it, used to test high-
1401 	   latency bulk transfers, so we set a larger timeout for the read */
1402 	status = cryptSetAttribute( cryptSession, CRYPT_OPTION_NET_READTIMEOUT,
1403 								15 );
1404 #elif defined USE_TIMING
1405 	status = cryptSetAttribute( cryptSession, CRYPT_OPTION_NET_READTIMEOUT,
1406 								5 );
1407 #else
1408 	status = cryptSetAttribute( cryptSession, CRYPT_OPTION_NET_READTIMEOUT,
1409 								( testType == SSL_TEST_BULKTRANSER ) ? 0 : 5 );
1410 #endif /* IS_HIGHVOLUME_SERVER */
1411 	if( cryptStatusError( status ) )
1412 		{
1413 		if( testType == SSL_TEST_BULKTRANSER )
1414 			free( bulkBuffer );
1415 		printExtError( cryptSession, isServer ? \
1416 					   "SVR: Session timeout set" : "Session timeout set",
1417 					   status, __LINE__ );
1418 		return( FALSE );
1419 		}
1420 	if( testType == SSL_TEST_BULKTRANSER )
1421 		{
1422 #ifdef USE_TIMING
1423 		int timeMS;
1424 
1425 		timeVal = timeDiff( 0 );
1426 #endif /* USE_TIMING */
1427 		if( isServer )
1428 			{
1429 			long byteCount = 0;
1430 
1431 			do
1432 				{
1433 				status = cryptPushData( cryptSession, bulkBuffer + byteCount,
1434 										BULKDATA_BUFFER_SIZE - byteCount,
1435 										&bytesCopied );
1436 				byteCount += bytesCopied;
1437 				}
1438 			while( ( cryptStatusOK( status ) || \
1439 					 status == CRYPT_ERROR_TIMEOUT ) && \
1440 				   byteCount < BULKDATA_BUFFER_SIZE );
1441 			if( cryptStatusError( status ) )
1442 				{
1443 				printExtError( cryptSession,
1444 							   "SVR: Send of bulk data to client", status,
1445 							   __LINE__ );
1446 				return( FALSE );
1447 				}
1448 			status = cryptFlushData( cryptSession );
1449 			if( cryptStatusError( status ) )
1450 				{
1451 				printExtError( cryptSession,
1452 							   "SVR: Flush of bulk data to client", status,
1453 							   __LINE__ );
1454 				return( FALSE );
1455 				}
1456 			if( byteCount != BULKDATA_BUFFER_SIZE )
1457 				{
1458 				printf( "Only sent %ld of %ld bytes, line %d.\n", byteCount,
1459 						BULKDATA_BUFFER_SIZE, __LINE__ );
1460 				return( FALSE );
1461 				}
1462 			}
1463 		else
1464 			{
1465 			long byteCount = 0;
1466 
1467 			do
1468 				{
1469 				status = cryptPopData( cryptSession, bulkBuffer + byteCount,
1470 									   BULKDATA_BUFFER_SIZE - byteCount,
1471 									   &bytesCopied );
1472 				byteCount += bytesCopied;
1473 				}
1474 			while( ( cryptStatusOK( status ) || \
1475 					 status == CRYPT_ERROR_TIMEOUT ) && \
1476 				   byteCount < BULKDATA_BUFFER_SIZE );
1477 			if( cryptStatusError( status ) )
1478 				{
1479 				char strBuffer[ 256 ];
1480 
1481 				sprintf( strBuffer, "Read of bulk data from server aborted "
1482 									"after %ld of %ld bytes were read\n(last "
1483 									"read = %d bytes), transfer",
1484 									byteCount, BULKDATA_BUFFER_SIZE,
1485 									bytesCopied );
1486 				printExtError( cryptSession, strBuffer, status, __LINE__ );
1487 				return( FALSE );
1488 				}
1489 			if( byteCount != BULKDATA_BUFFER_SIZE )
1490 				{
1491 				printf( "Only received %ld of %ld bytes, line %d.\n",
1492 						byteCount, BULKDATA_BUFFER_SIZE, __LINE__ );
1493 				return( FALSE );
1494 				}
1495 			if( !handleBulkBuffer( bulkBuffer, FALSE ) )
1496 				{
1497 				printf( "Received buffer contents don't match sent buffer "
1498 						"contents, line %d.", __LINE__ );
1499 				return( FALSE );
1500 				}
1501 			}
1502 #ifdef USE_TIMING
1503 		timeVal = timeDiff( timeVal );
1504 		printf( "Time for %s transfer: ",
1505 				isServer ? "server-to-client" : "client-to-server" );
1506 		timeMS = timeDisplay( timeVal );
1507 		printf( "Data rate = %d kBytes/second.\n",
1508 				( int ) ( BULKDATA_BUFFER_SIZE / timeMS ) );
1509 #endif /* USE_TIMING */
1510 		free( bulkBuffer );
1511 		}
1512 	else
1513 		{
1514 		/* It's a standard transfer, send/receive and HTTP request/response.
1515 		   We clean up if we exit due to an error, if we're running a local
1516 		   loopback test the client and server threads can occasionally lose
1517 		   sync, which isn't a fatal error but can turn into a
1518 		   CRYPT_ERROR_INCOMPLETE once all the tests are finished */
1519 		if( isServer )
1520 			{
1521 			BYTE textBuffer[ 1024 ];
1522 #if defined( __MVS__ ) || defined( __VMCMS__ )
1523   #pragma convlit( resume )
1524 #endif /* IBM big iron */
1525 #if defined( __ILEC400__ )
1526   #pragma convert( 819 )
1527 #endif /* IBM medium iron */
1528 			const char serverReply[] = \
1529 				"HTTP/1.0 200 OK\n"
1530 				"Date: Fri, 7 June 2015 20:02:07 GMT\n"
1531 				"Server: cryptlib SSL/TLS test\n"
1532 				"Content-Type: text/html\n"
1533 				"Connection: Close\n"
1534 				"\n"
1535 				"<!DOCTYPE HTML SYSTEM \"html.dtd\">\n"
1536 				"<html>\n"
1537 				"<head>\n"
1538 				"<title>cryptlib %s test page</title>\n"
1539 				"<body>\n"
1540 				"Test message from the cryptlib %s server.<p>\n"
1541 				"</body>\n"
1542 				"</html>\n";
1543 #if defined( __MVS__ ) || defined( __VMCMS__ )
1544   #pragma convlit( suspend )
1545 #endif /* IBM big iron */
1546 #if defined( __ILEC400__ )
1547   #pragma convert( 0 )
1548 #endif /* IBM medium iron */
1549 			int bytesToSend;
1550 
1551 			/* Print the text of the request from the client */
1552 			status = cryptPopData( cryptSession, buffer, FILEBUFFER_SIZE,
1553 								   &bytesCopied );
1554 			if( cryptStatusError( status ) )
1555 				{
1556 				printExtError( cryptSession, "SVR: Attempt to read data "
1557 							   "from client", status, __LINE__ );
1558 				cryptDestroySession( cryptSession );
1559 				return( FALSE );
1560 				}
1561 			buffer[ bytesCopied ] = '\0';
1562 #if defined( __MVS__ ) || defined( __VMCMS__ )
1563 			asciiToEbcdic( buffer, bytesCopied );
1564 #endif /* EBCDIC systems */
1565 			if( testType != SSL_TEST_MULTITHREAD )
1566 				{
1567 				printf( "---- Client sent %d bytes ----\n", bytesCopied );
1568 				puts( buffer );
1569 				puts( "---- End of output ----" );
1570 				}
1571 
1572 			/* Send a reply */
1573 			bytesToSend = sprintf( textBuffer, serverReply,
1574 								   versionStr[ version ],
1575 								   versionStr[ version ] );
1576 			status = cryptPushData( cryptSession, textBuffer, bytesToSend,
1577 									&bytesCopied );
1578 			if( cryptStatusOK( status ) )
1579 				status = cryptFlushData( cryptSession );
1580 			if( cryptStatusError( status ) || bytesCopied != bytesToSend )
1581 				{
1582 				printExtError( cryptSession, "Attempt to send data to "
1583 							   "client", status, __LINE__ );
1584 				cryptDestroySession( cryptSession );
1585 				return( FALSE );
1586 				}
1587 
1588 			/* Wait for the data to be flushed through to the client before
1589 			   we close the session */
1590 			delayThread( 1 );
1591 			}
1592 		else
1593 			{
1594 			char fetchString[ 128 ];
1595 			int fetchStringLen;
1596 
1597 			/* Send a fetch request to the server */
1598 			if( testType == SSL_TEST_STARTTLS )
1599 				{
1600 				switch( protocol )
1601 					{
1602 					case PROTOCOL_SMTP:
1603 						strcpy( fetchString, "EHLO foo.bar.com\r\n" );
1604 						break;
1605 
1606 					case PROTOCOL_POP:
1607 						strcpy( fetchString, "CAPA\r\n" );
1608 						break;
1609 
1610 					case PROTOCOL_IMAP:
1611 						strcpy( fetchString, "a003 CAPABILITY\r\n" );
1612 						break;
1613 
1614 					default:
1615 						strcpy( fetchString, "USER test\r\n" );
1616 					}
1617 				}
1618 			else
1619 				{
1620 				sprintf( fetchString, "GET %s HTTP/1.0\r\n\r\n",
1621 						 sslInfo[ SSL_SERVER_NO ].path );
1622 				}
1623 			fetchStringLen = strlen( fetchString );
1624 #if defined( __MVS__ ) || defined( __VMCMS__ )
1625 			ebcdicToAscii( fetchString, fetchStringLen );
1626 #endif /* EBCDIC systems */
1627 			status = cryptPushData( cryptSession, fetchString,
1628 									fetchStringLen, &bytesCopied );
1629 			if( cryptStatusOK( status ) )
1630 				status = cryptFlushData( cryptSession );
1631 			if( cryptStatusError( status ) || bytesCopied != fetchStringLen )
1632 				{
1633 				printExtError( cryptSession, "Attempt to send data to "
1634 							   "server", status, __LINE__ );
1635 				cryptDestroySession( cryptSession );
1636 				return( FALSE );
1637 				}
1638 
1639 			/* Print the text of the reply from the server */
1640 			status = cryptPopData( cryptSession, buffer, FILEBUFFER_SIZE,
1641 								   &bytesCopied );
1642 			if( cryptStatusError( status ) )
1643 				{
1644 				printExtError( cryptSession, "Attempt to read data from "
1645 							   "server", status, __LINE__ );
1646 				cryptDestroySession( cryptSession );
1647 #ifndef NDEBUG
1648 				if( isErrorTest )
1649 					{
1650 					/* These tests are supposed to fail, so if this happens
1651 					   then the overall test has succeeded */
1652 					puts( "  (This test checks error handling, so the "
1653 						  "failure response is correct).\n" );
1654 					return( TRUE );
1655 					}
1656 #endif /* !NDEBUG */
1657 				return( FALSE );
1658 				}
1659 #ifndef NDEBUG
1660 			/* The error tests should cause protocol failures, so getting to
1661 			   this point is an error */
1662 			if( isErrorTest )
1663 				{
1664 				cryptDestroySession( cryptSession );
1665 				puts( "  (This test should have led to a protocol failure "
1666 					  "but didn't, test has\n   failed).\n" );
1667 				return( FALSE );
1668 				}
1669 #endif /* !NDEBUG */
1670 			if( bytesCopied == 0 && testType != SSL_TEST_STARTTLS )
1671 				{
1672 				/* We've set a 5s timeout, we should get at least some
1673 				   data, however we allow this for the STARTTLS tests since
1674 				   the servers can exhibit all sorts of odd behaviour that
1675 				   we can't do much about with the partial client that we
1676 				   have here */
1677 				puts( "Server returned no data in response to our request." );
1678 				cryptDestroySession( cryptSession );
1679 				return( FALSE );
1680 				}
1681 			buffer[ min( bytesCopied, 4096 ) ] = '\0';
1682 #if defined( __MVS__ ) || defined( __VMCMS__ )
1683 			asciiToEbcdic( buffer, bytesCopied );
1684 #endif /* EBCDIC systems */
1685 			if( testType != SSL_TEST_MULTITHREAD )
1686 				{
1687 				printf( "---- Server sent %d bytes ----\n", bytesCopied );
1688 				puts( buffer );
1689 				if( bytesCopied > 4096 )
1690 					printf( "  (Further %d bytes data omitted)\n",
1691 							bytesCopied - 4096 );
1692 				puts( "---- End of output ----" );
1693 				}
1694 
1695 #ifdef IS_HIGHVOLUME_SERVER
1696 			/* If we're reading a lot of data, more may have arrived in the
1697 			   meantime */
1698 			status = cryptPopData( cryptSession, buffer, FILEBUFFER_SIZE,
1699 								   &bytesCopied );
1700 			if( cryptStatusError( status ) )
1701 				{
1702 				if( status == CRYPT_ERROR_READ )
1703 					{
1704 					/* Since this is HTTP, the other side can close the
1705 					   connection with no further warning, even though SSL
1706 					   says you shouldn't really do this */
1707 					puts( "Remote system closed connection." );
1708 					}
1709 				else
1710 					{
1711 					printExtError( cryptSession, "Attempt to read data from "
1712 								   "server", status, __LINE__ );
1713 					cryptDestroySession( cryptSession );
1714 					return( FALSE );
1715 					}
1716 				}
1717 			else
1718 				{
1719 				buffer[ bytesCopied ] = '\0';
1720 #if defined( __MVS__ ) || defined( __VMCMS__ )
1721 				asciiToEbcdic( buffer, bytesCopied );
1722 #endif /* EBCDIC systems */
1723 				if( testType != SSL_TEST_MULTITHREAD )
1724 					{
1725 					printf( "---- Server sent further %d bytes ----\n",
1726 							bytesCopied );
1727 					puts( buffer );
1728 					puts( "---- End of output ----" );
1729 					}
1730 				}
1731 #endif /* IS_HIGHVOLUME_SERVER */
1732 
1733 			/* If it's a chatty protocol, exchange some more pleasantries */
1734 			if( testType == SSL_TEST_STARTTLS )
1735 				{
1736 				switch( protocol )
1737 					{
1738 					case PROTOCOL_SMTP:
1739 						strcpy( fetchString, "QUIT\r\n" );
1740 						break;
1741 
1742 					case PROTOCOL_POP:
1743 						strcpy( fetchString, "USER test\r\n" );
1744 						break;
1745 
1746 					case PROTOCOL_IMAP:
1747 						strcpy( fetchString, "a004 LOGIN test\r\n" );
1748 						break;
1749 
1750 					default:
1751 						strcpy( fetchString, "QUIT\r\n" );
1752 					}
1753 				fetchStringLen = strlen( fetchString );
1754 #if defined( __MVS__ ) || defined( __VMCMS__ )
1755 				ebcdicToAscii( fetchString, fetchStringLen );
1756 #endif /* EBCDIC systems */
1757 				status = cryptPushData( cryptSession, fetchString,
1758 										fetchStringLen, &bytesCopied );
1759 				if( cryptStatusOK( status ) )
1760 					status = cryptFlushData( cryptSession );
1761 				if( cryptStatusError( status ) || bytesCopied != fetchStringLen )
1762 					{
1763 					printExtError( cryptSession, "Attempt to send data to "
1764 								   "server", status, __LINE__ );
1765 					cryptDestroySession( cryptSession );
1766 					return( FALSE );
1767 					}
1768 				status = cryptPopData( cryptSession, buffer, FILEBUFFER_SIZE,
1769 									   &bytesCopied );
1770 				if( cryptStatusError( status ) )
1771 					{
1772 					printExtError( cryptSession, "Attempt to read data from "
1773 								   "server", status, __LINE__ );
1774 					cryptDestroySession( cryptSession );
1775 					return( FALSE );
1776 					}
1777 				buffer[ bytesCopied ] = '\0';
1778 #if defined( __MVS__ ) || defined( __VMCMS__ )
1779 				asciiToEbcdic( buffer, bytesCopied );
1780 #endif /* EBCDIC systems */
1781 				if( testType != SSL_TEST_MULTITHREAD )
1782 					{
1783 					printf( "---- Server sent %d bytes ----\n", bytesCopied );
1784 					puts( buffer );
1785 					puts( "---- End of output ----" );
1786 					}
1787 				}
1788 			}
1789 		}
1790 
1791 	/* Clean up */
1792 	status = cryptDestroySession( cryptSession );
1793 	if( cryptStatusError( status ) )
1794 		{
1795 		printf( "cryptDestroySession() failed with error code %d, line %d.\n",
1796 				status, __LINE__ );
1797 		return( FALSE );
1798 		}
1799 #if defined( __WINDOWS__ ) && !defined( _WIN32_WCE )
1800 	if( testType == SSL_TEST_STARTTLS )
1801 		{
1802 		closesocket( netSocket );
1803 		WSACleanup();
1804 		}
1805 #endif /* __WINDOWS__ && !_WIN32_WCE */
1806 
1807 	if( sessionID != CRYPT_UNUSED )
1808 		printf( "%02d: ", sessionID );
1809 	printf( "%s%s session succeeded.\n", isServer ? "SVR: " : "",
1810 			versionStr[ version ] );
1811 	if( testType != SSL_TEST_MULTITHREAD )
1812 		putchar( '\n' );
1813 	return( TRUE );
1814 	}
1815 
testSessionSSL(void)1816 int testSessionSSL( void )
1817 	{
1818 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_NORMAL, 0, CRYPT_UNUSED, FALSE ) );
1819 	}
testSessionSSLLocalSocket(void)1820 int testSessionSSLLocalSocket( void )
1821 	{
1822 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_STARTTLS, 0, CRYPT_UNUSED, FALSE ) );
1823 	}
testSessionSSLClientCert(void)1824 int testSessionSSLClientCert( void )
1825 	{
1826 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_CLIENTCERT, 0, CRYPT_UNUSED, FALSE ) );
1827 	}
1828 
testSessionSSLServer(void)1829 int testSessionSSLServer( void )
1830 	{
1831 	int status;
1832 
1833 	createMutex();
1834 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_NORMAL, 0, CRYPT_UNUSED, FALSE );
1835 	destroyMutex();
1836 
1837 	return( status );
1838 	}
testSessionSSLServerCached(void)1839 int testSessionSSLServerCached( void )
1840 	{
1841 	int status;
1842 
1843 	/* Run the server twice to check session cacheing.  Testing this
1844 	   requires manual reconnection with a browser to localhost, since it's
1845 	   too complex to handle easily via a loopback test.  Note that with
1846 	   MSIE this will require three lots of connects rather than two,
1847 	   because it handles an unknown certificate by doing a resume, which
1848 	   consumes two lots of sessions, and then the third one is the actual
1849 	   session resume */
1850 	createMutex();
1851 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_NORMAL, 0, CRYPT_UNUSED, FALSE );
1852 	if( status > 0 )
1853 		status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_NORMAL, 0, CRYPT_UNUSED, FALSE );
1854 	destroyMutex();
1855 
1856 	return( status );
1857 	}
testSessionSSLServerClientCert(void)1858 int testSessionSSLServerClientCert( void )
1859 	{
1860 	int status;
1861 
1862 	createMutex();
1863 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_CLIENTCERT, 0, CRYPT_UNUSED, FALSE );
1864 	destroyMutex();
1865 
1866 	return( status );
1867 	}
1868 
testSessionTLS(void)1869 int testSessionTLS( void )
1870 	{
1871 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_NORMAL, 1, CRYPT_UNUSED, FALSE ) );
1872 	}
testSessionTLSLocalSocket(void)1873 int testSessionTLSLocalSocket( void )
1874 	{
1875 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_STARTTLS, 1, CRYPT_UNUSED, FALSE ) );
1876 	}
testSessionTLSSharedKey(void)1877 int testSessionTLSSharedKey( void )
1878 	{
1879 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_PSK, 1, CRYPT_UNUSED, FALSE ) );
1880 	}
1881 
testSessionTLSServer(void)1882 int testSessionTLSServer( void )
1883 	{
1884 	int status;
1885 
1886 	createMutex();
1887 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_NORMAL, 1, CRYPT_UNUSED, FALSE );
1888 	destroyMutex();
1889 
1890 	return( status );
1891 	}
testSessionTLSServerSharedKey(void)1892 int testSessionTLSServerSharedKey( void )
1893 	{
1894 	int status;
1895 
1896 	createMutex();
1897 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_PSK, 1, CRYPT_UNUSED, FALSE );
1898 	destroyMutex();
1899 
1900 	return( status );
1901 	}
1902 
testSessionTLS11(void)1903 int testSessionTLS11( void )
1904 	{
1905 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_NORMAL, 2, CRYPT_UNUSED, FALSE ) );
1906 	}
testSessionTLS11Server(void)1907 int testSessionTLS11Server( void )
1908 	{
1909 	int status;
1910 
1911 	createMutex();
1912 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_NORMAL, 2, CRYPT_UNUSED, FALSE );
1913 	destroyMutex();
1914 
1915 	return( status );
1916 	}
1917 
testSessionTLS12(void)1918 int testSessionTLS12( void )
1919 	{
1920 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_NORMAL, 3, CRYPT_UNUSED, FALSE ) );
1921 	}
testSessionTLS12ClientCert(void)1922 int testSessionTLS12ClientCert( void )
1923 	{
1924 	return( connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_CLIENTCERT, 3, CRYPT_UNUSED, FALSE ) );
1925 	}
testSessionTLS12Server(void)1926 int testSessionTLS12Server( void )
1927 	{
1928 	int status;
1929 
1930 	createMutex();
1931 
1932 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_NORMAL, 3, CRYPT_UNUSED, FALSE );
1933 	destroyMutex();
1934 
1935 	return( status );
1936 	}
testSessionTLS12ServerClientCertManual(void)1937 int testSessionTLS12ServerClientCertManual( void )
1938 	{
1939 	int status;
1940 
1941 	createMutex();
1942 
1943 	status = connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_CLIENTCERT_MANUAL, 3, CRYPT_UNUSED, TRUE );
1944 	destroyMutex();
1945 
1946 	return( status );
1947 	}
1948 
1949 /* Perform a client/server loopback test */
1950 
1951 #ifdef WINDOWS_THREADS
1952 
sslServerThread(void * arg)1953 unsigned __stdcall sslServerThread( void *arg )
1954 	{
1955 	const int argValue = *( ( int * ) arg );
1956 
1957 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, argValue, 0, CRYPT_UNUSED,
1958 				   TRUE );
1959 	_endthreadex( 0 );
1960 	return( 0 );
1961 	}
sslClientServer(const SSL_TEST_TYPE testType)1962 static int sslClientServer( const SSL_TEST_TYPE testType )
1963 	{
1964 	HANDLE hThread;
1965 	unsigned threadID;
1966 	int arg = testType, status;
1967 
1968 	/* Start the server */
1969 	createMutex();
1970 	hThread = ( HANDLE ) _beginthreadex( NULL, 0, sslServerThread, &arg, 0,
1971 										 &threadID );
1972 	Sleep( 1000 );
1973 
1974 	/* Connect to the local server */
1975 	status = connectSSLTLS( CRYPT_SESSION_SSL, testType, 0, CRYPT_UNUSED,
1976 							TRUE );
1977 	waitForThread( hThread );
1978 	destroyMutex();
1979 	return( status );
1980 	}
testSessionSSLClientServer(void)1981 int testSessionSSLClientServer( void )
1982 	{
1983 	return( sslClientServer( SSL_TEST_NORMAL ) );
1984 	}
testSessionSSLClientCertClientServer(void)1985 int testSessionSSLClientCertClientServer( void )
1986 	{
1987 	return( sslClientServer( SSL_TEST_CLIENTCERT ) );
1988 	}
1989 
tlsServerThread(void * arg)1990 unsigned __stdcall tlsServerThread( void *arg )
1991 	{
1992 	const int argValue = *( ( int * ) arg );
1993 
1994 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, argValue, 1, CRYPT_UNUSED,
1995 				   TRUE );
1996 	_endthreadex( 0 );
1997 	return( 0 );
1998 	}
tlsClientServer(const SSL_TEST_TYPE testType)1999 static int tlsClientServer( const SSL_TEST_TYPE testType )
2000 	{
2001 	HANDLE hThread;
2002 	unsigned threadID;
2003 	int arg = testType, status;
2004 
2005 	/* Start the server */
2006 	createMutex();
2007 	hThread = ( HANDLE ) _beginthreadex( NULL, 0, tlsServerThread, &arg, 0,
2008 										 &threadID );
2009 	Sleep( 1000 );
2010 
2011 	/* Connect to the local server */
2012 	status = connectSSLTLS( CRYPT_SESSION_SSL, testType, 1, CRYPT_UNUSED,
2013 							TRUE );
2014 	waitForThread( hThread );
2015 	destroyMutex();
2016 	return( status );
2017 	}
testSessionTLSClientServer(void)2018 int testSessionTLSClientServer( void )
2019 	{
2020 	return( tlsClientServer( SSL_TEST_NORMAL ) );
2021 	}
testSessionTLSSharedKeyClientServer(void)2022 int testSessionTLSSharedKeyClientServer( void )
2023 	{
2024 	return( tlsClientServer( SSL_TEST_PSK ) );
2025 	}
testSessionTLSNoSharedKeyClientServer(void)2026 int testSessionTLSNoSharedKeyClientServer( void )
2027 	{
2028 	if( !tlsClientServer( SSL_TEST_PSK_CLIONLY ) )
2029 		return( FALSE );
2030 	return( tlsClientServer( SSL_TEST_PSK_SVRONLY ) );
2031 	}
testSessionTLSBulkTransferClientServer(void)2032 int testSessionTLSBulkTransferClientServer( void )
2033 	{
2034 	return( tlsClientServer( SSL_TEST_BULKTRANSER ) );
2035 	}
2036 
tls11ServerThread(void * arg)2037 unsigned __stdcall tls11ServerThread( void *arg )
2038 	{
2039 	const int argValue = *( ( int * ) arg );
2040 
2041 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, argValue, 2, CRYPT_UNUSED,
2042 				   TRUE );
2043 	_endthreadex( 0 );
2044 	return( 0 );
2045 	}
tls11ClientServer(const SSL_TEST_TYPE testType)2046 static int tls11ClientServer( const SSL_TEST_TYPE testType )
2047 	{
2048 	HANDLE hThread;
2049 	unsigned threadID;
2050 	int arg = testType, status;
2051 
2052 	/* Start the server */
2053 	createMutex();
2054 	hThread = ( HANDLE ) _beginthreadex( NULL, 0, tls11ServerThread, &arg, 0,
2055 										 &threadID );
2056 	Sleep( 1000 );
2057 
2058 	/* Connect to the local server */
2059 	status = connectSSLTLS( CRYPT_SESSION_SSL, testType, 2, CRYPT_UNUSED,
2060 							TRUE );
2061 	waitForThread( hThread );
2062 	destroyMutex();
2063 	return( status );
2064 	}
testSessionTLS11ClientServer(void)2065 int testSessionTLS11ClientServer( void )
2066 	{
2067 	return( tls11ClientServer( SSL_TEST_NORMAL ) );
2068 	}
testSessionTLS11ClientCertClientServer(void)2069 int testSessionTLS11ClientCertClientServer( void )
2070 	{
2071 	return( tls11ClientServer( SSL_TEST_CLIENTCERT ) );
2072 	}
testSessionTLS11ResumeClientServer(void)2073 int testSessionTLS11ResumeClientServer( void )
2074 	{
2075 	/* Note that this function has to be called after one of the standard
2076 	   TLS-connect functions has been called, since it checks for the
2077 	   ability to resume a previously-cached session */
2078 	return( tls11ClientServer( SSL_TEST_RESUME ) );
2079 	}
2080 
tls12ServerThread(void * arg)2081 unsigned __stdcall tls12ServerThread( void *arg )
2082 	{
2083 	const int argValue = *( ( int * ) arg );
2084 
2085 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, argValue, 3, CRYPT_UNUSED,
2086 				   TRUE );
2087 	_endthreadex( 0 );
2088 	return( 0 );
2089 	}
tls12ClientServer(const SSL_TEST_TYPE testType)2090 static int tls12ClientServer( const SSL_TEST_TYPE testType )
2091 	{
2092 	HANDLE hThread;
2093 	unsigned threadID;
2094 	int arg = testType, status;
2095 
2096 	/* Start the server */
2097 	createMutex();
2098 	hThread = ( HANDLE ) _beginthreadex( NULL, 0, tls12ServerThread, &arg, 0,
2099 										 &threadID );
2100 	Sleep( 1000 );
2101 
2102 	/* Connect to the local server */
2103 	status = connectSSLTLS( CRYPT_SESSION_SSL, testType, 3, CRYPT_UNUSED,
2104 							TRUE );
2105 	waitForThread( hThread );
2106 	destroyMutex();
2107 	return( status );
2108 	}
testSessionTLS12ClientServer(void)2109 int testSessionTLS12ClientServer( void )
2110 	{
2111 	return( tls12ClientServer( SSL_TEST_NORMAL ) );
2112 	}
testSessionTLS12ClientServerEccKey(void)2113 int testSessionTLS12ClientServerEccKey( void )
2114 	{
2115 	if( cryptQueryCapability( CRYPT_ALGO_ECDSA, \
2116 							  NULL ) == CRYPT_ERROR_NOTAVAIL )
2117 		{
2118 		puts( "ECC is disabled in this build of cryptlib, skipping TLS ECC "
2119 			  "test." );
2120 		return( TRUE );
2121 		}
2122 	return( tls12ClientServer( SSL_TEST_ECC ) );
2123 	}
testSessionTLS12ClientServerEcc384Key(void)2124 int testSessionTLS12ClientServerEcc384Key( void )
2125 	{
2126 	if( cryptQueryCapability( CRYPT_ALGO_ECDSA, \
2127 							  NULL ) == CRYPT_ERROR_NOTAVAIL )
2128 		{
2129 		puts( "ECC is disabled in this build of cryptlib, skipping TLS ECC "
2130 			  "test." );
2131 		return( TRUE );
2132 		}
2133 	return( tls12ClientServer( SSL_TEST_ECC_P384 ) );
2134 	}
testSessionTLS12ClientCertClientServer(void)2135 int testSessionTLS12ClientCertClientServer( void )
2136 	{
2137 	return( tls12ClientServer( SSL_TEST_CLIENTCERT ) );
2138 	}
testSessionTLS12ClientCertManualClientServer(void)2139 int testSessionTLS12ClientCertManualClientServer( void )
2140 	{
2141 	return( tls12ClientServer( SSL_TEST_CLIENTCERT_MANUAL ) );
2142 	}
2143 
tlsServerDualThread2(void * dummy)2144 unsigned __stdcall tlsServerDualThread2( void *dummy )
2145 	{
2146 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_DUALTHREAD, 1, 0, TRUE );
2147 	_endthreadex( 0 );
2148 	return( 0 );
2149 	}
tlsServerDualThread1(void * dummy)2150 unsigned __stdcall tlsServerDualThread1( void *dummy )
2151 	{
2152 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_DUALTHREAD, 1, CRYPT_UNUSED, TRUE );
2153 	_endthreadex( 0 );
2154 	return( 0 );
2155 	}
testSessionTLSClientServerDualThread(void)2156 int testSessionTLSClientServerDualThread( void )
2157 	{
2158 	HANDLE hThread;
2159 	unsigned threadID;
2160 	int status;
2161 
2162 	/* Start the server */
2163 	createMutex();
2164 	hThread = ( HANDLE ) _beginthreadex( NULL, 0, tlsServerDualThread1,
2165 										 NULL, 0, &threadID );
2166 	Sleep( 1000 );
2167 
2168 	/* Connect to the local server */
2169 	status = connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_PSK, 1, CRYPT_UNUSED, TRUE );
2170 	waitForThread( hThread );
2171 	destroyMutex();
2172 	return( status );
2173 	}
2174 
tlsServerMultiThread(void * threadIdPtr)2175 unsigned __stdcall tlsServerMultiThread( void *threadIdPtr )
2176 	{
2177 	int threadID = *( ( int * ) threadIdPtr );
2178 
2179 	connectSSLTLS( CRYPT_SESSION_SSL_SERVER, SSL_TEST_MULTITHREAD, 1, threadID, TRUE );
2180 	_endthreadex( 0 );
2181 	return( 0 );
2182 	}
tlsClientMultiThread(void * threadIdPtr)2183 unsigned __stdcall tlsClientMultiThread( void *threadIdPtr )
2184 	{
2185 	int threadID = *( ( int * ) threadIdPtr );
2186 
2187 	connectSSLTLS( CRYPT_SESSION_SSL, SSL_TEST_MULTITHREAD, 1, threadID, TRUE );
2188 	_endthreadex( 0 );
2189 	return( 0 );
2190 	}
testSessionTLSClientServerMultiThread(void)2191 int testSessionTLSClientServerMultiThread( void )
2192 	{
2193 	return( multiThreadDispatch( tlsClientMultiThread,
2194 								 tlsServerMultiThread, MAX_NO_THREADS ) );
2195 	}
2196 
testSessionSSLClientServerDebugCheck(void)2197 int testSessionSSLClientServerDebugCheck( void )
2198 	{
2199 #ifndef NDEBUG
2200 	if( !sslClientServer( SSL_TEST_CORRUPT_HANDSHAKE ) )
2201 		return( FALSE );	/* Detect corruption of handshake data */
2202 	if( !sslClientServer( SSL_TEST_CORRUPT_DATA ) )
2203 		return( FALSE );	/* Detect corruption of payload data */
2204 	if( !sslClientServer( SSL_TEST_WRONGCERT ) )
2205 		return( FALSE );	/* Detect wrong key for server */
2206 	if( !sslClientServer( SSL_TEST_BADSIG_HASH ) )
2207 		return( FALSE );	/* Detect corruption of signed DH params */
2208 	if( !sslClientServer( SSL_TEST_BADSIG_DATA ) )
2209 		return( FALSE );	/* Detect corruption of signed DH params */
2210 	if( !tlsClientServer( SSL_TEST_CORRUPT_HANDSHAKE ) )
2211 		return( FALSE );	/* Detect corruption of handshake data */
2212 	if( !tlsClientServer( SSL_TEST_CORRUPT_DATA ) )
2213 		return( FALSE );	/* Detect corruption of payload data */
2214 	if( !tlsClientServer( SSL_TEST_WRONGCERT ) )
2215 		return( FALSE );	/* Detect wrong key for server */
2216 	if( !tlsClientServer( SSL_TEST_BADSIG_HASH ) )
2217 		return( FALSE );	/* Detect corruption of signed DH params */
2218 	if( !tlsClientServer( SSL_TEST_BADSIG_DATA ) )
2219 		return( FALSE );	/* Detect corruption of signed DH params */
2220 	cryptSetFaultType( FAULT_NONE );
2221 #endif /* !NDEBUG */
2222 	return( TRUE );
2223 	}
2224 #endif /* WINDOWS_THREADS */
2225 
2226 #endif /* TEST_SESSION || TEST_SESSION_LOOPBACK */
2227