]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/tls-sspi.c
Add SSLOptions to enable Diffie-Hellman key exchange and disable TLS/1.0.
[thirdparty/cups.git] / cups / tls-sspi.c
1 /*
2 * "$Id$"
3 *
4 * TLS support for CUPS on Windows using the Security Support Provider
5 * Interface (SSPI).
6 *
7 * Copyright 2010-2015 by Apple Inc.
8 *
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 */
17
18 /**** This file is included from tls.c ****/
19
20 /*
21 * Include necessary headers...
22 */
23
24 #include "debug-private.h"
25
26
27 /*
28 * Include necessary libraries...
29 */
30
31 #pragma comment(lib, "Crypt32.lib")
32 #pragma comment(lib, "Secur32.lib")
33 #pragma comment(lib, "Ws2_32.lib")
34
35
36 /*
37 * Constants...
38 */
39
40 #ifndef SECURITY_FLAG_IGNORE_UNKNOWN_CA
41 # define SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00000100 /* Untrusted root */
42 #endif /* SECURITY_FLAG_IGNORE_UNKNOWN_CA */
43
44 #ifndef SECURITY_FLAG_IGNORE_CERT_CN_INVALID
45 # define SECURITY_FLAG_IGNORE_CERT_CN_INVALID 0x00001000 /* Common name does not match */
46 #endif /* !SECURITY_FLAG_IGNORE_CERT_CN_INVALID */
47
48 #ifndef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
49 # define SECURITY_FLAG_IGNORE_CERT_DATE_INVALID 0x00002000 /* Expired X509 Cert. */
50 #endif /* !SECURITY_FLAG_IGNORE_CERT_DATE_INVALID */
51
52
53 /*
54 * Local globals...
55 */
56
57 static int tls_options = 0;/* Options for TLS connections */
58
59
60 /*
61 * Local functions...
62 */
63
64 static _http_sspi_t *http_sspi_alloc(void);
65 static int http_sspi_client(http_t *http, const char *hostname);
66 static PCCERT_CONTEXT http_sspi_create_credential(http_credential_t *cred);
67 static BOOL http_sspi_find_credentials(http_t *http, const LPWSTR containerName, const char *common_name);
68 static void http_sspi_free(_http_sspi_t *sspi);
69 static BOOL http_sspi_make_credentials(_http_sspi_t *sspi, const LPWSTR containerName, const char *common_name, _http_mode_t mode, int years);
70 static int http_sspi_server(http_t *http, const char *hostname);
71 static void http_sspi_set_allows_any_root(_http_sspi_t *sspi, BOOL allow);
72 static void http_sspi_set_allows_expired_certs(_http_sspi_t *sspi, BOOL allow);
73 static const char *http_sspi_strerror(char *buffer, size_t bufsize, DWORD code);
74 static DWORD http_sspi_verify(PCCERT_CONTEXT cert, const char *common_name, DWORD dwCertFlags);
75
76
77 /*
78 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
79 *
80 * @since CUPS 2.0/OS 10.10@
81 */
82
83 int /* O - 1 on success, 0 on failure */
84 cupsMakeServerCredentials(
85 const char *path, /* I - Keychain path or @code NULL@ for default */
86 const char *common_name, /* I - Common name */
87 int num_alt_names, /* I - Number of subject alternate names */
88 const char **alt_names, /* I - Subject Alternate Names */
89 time_t expiration_date) /* I - Expiration date */
90 {
91 _http_sspi_t *sspi; /* SSPI data */
92 int ret; /* Return value */
93
94
95 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
96
97 (void)path;
98 (void)num_alt_names;
99 (void)alt_names;
100
101 sspi = http_sspi_alloc();
102 ret = http_sspi_make_credentials(sspi, L"ServerContainer", common_name, _HTTP_MODE_SERVER, (int)((expiration_date - time(NULL) + 86399) / 86400 / 365));
103
104 http_sspi_free(sspi);
105
106 return (ret);
107 }
108
109
110 /*
111 * 'cupsSetServerCredentials()' - Set the default server credentials.
112 *
113 * Note: The server credentials are used by all threads in the running process.
114 * This function is threadsafe.
115 *
116 * @since CUPS 2.0/OS 10.10@
117 */
118
119 int /* O - 1 on success, 0 on failure */
120 cupsSetServerCredentials(
121 const char *path, /* I - Keychain path or @code NULL@ for default */
122 const char *common_name, /* I - Default common name for server */
123 int auto_create) /* I - 1 = automatically create self-signed certificates */
124 {
125 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
126
127 (void)path;
128 (void)common_name;
129 (void)auto_create;
130
131 return (0);
132 }
133
134
135 /*
136 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
137 * an encrypted connection.
138 *
139 * @since CUPS 1.5/OS X 10.7@
140 */
141
142 int /* O - Status of call (0 = success) */
143 httpCopyCredentials(
144 http_t *http, /* I - Connection to server */
145 cups_array_t **credentials) /* O - Array of credentials */
146 {
147 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
148
149 if (!http || !http->tls || !http->tls->remoteCert || !credentials)
150 {
151 if (credentials)
152 *credentials = NULL;
153
154 return (-1);
155 }
156
157 *credentials = cupsArrayNew(NULL, NULL);
158 httpAddCredential(*credentials, http->tls->remoteCert->pbCertEncoded, http->tls->remoteCert->cbCertEncoded);
159
160 return (0);
161 }
162
163
164 /*
165 * '_httpCreateCredentials()' - Create credentials in the internal format.
166 */
167
168 http_tls_credentials_t /* O - Internal credentials */
169 _httpCreateCredentials(
170 cups_array_t *credentials) /* I - Array of credentials */
171 {
172 return (http_sspi_create_credential((http_credential_t *)cupsArrayFirst(credentials)));
173 }
174
175
176 /*
177 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
178 *
179 * @since CUPS 2.0/OS 10.10@
180 */
181
182 int /* O - 1 if valid, 0 otherwise */
183 httpCredentialsAreValidForName(
184 cups_array_t *credentials, /* I - Credentials */
185 const char *common_name) /* I - Name to check */
186 {
187 int valid = 1; /* Valid name? */
188 PCCERT_CONTEXT cert = http_sspi_create_credential((http_credential_t *)cupsArrayFirst(credentials));
189 /* Certificate */
190 char cert_name[1024]; /* Name from certificate */
191
192
193 if (cert)
194 {
195 if (CertNameToStr(X509_ASN_ENCODING, &(cert->pCertInfo->Subject), CERT_SIMPLE_NAME_STR, cert_name, sizeof(cert_name)))
196 {
197 /*
198 * Extract common name at end...
199 */
200
201 char *ptr = strrchr(cert_name, ',');
202 if (ptr && ptr[1])
203 _cups_strcpy(cert_name, ptr + 2);
204 }
205 else
206 strlcpy(cert_name, "unknown", sizeof(cert_name));
207
208 CertFreeCertificateContext(cert);
209 }
210 else
211 strlcpy(cert_name, "unknown", sizeof(cert_name));
212
213 /*
214 * Compare the common names...
215 */
216
217 if (_cups_strcasecmp(common_name, cert_name))
218 {
219 /*
220 * Not an exact match for the common name, check for wildcard certs...
221 */
222
223 const char *domain = strchr(common_name, '.');
224 /* Domain in common name */
225
226 if (strncmp(cert_name, "*.", 2) || !domain || _cups_strcasecmp(domain, cert_name + 1))
227 {
228 /*
229 * Not a wildcard match.
230 */
231
232 /* TODO: Check subject alternate names */
233 valid = 0;
234 }
235 }
236
237 return (valid);
238 }
239
240
241 /*
242 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
243 *
244 * @since CUPS 2.0/OS 10.10@
245 */
246
247 http_trust_t /* O - Level of trust */
248 httpCredentialsGetTrust(
249 cups_array_t *credentials, /* I - Credentials */
250 const char *common_name) /* I - Common name for trust lookup */
251 {
252 http_trust_t trust = HTTP_TRUST_OK; /* Level of trust */
253 PCCERT_CONTEXT cert = NULL; /* Certificate to validate */
254 DWORD certFlags = 0; /* Cert verification flags */
255 _cups_globals_t *cg = _cupsGlobals(); /* Per-thread global data */
256
257
258 if (!common_name)
259 return (HTTP_TRUST_UNKNOWN);
260
261 cert = http_sspi_create_credential((http_credential_t *)cupsArrayFirst(credentials));
262 if (!cert)
263 return (HTTP_TRUST_UNKNOWN);
264
265 if (cg->any_root < 0)
266 _cupsSetDefaults();
267
268 if (cg->any_root)
269 certFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
270
271 if (cg->expired_certs)
272 certFlags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
273
274 if (!cg->validate_certs)
275 certFlags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
276
277 if (http_sspi_verify(cert, common_name, certFlags) != SEC_E_OK)
278 trust = HTTP_TRUST_INVALID;
279
280 CertFreeCertificateContext(cert);
281
282 return (trust);
283 }
284
285
286 /*
287 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
288 *
289 * @since CUPS 2.0/OS 10.10@
290 */
291
292 time_t /* O - Expiration date of credentials */
293 httpCredentialsGetExpiration(
294 cups_array_t *credentials) /* I - Credentials */
295 {
296 time_t expiration_date = 0; /* Expiration data of credentials */
297 PCCERT_CONTEXT cert = http_sspi_create_credential((http_credential_t *)cupsArrayFirst(credentials));
298 /* Certificate */
299
300 if (cert)
301 {
302 SYSTEMTIME systime; /* System time */
303 struct tm tm; /* UNIX date/time */
304
305 FileTimeToSystemTime(&(cert->pCertInfo->NotAfter), &systime);
306
307 tm.tm_year = systime.wYear - 1900;
308 tm.tm_mon = systime.wMonth - 1;
309 tm.tm_mday = systime.wDay;
310 tm.tm_hour = systime.wHour;
311 tm.tm_min = systime.wMinute;
312 tm.tm_sec = systime.wSecond;
313
314 expiration_date = mktime(&tm);
315
316 CertFreeCertificateContext(cert);
317 }
318
319 return (expiration_date);
320 }
321
322
323 /*
324 * 'httpCredentialsString()' - Return a string representing the credentials.
325 *
326 * @since CUPS 2.0/OS 10.10@
327 */
328
329 size_t /* O - Total size of credentials string */
330 httpCredentialsString(
331 cups_array_t *credentials, /* I - Credentials */
332 char *buffer, /* I - Buffer or @code NULL@ */
333 size_t bufsize) /* I - Size of buffer */
334 {
335 http_credential_t *first = (http_credential_t *)cupsArrayFirst(credentials);
336 /* First certificate */
337 PCCERT_CONTEXT cert; /* Certificate */
338
339
340 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
341
342 if (!buffer)
343 return (0);
344
345 if (buffer && bufsize > 0)
346 *buffer = '\0';
347
348 cert = http_sspi_create_credential(first);
349
350 if (cert)
351 {
352 char cert_name[256]; /* Common name */
353 SYSTEMTIME systime; /* System time */
354 struct tm tm; /* UNIX date/time */
355 time_t expiration; /* Expiration date of cert */
356 _cups_md5_state_t md5_state; /* MD5 state */
357 unsigned char md5_digest[16]; /* MD5 result */
358
359 FileTimeToSystemTime(&(cert->pCertInfo->NotAfter), &systime);
360
361 tm.tm_year = systime.wYear - 1900;
362 tm.tm_mon = systime.wMonth - 1;
363 tm.tm_mday = systime.wDay;
364 tm.tm_hour = systime.wHour;
365 tm.tm_min = systime.wMinute;
366 tm.tm_sec = systime.wSecond;
367
368 expiration = mktime(&tm);
369
370 if (CertNameToStr(X509_ASN_ENCODING, &(cert->pCertInfo->Subject), CERT_SIMPLE_NAME_STR, cert_name, sizeof(cert_name)))
371 {
372 /*
373 * Extract common name at end...
374 */
375
376 char *ptr = strrchr(cert_name, ',');
377 if (ptr && ptr[1])
378 _cups_strcpy(cert_name, ptr + 2);
379 }
380 else
381 strlcpy(cert_name, "unknown", sizeof(cert_name));
382
383 _cupsMD5Init(&md5_state);
384 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
385 _cupsMD5Finish(&md5_state, md5_digest);
386
387 snprintf(buffer, bufsize, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", cert_name, httpGetDateString(expiration), md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
388
389 CertFreeCertificateContext(cert);
390 }
391
392 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
393
394 return (strlen(buffer));
395 }
396
397
398 /*
399 * '_httpFreeCredentials()' - Free internal credentials.
400 */
401
402 void
403 _httpFreeCredentials(
404 http_tls_credentials_t credentials) /* I - Internal credentials */
405 {
406 if (!credentials)
407 return;
408
409 CertFreeCertificateContext(credentials);
410 }
411
412
413 /*
414 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
415 *
416 * @since CUPS 2.0/OS 10.10@
417 */
418
419 int /* O - 0 on success, -1 on error */
420 httpLoadCredentials(
421 const char *path, /* I - Keychain path or @code NULL@ for default */
422 cups_array_t **credentials, /* IO - Credentials */
423 const char *common_name) /* I - Common name for credentials */
424 {
425 HCERTSTORE store = NULL; /* Certificate store */
426 PCCERT_CONTEXT storedContext = NULL; /* Context created from the store */
427 DWORD dwSize = 0; /* 32 bit size */
428 PBYTE p = NULL; /* Temporary storage */
429 HCRYPTPROV hProv = (HCRYPTPROV)NULL;
430 /* Handle to a CSP */
431 CERT_NAME_BLOB sib; /* Arbitrary array of bytes */
432 #ifdef DEBUG
433 char error[1024]; /* Error message buffer */
434 #endif /* DEBUG */
435
436
437 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
438
439 (void)path;
440
441 if (credentials)
442 {
443 *credentials = NULL;
444 }
445 else
446 {
447 DEBUG_puts("1httpLoadCredentials: NULL credentials pointer, returning -1.");
448 return (-1);
449 }
450
451 if (!common_name)
452 {
453 DEBUG_puts("1httpLoadCredentials: Bad common name, returning -1.");
454 return (-1);
455 }
456
457 if (!CryptAcquireContextW(&hProv, L"RememberedContainer", MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET))
458 {
459 if (GetLastError() == NTE_EXISTS)
460 {
461 if (!CryptAcquireContextW(&hProv, L"RememberedContainer", MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
462 {
463 DEBUG_printf(("1httpLoadCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
464 goto cleanup;
465 }
466 }
467 }
468
469 store = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, hProv, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_OPEN_EXISTING_FLAG, L"MY");
470
471 if (!store)
472 {
473 DEBUG_printf(("1httpLoadCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
474 goto cleanup;
475 }
476
477 dwSize = 0;
478
479 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, NULL, &dwSize, NULL))
480 {
481 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
482 goto cleanup;
483 }
484
485 p = (PBYTE)malloc(dwSize);
486
487 if (!p)
488 {
489 DEBUG_printf(("1httpLoadCredentials: malloc failed for %d bytes.", dwSize));
490 goto cleanup;
491 }
492
493 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, p, &dwSize, NULL))
494 {
495 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
496 goto cleanup;
497 }
498
499 sib.cbData = dwSize;
500 sib.pbData = p;
501
502 storedContext = CertFindCertificateInStore(store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_NAME, &sib, NULL);
503
504 if (!storedContext)
505 {
506 DEBUG_printf(("1httpLoadCredentials: Unable to find credentials for \"%s\".", common_name));
507 goto cleanup;
508 }
509
510 *credentials = cupsArrayNew(NULL, NULL);
511 httpAddCredential(*credentials, storedContext->pbCertEncoded, storedContext->cbCertEncoded);
512
513 cleanup:
514
515 /*
516 * Cleanup
517 */
518
519 if (storedContext)
520 CertFreeCertificateContext(storedContext);
521
522 if (p)
523 free(p);
524
525 if (store)
526 CertCloseStore(store, 0);
527
528 if (hProv)
529 CryptReleaseContext(hProv, 0);
530
531 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials ? 0 : -1));
532
533 return (*credentials ? 0 : -1);
534 }
535
536
537 /*
538 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
539 *
540 * @since CUPS 2.0/OS 10.10@
541 */
542
543 int /* O - -1 on error, 0 on success */
544 httpSaveCredentials(
545 const char *path, /* I - Keychain path or @code NULL@ for default */
546 cups_array_t *credentials, /* I - Credentials */
547 const char *common_name) /* I - Common name for credentials */
548 {
549 HCERTSTORE store = NULL; /* Certificate store */
550 PCCERT_CONTEXT storedContext = NULL; /* Context created from the store */
551 PCCERT_CONTEXT createdContext = NULL; /* Context created by us */
552 DWORD dwSize = 0; /* 32 bit size */
553 PBYTE p = NULL; /* Temporary storage */
554 HCRYPTPROV hProv = (HCRYPTPROV)NULL;
555 /* Handle to a CSP */
556 CRYPT_KEY_PROV_INFO ckp; /* Handle to crypto key */
557 int ret = -1; /* Return value */
558 #ifdef DEBUG
559 char error[1024]; /* Error message buffer */
560 #endif /* DEBUG */
561
562
563 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path, credentials, common_name));
564
565 (void)path;
566
567 if (!common_name)
568 {
569 DEBUG_puts("1httpSaveCredentials: Bad common name, returning -1.");
570 return (-1);
571 }
572
573 createdContext = http_sspi_create_credential((http_credential_t *)cupsArrayFirst(credentials));
574 if (!createdContext)
575 {
576 DEBUG_puts("1httpSaveCredentials: Bad credentials, returning -1.");
577 return (-1);
578 }
579
580 if (!CryptAcquireContextW(&hProv, L"RememberedContainer", MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET))
581 {
582 if (GetLastError() == NTE_EXISTS)
583 {
584 if (!CryptAcquireContextW(&hProv, L"RememberedContainer", MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
585 {
586 DEBUG_printf(("1httpSaveCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
587 goto cleanup;
588 }
589 }
590 }
591
592 store = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, hProv, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_OPEN_EXISTING_FLAG, L"MY");
593
594 if (!store)
595 {
596 DEBUG_printf(("1httpSaveCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
597 goto cleanup;
598 }
599
600 dwSize = 0;
601
602 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, NULL, &dwSize, NULL))
603 {
604 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
605 goto cleanup;
606 }
607
608 p = (PBYTE)malloc(dwSize);
609
610 if (!p)
611 {
612 DEBUG_printf(("1httpSaveCredentials: malloc failed for %d bytes.", dwSize));
613 goto cleanup;
614 }
615
616 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, p, &dwSize, NULL))
617 {
618 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
619 goto cleanup;
620 }
621
622 /*
623 * Add the created context to the named store, and associate it with the named
624 * container...
625 */
626
627 if (!CertAddCertificateContextToStore(store, createdContext, CERT_STORE_ADD_REPLACE_EXISTING, &storedContext))
628 {
629 DEBUG_printf(("1httpSaveCredentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
630 goto cleanup;
631 }
632
633 ZeroMemory(&ckp, sizeof(ckp));
634 ckp.pwszContainerName = L"RememberedContainer";
635 ckp.pwszProvName = MS_DEF_PROV_W;
636 ckp.dwProvType = PROV_RSA_FULL;
637 ckp.dwFlags = CRYPT_MACHINE_KEYSET;
638 ckp.dwKeySpec = AT_KEYEXCHANGE;
639
640 if (!CertSetCertificateContextProperty(storedContext, CERT_KEY_PROV_INFO_PROP_ID, 0, &ckp))
641 {
642 DEBUG_printf(("1httpSaveCredentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(error, sizeof(error), GetLastError())));
643 goto cleanup;
644 }
645
646 ret = 0;
647
648 cleanup:
649
650 /*
651 * Cleanup
652 */
653
654 if (createdContext)
655 CertFreeCertificateContext(createdContext);
656
657 if (storedContext)
658 CertFreeCertificateContext(storedContext);
659
660 if (p)
661 free(p);
662
663 if (store)
664 CertCloseStore(store, 0);
665
666 if (hProv)
667 CryptReleaseContext(hProv, 0);
668
669 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret));
670 return (ret);
671 }
672
673
674 /*
675 * '_httpTLSInitialize()' - Initialize the TLS stack.
676 */
677
678 void
679 _httpTLSInitialize(void)
680 {
681 /*
682 * Nothing to do...
683 */
684 }
685
686
687 /*
688 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
689 */
690
691 size_t /* O - Bytes available */
692 _httpTLSPending(http_t *http) /* I - HTTP connection */
693 {
694 if (http->tls)
695 return (http->tls->readBufferUsed);
696 else
697 return (0);
698 }
699
700
701 /*
702 * '_httpTLSRead()' - Read from a SSL/TLS connection.
703 */
704
705 int /* O - Bytes read */
706 _httpTLSRead(http_t *http, /* I - HTTP connection */
707 char *buf, /* I - Buffer to store data */
708 int len) /* I - Length of buffer */
709 {
710 int i; /* Looping var */
711 _http_sspi_t *sspi = http->tls; /* SSPI data */
712 SecBufferDesc message; /* Array of SecBuffer struct */
713 SecBuffer buffers[4] = { 0 }; /* Security package buffer */
714 int num = 0; /* Return value */
715 PSecBuffer pDataBuffer; /* Data buffer */
716 PSecBuffer pExtraBuffer; /* Excess data buffer */
717 SECURITY_STATUS scRet; /* SSPI status */
718
719
720 DEBUG_printf(("4_httpTLSRead(http=%p, buf=%p, len=%d)", http, buf, len));
721
722 /*
723 * If there are bytes that have already been decrypted and have not yet been
724 * read, return those...
725 */
726
727 if (sspi->readBufferUsed > 0)
728 {
729 int bytesToCopy = min(sspi->readBufferUsed, len);
730 /* Number of bytes to copy */
731
732 memcpy(buf, sspi->readBuffer, bytesToCopy);
733 sspi->readBufferUsed -= bytesToCopy;
734
735 if (sspi->readBufferUsed > 0)
736 memmove(sspi->readBuffer, sspi->readBuffer + bytesToCopy, sspi->readBufferUsed);
737
738 DEBUG_printf(("5_httpTLSRead: Returning %d bytes previously decrypted.", bytesToCopy));
739
740 return (bytesToCopy);
741 }
742
743 /*
744 * Initialize security buffer structs
745 */
746
747 message.ulVersion = SECBUFFER_VERSION;
748 message.cBuffers = 4;
749 message.pBuffers = buffers;
750
751 do
752 {
753 /*
754 * If there is not enough space in the buffer, then increase its size...
755 */
756
757 if (sspi->decryptBufferLength <= sspi->decryptBufferUsed)
758 {
759 BYTE *temp; /* New buffer */
760
761 if (sspi->decryptBufferLength >= 262144)
762 {
763 WSASetLastError(E_OUTOFMEMORY);
764 DEBUG_puts("_httpTLSRead: Decryption buffer too large (>256k)");
765 return (-1);
766 }
767
768 if ((temp = realloc(sspi->decryptBuffer, sspi->decryptBufferLength + 4096)) == NULL)
769 {
770 DEBUG_printf(("_httpTLSRead: Unable to allocate %d byte decryption buffer.", sspi->decryptBufferLength + 4096));
771 WSASetLastError(E_OUTOFMEMORY);
772 return (-1);
773 }
774
775 sspi->decryptBufferLength += 4096;
776 sspi->decryptBuffer = temp;
777
778 DEBUG_printf(("_httpTLSRead: Resized decryption buffer to %d bytes.", sspi->decryptBufferLength));
779 }
780
781 buffers[0].pvBuffer = sspi->decryptBuffer;
782 buffers[0].cbBuffer = (unsigned long)sspi->decryptBufferUsed;
783 buffers[0].BufferType = SECBUFFER_DATA;
784 buffers[1].BufferType = SECBUFFER_EMPTY;
785 buffers[2].BufferType = SECBUFFER_EMPTY;
786 buffers[3].BufferType = SECBUFFER_EMPTY;
787
788 DEBUG_printf(("5_httpTLSRead: decryptBufferUsed=%d", sspi->decryptBufferUsed));
789
790 scRet = DecryptMessage(&sspi->context, &message, 0, NULL);
791
792 if (scRet == SEC_E_INCOMPLETE_MESSAGE)
793 {
794 num = recv(http->fd, sspi->decryptBuffer + sspi->decryptBufferUsed, (int)(sspi->decryptBufferLength - sspi->decryptBufferUsed), 0);
795 if (num < 0)
796 {
797 DEBUG_printf(("5_httpTLSRead: recv failed: %d", WSAGetLastError()));
798 return (-1);
799 }
800 else if (num == 0)
801 {
802 DEBUG_puts("5_httpTLSRead: Server disconnected.");
803 return (0);
804 }
805
806 DEBUG_printf(("5_httpTLSRead: Read %d bytes into decryption buffer.", num));
807
808 sspi->decryptBufferUsed += num;
809 }
810 }
811 while (scRet == SEC_E_INCOMPLETE_MESSAGE);
812
813 if (scRet == SEC_I_CONTEXT_EXPIRED)
814 {
815 DEBUG_puts("5_httpTLSRead: Context expired.");
816 WSASetLastError(WSAECONNRESET);
817 return (-1);
818 }
819 else if (scRet != SEC_E_OK)
820 {
821 DEBUG_printf(("5_httpTLSRead: DecryptMessage failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
822 WSASetLastError(WSASYSCALLFAILURE);
823 return (-1);
824 }
825
826 /*
827 * The decryption worked. Now, locate data buffer.
828 */
829
830 pDataBuffer = NULL;
831 pExtraBuffer = NULL;
832
833 for (i = 1; i < 4; i++)
834 {
835 if (buffers[i].BufferType == SECBUFFER_DATA)
836 pDataBuffer = &buffers[i];
837 else if (!pExtraBuffer && (buffers[i].BufferType == SECBUFFER_EXTRA))
838 pExtraBuffer = &buffers[i];
839 }
840
841 /*
842 * If a data buffer is found, then copy the decrypted bytes to the passed-in
843 * buffer...
844 */
845
846 if (pDataBuffer)
847 {
848 int bytesToCopy = min((int)pDataBuffer->cbBuffer, len);
849 /* Number of bytes to copy into buf */
850 int bytesToSave = pDataBuffer->cbBuffer - bytesToCopy;
851 /* Number of bytes to save in our read buffer */
852
853 if (bytesToCopy)
854 memcpy(buf, pDataBuffer->pvBuffer, bytesToCopy);
855
856 /*
857 * If there are more decrypted bytes than can be copied to the passed in
858 * buffer, then save them...
859 */
860
861 if (bytesToSave)
862 {
863 if ((sspi->readBufferLength - sspi->readBufferUsed) < bytesToSave)
864 {
865 BYTE *temp; /* New buffer pointer */
866
867 if ((temp = realloc(sspi->readBuffer, sspi->readBufferUsed + bytesToSave)) == NULL)
868 {
869 DEBUG_printf(("_httpTLSRead: Unable to allocate %d bytes.", sspi->readBufferUsed + bytesToSave));
870 WSASetLastError(E_OUTOFMEMORY);
871 return (-1);
872 }
873
874 sspi->readBufferLength = sspi->readBufferUsed + bytesToSave;
875 sspi->readBuffer = temp;
876 }
877
878 memcpy(((BYTE *)sspi->readBuffer) + sspi->readBufferUsed, ((BYTE *)pDataBuffer->pvBuffer) + bytesToCopy, bytesToSave);
879
880 sspi->readBufferUsed += bytesToSave;
881 }
882
883 num = bytesToCopy;
884 }
885 else
886 {
887 DEBUG_puts("_httpTLSRead: Unable to find data buffer.");
888 WSASetLastError(WSASYSCALLFAILURE);
889 return (-1);
890 }
891
892 /*
893 * If the decryption process left extra bytes, then save those back in
894 * decryptBuffer. They will be processed the next time through the loop.
895 */
896
897 if (pExtraBuffer)
898 {
899 memmove(sspi->decryptBuffer, pExtraBuffer->pvBuffer, pExtraBuffer->cbBuffer);
900 sspi->decryptBufferUsed = pExtraBuffer->cbBuffer;
901 }
902 else
903 {
904 sspi->decryptBufferUsed = 0;
905 }
906
907 return (num);
908 }
909
910
911 /*
912 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
913 */
914
915 void
916 _httpTLSSetOptions(int options) /* I - Options */
917 {
918 tls_options = options;
919 }
920
921
922 /*
923 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
924 */
925
926 int /* O - 0 on success, -1 on failure */
927 _httpTLSStart(http_t *http) /* I - HTTP connection */
928 {
929 char hostname[256], /* Hostname */
930 *hostptr; /* Pointer into hostname */
931
932
933 DEBUG_printf(("7_httpTLSStart(http=%p)", http));
934
935 if ((http->tls = http_sspi_alloc()) == NULL)
936 return (-1);
937
938 if (http->mode == _HTTP_MODE_CLIENT)
939 {
940 /*
941 * Client: determine hostname...
942 */
943
944 if (httpAddrLocalhost(http->hostaddr))
945 {
946 strlcpy(hostname, "localhost", sizeof(hostname));
947 }
948 else
949 {
950 /*
951 * Otherwise make sure the hostname we have does not end in a trailing dot.
952 */
953
954 strlcpy(hostname, http->hostname, sizeof(hostname));
955 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
956 *hostptr == '.')
957 *hostptr = '\0';
958 }
959
960 return (http_sspi_client(http, hostname));
961 }
962 else
963 {
964 /*
965 * Server: determine hostname to use...
966 */
967
968 if (http->fields[HTTP_FIELD_HOST][0])
969 {
970 /*
971 * Use hostname for TLS upgrade...
972 */
973
974 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
975 }
976 else
977 {
978 /*
979 * Resolve hostname from connection address...
980 */
981
982 http_addr_t addr; /* Connection address */
983 socklen_t addrlen; /* Length of address */
984
985 addrlen = sizeof(addr);
986 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
987 {
988 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
989 hostname[0] = '\0';
990 }
991 else if (httpAddrLocalhost(&addr))
992 hostname[0] = '\0';
993 else
994 {
995 httpAddrLookup(&addr, hostname, sizeof(hostname));
996 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
997 }
998 }
999
1000 return (http_sspi_server(http, hostname));
1001 }
1002 }
1003
1004
1005 /*
1006 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1007 */
1008
1009 void
1010 _httpTLSStop(http_t *http) /* I - HTTP connection */
1011 {
1012 _http_sspi_t *sspi = http->tls; /* SSPI data */
1013
1014
1015 if (sspi->contextInitialized && http->fd >= 0)
1016 {
1017 SecBufferDesc message; /* Array of SecBuffer struct */
1018 SecBuffer buffers[1] = { 0 };
1019 /* Security package buffer */
1020 DWORD dwType; /* Type */
1021 DWORD status; /* Status */
1022
1023 /*
1024 * Notify schannel that we are about to close the connection.
1025 */
1026
1027 dwType = SCHANNEL_SHUTDOWN;
1028
1029 buffers[0].pvBuffer = &dwType;
1030 buffers[0].BufferType = SECBUFFER_TOKEN;
1031 buffers[0].cbBuffer = sizeof(dwType);
1032
1033 message.cBuffers = 1;
1034 message.pBuffers = buffers;
1035 message.ulVersion = SECBUFFER_VERSION;
1036
1037 status = ApplyControlToken(&sspi->context, &message);
1038
1039 if (SUCCEEDED(status))
1040 {
1041 PBYTE pbMessage; /* Message buffer */
1042 DWORD cbMessage; /* Message buffer count */
1043 DWORD cbData; /* Data count */
1044 DWORD dwSSPIFlags; /* SSL attributes we requested */
1045 DWORD dwSSPIOutFlags; /* SSL attributes we received */
1046 TimeStamp tsExpiry; /* Time stamp */
1047
1048 dwSSPIFlags = ASC_REQ_SEQUENCE_DETECT |
1049 ASC_REQ_REPLAY_DETECT |
1050 ASC_REQ_CONFIDENTIALITY |
1051 ASC_REQ_EXTENDED_ERROR |
1052 ASC_REQ_ALLOCATE_MEMORY |
1053 ASC_REQ_STREAM;
1054
1055 buffers[0].pvBuffer = NULL;
1056 buffers[0].BufferType = SECBUFFER_TOKEN;
1057 buffers[0].cbBuffer = 0;
1058
1059 message.cBuffers = 1;
1060 message.pBuffers = buffers;
1061 message.ulVersion = SECBUFFER_VERSION;
1062
1063 status = AcceptSecurityContext(&sspi->creds, &sspi->context, NULL,
1064 dwSSPIFlags, SECURITY_NATIVE_DREP, NULL,
1065 &message, &dwSSPIOutFlags, &tsExpiry);
1066
1067 if (SUCCEEDED(status))
1068 {
1069 pbMessage = buffers[0].pvBuffer;
1070 cbMessage = buffers[0].cbBuffer;
1071
1072 /*
1073 * Send the close notify message to the client.
1074 */
1075
1076 if (pbMessage && cbMessage)
1077 {
1078 cbData = send(http->fd, pbMessage, cbMessage, 0);
1079 if ((cbData == SOCKET_ERROR) || (cbData == 0))
1080 {
1081 status = WSAGetLastError();
1082 DEBUG_printf(("_httpTLSStop: sending close notify failed: %d", status));
1083 }
1084 else
1085 {
1086 FreeContextBuffer(pbMessage);
1087 }
1088 }
1089 }
1090 else
1091 {
1092 DEBUG_printf(("_httpTLSStop: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), status)));
1093 }
1094 }
1095 else
1096 {
1097 DEBUG_printf(("_httpTLSStop: ApplyControlToken failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), status)));
1098 }
1099 }
1100
1101 http_sspi_free(sspi);
1102
1103 http->tls = NULL;
1104 }
1105
1106
1107 /*
1108 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1109 */
1110
1111 int /* O - Bytes written */
1112 _httpTLSWrite(http_t *http, /* I - HTTP connection */
1113 const char *buf, /* I - Buffer holding data */
1114 int len) /* I - Length of buffer */
1115 {
1116 _http_sspi_t *sspi = http->tls; /* SSPI data */
1117 SecBufferDesc message; /* Array of SecBuffer struct */
1118 SecBuffer buffers[4] = { 0 }; /* Security package buffer */
1119 int bufferLen; /* Buffer length */
1120 int bytesLeft; /* Bytes left to write */
1121 const char *bufptr; /* Pointer into buffer */
1122 int num = 0; /* Return value */
1123
1124
1125 bufferLen = sspi->streamSizes.cbMaximumMessage + sspi->streamSizes.cbHeader + sspi->streamSizes.cbTrailer;
1126
1127 if (bufferLen > sspi->writeBufferLength)
1128 {
1129 BYTE *temp; /* New buffer pointer */
1130
1131 if ((temp = (BYTE *)realloc(sspi->writeBuffer, bufferLen)) == NULL)
1132 {
1133 DEBUG_printf(("_httpTLSWrite: Unable to allocate buffer of %d bytes.", bufferLen));
1134 WSASetLastError(E_OUTOFMEMORY);
1135 return (-1);
1136 }
1137
1138 sspi->writeBuffer = temp;
1139 sspi->writeBufferLength = bufferLen;
1140 }
1141
1142 bytesLeft = len;
1143 bufptr = buf;
1144
1145 while (bytesLeft)
1146 {
1147 int chunk = min((int)sspi->streamSizes.cbMaximumMessage, bytesLeft);
1148 /* Size of data to write */
1149 SECURITY_STATUS scRet; /* SSPI status */
1150
1151 /*
1152 * Copy user data into the buffer, starting just past the header...
1153 */
1154
1155 memcpy(sspi->writeBuffer + sspi->streamSizes.cbHeader, bufptr, chunk);
1156
1157 /*
1158 * Setup the SSPI buffers
1159 */
1160
1161 message.ulVersion = SECBUFFER_VERSION;
1162 message.cBuffers = 4;
1163 message.pBuffers = buffers;
1164
1165 buffers[0].pvBuffer = sspi->writeBuffer;
1166 buffers[0].cbBuffer = sspi->streamSizes.cbHeader;
1167 buffers[0].BufferType = SECBUFFER_STREAM_HEADER;
1168 buffers[1].pvBuffer = sspi->writeBuffer + sspi->streamSizes.cbHeader;
1169 buffers[1].cbBuffer = (unsigned long) chunk;
1170 buffers[1].BufferType = SECBUFFER_DATA;
1171 buffers[2].pvBuffer = sspi->writeBuffer + sspi->streamSizes.cbHeader + chunk;
1172 buffers[2].cbBuffer = sspi->streamSizes.cbTrailer;
1173 buffers[2].BufferType = SECBUFFER_STREAM_TRAILER;
1174 buffers[3].BufferType = SECBUFFER_EMPTY;
1175
1176 /*
1177 * Encrypt the data
1178 */
1179
1180 scRet = EncryptMessage(&sspi->context, 0, &message, 0);
1181
1182 if (FAILED(scRet))
1183 {
1184 DEBUG_printf(("_httpTLSWrite: EncryptMessage failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
1185 WSASetLastError(WSASYSCALLFAILURE);
1186 return (-1);
1187 }
1188
1189 /*
1190 * Send the data. Remember the size of the total data to send is the size
1191 * of the header, the size of the data the caller passed in and the size
1192 * of the trailer...
1193 */
1194
1195 num = send(http->fd, sspi->writeBuffer, buffers[0].cbBuffer + buffers[1].cbBuffer + buffers[2].cbBuffer, 0);
1196
1197 if (num <= 0)
1198 {
1199 DEBUG_printf(("_httpTLSWrite: send failed: %ld", WSAGetLastError()));
1200 return (num);
1201 }
1202
1203 bytesLeft -= chunk;
1204 bufptr += chunk;
1205 }
1206
1207 return (len);
1208 }
1209
1210
1211 #if 0
1212 /*
1213 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
1214 */
1215
1216 static int /* O - 0 on success, -1 on failure */
1217 http_setup_ssl(http_t *http) /* I - Connection to server */
1218 {
1219 char hostname[256], /* Hostname */
1220 *hostptr; /* Pointer into hostname */
1221
1222 TCHAR username[256]; /* Username returned from GetUserName() */
1223 TCHAR commonName[256];/* Common name for certificate */
1224 DWORD dwSize; /* 32 bit size */
1225
1226
1227 DEBUG_printf(("7http_setup_ssl(http=%p)", http));
1228
1229 /*
1230 * Get the hostname to use for SSL...
1231 */
1232
1233 if (httpAddrLocalhost(http->hostaddr))
1234 {
1235 strlcpy(hostname, "localhost", sizeof(hostname));
1236 }
1237 else
1238 {
1239 /*
1240 * Otherwise make sure the hostname we have does not end in a trailing dot.
1241 */
1242
1243 strlcpy(hostname, http->hostname, sizeof(hostname));
1244 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1245 *hostptr == '.')
1246 *hostptr = '\0';
1247 }
1248
1249 http->tls = http_sspi_alloc();
1250
1251 if (!http->tls)
1252 {
1253 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1254 return (-1);
1255 }
1256
1257 dwSize = sizeof(username) / sizeof(TCHAR);
1258 GetUserName(username, &dwSize);
1259 _sntprintf_s(commonName, sizeof(commonName) / sizeof(TCHAR),
1260 sizeof(commonName) / sizeof(TCHAR), TEXT("CN=%s"), username);
1261
1262 if (!_sspiGetCredentials(http->tls, L"ClientContainer",
1263 commonName, FALSE))
1264 {
1265 _sspiFree(http->tls);
1266 http->tls = NULL;
1267
1268 http->error = EIO;
1269 http->status = HTTP_STATUS_ERROR;
1270
1271 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI,
1272 _("Unable to establish a secure connection to host."), 1);
1273
1274 return (-1);
1275 }
1276
1277 _sspiSetAllowsAnyRoot(http->tls, TRUE);
1278 _sspiSetAllowsExpiredCerts(http->tls, TRUE);
1279
1280 if (!_sspiConnect(http->tls, hostname))
1281 {
1282 _sspiFree(http->tls);
1283 http->tls = NULL;
1284
1285 http->error = EIO;
1286 http->status = HTTP_STATUS_ERROR;
1287
1288 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI,
1289 _("Unable to establish a secure connection to host."), 1);
1290
1291 return (-1);
1292 }
1293
1294 return (0);
1295 }
1296 #endif // 0
1297
1298
1299 /*
1300 * 'http_sspi_alloc()' - Allocate SSPI object.
1301 */
1302
1303 static _http_sspi_t * /* O - New SSPI/SSL object */
1304 http_sspi_alloc(void)
1305 {
1306 return ((_http_sspi_t *)calloc(sizeof(_http_sspi_t), 1));
1307 }
1308
1309
1310 /*
1311 * 'http_sspi_client()' - Negotiate a TLS connection as a client.
1312 */
1313
1314 static int /* O - 0 on success, -1 on failure */
1315 http_sspi_client(http_t *http, /* I - Client connection */
1316 const char *hostname) /* I - Server hostname */
1317 {
1318 _http_sspi_t *sspi = http->tls; /* SSPI data */
1319 DWORD dwSize; /* Size for buffer */
1320 DWORD dwSSPIFlags; /* SSL connection attributes we want */
1321 DWORD dwSSPIOutFlags; /* SSL connection attributes we got */
1322 TimeStamp tsExpiry; /* Time stamp */
1323 SECURITY_STATUS scRet; /* Status */
1324 int cbData; /* Data count */
1325 SecBufferDesc inBuffer; /* Array of SecBuffer structs */
1326 SecBuffer inBuffers[2]; /* Security package buffer */
1327 SecBufferDesc outBuffer; /* Array of SecBuffer structs */
1328 SecBuffer outBuffers[1]; /* Security package buffer */
1329 int ret = 0; /* Return value */
1330 char username[1024], /* Current username */
1331 common_name[1024]; /* CN=username */
1332
1333
1334 DEBUG_printf(("4http_sspi_client(http=%p, hostname=\"%s\")", http, hostname));
1335
1336 dwSSPIFlags = ISC_REQ_SEQUENCE_DETECT |
1337 ISC_REQ_REPLAY_DETECT |
1338 ISC_REQ_CONFIDENTIALITY |
1339 ISC_RET_EXTENDED_ERROR |
1340 ISC_REQ_ALLOCATE_MEMORY |
1341 ISC_REQ_STREAM;
1342
1343 /*
1344 * Lookup the client certificate...
1345 */
1346
1347 dwSize = sizeof(username);
1348 GetUserName(username, &dwSize);
1349 snprintf(common_name, sizeof(common_name), "CN=%s", username);
1350
1351 if (!http_sspi_find_credentials(http, L"ClientContainer", common_name))
1352 if (!http_sspi_make_credentials(http->tls, L"ClientContainer", common_name, _HTTP_MODE_CLIENT, 10))
1353 {
1354 DEBUG_puts("5http_sspi_client: Unable to get client credentials.");
1355 return (-1);
1356 }
1357
1358 /*
1359 * Initiate a ClientHello message and generate a token.
1360 */
1361
1362 outBuffers[0].pvBuffer = NULL;
1363 outBuffers[0].BufferType = SECBUFFER_TOKEN;
1364 outBuffers[0].cbBuffer = 0;
1365
1366 outBuffer.cBuffers = 1;
1367 outBuffer.pBuffers = outBuffers;
1368 outBuffer.ulVersion = SECBUFFER_VERSION;
1369
1370 scRet = InitializeSecurityContext(&sspi->creds, NULL, TEXT(""), dwSSPIFlags, 0, SECURITY_NATIVE_DREP, NULL, 0, &sspi->context, &outBuffer, &dwSSPIOutFlags, &tsExpiry);
1371
1372 if (scRet != SEC_I_CONTINUE_NEEDED)
1373 {
1374 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(1) failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
1375 return (-1);
1376 }
1377
1378 /*
1379 * Send response to server if there is one.
1380 */
1381
1382 if (outBuffers[0].cbBuffer && outBuffers[0].pvBuffer)
1383 {
1384 if ((cbData = send(http->fd, outBuffers[0].pvBuffer, outBuffers[0].cbBuffer, 0)) <= 0)
1385 {
1386 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1387 FreeContextBuffer(outBuffers[0].pvBuffer);
1388 DeleteSecurityContext(&sspi->context);
1389 return (-1);
1390 }
1391
1392 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData));
1393
1394 FreeContextBuffer(outBuffers[0].pvBuffer);
1395 outBuffers[0].pvBuffer = NULL;
1396 }
1397
1398 dwSSPIFlags = ISC_REQ_MANUAL_CRED_VALIDATION |
1399 ISC_REQ_SEQUENCE_DETECT |
1400 ISC_REQ_REPLAY_DETECT |
1401 ISC_REQ_CONFIDENTIALITY |
1402 ISC_RET_EXTENDED_ERROR |
1403 ISC_REQ_ALLOCATE_MEMORY |
1404 ISC_REQ_STREAM;
1405
1406 sspi->decryptBufferUsed = 0;
1407
1408 /*
1409 * Loop until the handshake is finished or an error occurs.
1410 */
1411
1412 scRet = SEC_I_CONTINUE_NEEDED;
1413
1414 while(scRet == SEC_I_CONTINUE_NEEDED ||
1415 scRet == SEC_E_INCOMPLETE_MESSAGE ||
1416 scRet == SEC_I_INCOMPLETE_CREDENTIALS)
1417 {
1418 if (sspi->decryptBufferUsed == 0 || scRet == SEC_E_INCOMPLETE_MESSAGE)
1419 {
1420 if (sspi->decryptBufferLength <= sspi->decryptBufferUsed)
1421 {
1422 BYTE *temp; /* New buffer */
1423
1424 if (sspi->decryptBufferLength >= 262144)
1425 {
1426 WSASetLastError(E_OUTOFMEMORY);
1427 DEBUG_puts("5http_sspi_client: Decryption buffer too large (>256k)");
1428 return (-1);
1429 }
1430
1431 if ((temp = realloc(sspi->decryptBuffer, sspi->decryptBufferLength + 4096)) == NULL)
1432 {
1433 DEBUG_printf(("5http_sspi_client: Unable to allocate %d byte buffer.", sspi->decryptBufferLength + 4096));
1434 WSASetLastError(E_OUTOFMEMORY);
1435 return (-1);
1436 }
1437
1438 sspi->decryptBufferLength += 4096;
1439 sspi->decryptBuffer = temp;
1440 }
1441
1442 cbData = recv(http->fd, sspi->decryptBuffer + sspi->decryptBufferUsed, (int)(sspi->decryptBufferLength - sspi->decryptBufferUsed), 0);
1443
1444 if (cbData < 0)
1445 {
1446 DEBUG_printf(("5http_sspi_client: recv failed: %d", WSAGetLastError()));
1447 return (-1);
1448 }
1449 else if (cbData == 0)
1450 {
1451 DEBUG_printf(("5http_sspi_client: Server unexpectedly disconnected."));
1452 return (-1);
1453 }
1454
1455 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data received", cbData));
1456
1457 sspi->decryptBufferUsed += cbData;
1458 }
1459
1460 /*
1461 * Set up the input buffers. Buffer 0 is used to pass in data received from
1462 * the server. Schannel will consume some or all of this. Leftover data
1463 * (if any) will be placed in buffer 1 and given a buffer type of
1464 * SECBUFFER_EXTRA.
1465 */
1466
1467 inBuffers[0].pvBuffer = sspi->decryptBuffer;
1468 inBuffers[0].cbBuffer = (unsigned long)sspi->decryptBufferUsed;
1469 inBuffers[0].BufferType = SECBUFFER_TOKEN;
1470
1471 inBuffers[1].pvBuffer = NULL;
1472 inBuffers[1].cbBuffer = 0;
1473 inBuffers[1].BufferType = SECBUFFER_EMPTY;
1474
1475 inBuffer.cBuffers = 2;
1476 inBuffer.pBuffers = inBuffers;
1477 inBuffer.ulVersion = SECBUFFER_VERSION;
1478
1479 /*
1480 * Set up the output buffers. These are initialized to NULL so as to make it
1481 * less likely we'll attempt to free random garbage later.
1482 */
1483
1484 outBuffers[0].pvBuffer = NULL;
1485 outBuffers[0].BufferType = SECBUFFER_TOKEN;
1486 outBuffers[0].cbBuffer = 0;
1487
1488 outBuffer.cBuffers = 1;
1489 outBuffer.pBuffers = outBuffers;
1490 outBuffer.ulVersion = SECBUFFER_VERSION;
1491
1492 /*
1493 * Call InitializeSecurityContext.
1494 */
1495
1496 scRet = InitializeSecurityContext(&sspi->creds, &sspi->context, NULL, dwSSPIFlags, 0, SECURITY_NATIVE_DREP, &inBuffer, 0, NULL, &outBuffer, &dwSSPIOutFlags, &tsExpiry);
1497
1498 /*
1499 * If InitializeSecurityContext was successful (or if the error was one of
1500 * the special extended ones), send the contents of the output buffer to the
1501 * server.
1502 */
1503
1504 if (scRet == SEC_E_OK ||
1505 scRet == SEC_I_CONTINUE_NEEDED ||
1506 FAILED(scRet) && (dwSSPIOutFlags & ISC_RET_EXTENDED_ERROR))
1507 {
1508 if (outBuffers[0].cbBuffer && outBuffers[0].pvBuffer)
1509 {
1510 cbData = send(http->fd, outBuffers[0].pvBuffer, outBuffers[0].cbBuffer, 0);
1511
1512 if (cbData <= 0)
1513 {
1514 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1515 FreeContextBuffer(outBuffers[0].pvBuffer);
1516 DeleteSecurityContext(&sspi->context);
1517 return (-1);
1518 }
1519
1520 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData));
1521
1522 /*
1523 * Free output buffer.
1524 */
1525
1526 FreeContextBuffer(outBuffers[0].pvBuffer);
1527 outBuffers[0].pvBuffer = NULL;
1528 }
1529 }
1530
1531 /*
1532 * If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, then we
1533 * need to read more data from the server and try again.
1534 */
1535
1536 if (scRet == SEC_E_INCOMPLETE_MESSAGE)
1537 continue;
1538
1539 /*
1540 * If InitializeSecurityContext returned SEC_E_OK, then the handshake
1541 * completed successfully.
1542 */
1543
1544 if (scRet == SEC_E_OK)
1545 {
1546 /*
1547 * If the "extra" buffer contains data, this is encrypted application
1548 * protocol layer stuff. It needs to be saved. The application layer will
1549 * later decrypt it with DecryptMessage.
1550 */
1551
1552 DEBUG_puts("5http_sspi_client: Handshake was successful.");
1553
1554 if (inBuffers[1].BufferType == SECBUFFER_EXTRA)
1555 {
1556 memmove(sspi->decryptBuffer, sspi->decryptBuffer + sspi->decryptBufferUsed - inBuffers[1].cbBuffer, inBuffers[1].cbBuffer);
1557
1558 sspi->decryptBufferUsed = inBuffers[1].cbBuffer;
1559
1560 DEBUG_printf(("5http_sspi_client: %d bytes of app data was bundled with handshake data", sspi->decryptBufferUsed));
1561 }
1562 else
1563 sspi->decryptBufferUsed = 0;
1564
1565 /*
1566 * Bail out to quit
1567 */
1568
1569 break;
1570 }
1571
1572 /*
1573 * Check for fatal error.
1574 */
1575
1576 if (FAILED(scRet))
1577 {
1578 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(2) failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
1579 ret = -1;
1580 break;
1581 }
1582
1583 /*
1584 * If InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS,
1585 * then the server just requested client authentication.
1586 */
1587
1588 if (scRet == SEC_I_INCOMPLETE_CREDENTIALS)
1589 {
1590 /*
1591 * Unimplemented
1592 */
1593
1594 DEBUG_printf(("5http_sspi_client: server requested client credentials."));
1595 ret = -1;
1596 break;
1597 }
1598
1599 /*
1600 * Copy any leftover data from the "extra" buffer, and go around again.
1601 */
1602
1603 if (inBuffers[1].BufferType == SECBUFFER_EXTRA)
1604 {
1605 memmove(sspi->decryptBuffer, sspi->decryptBuffer + sspi->decryptBufferUsed - inBuffers[1].cbBuffer, inBuffers[1].cbBuffer);
1606
1607 sspi->decryptBufferUsed = inBuffers[1].cbBuffer;
1608 }
1609 else
1610 {
1611 sspi->decryptBufferUsed = 0;
1612 }
1613 }
1614
1615 if (!ret)
1616 {
1617 /*
1618 * Success! Get the server cert
1619 */
1620
1621 sspi->contextInitialized = TRUE;
1622
1623 scRet = QueryContextAttributes(&sspi->context, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (VOID *)&(sspi->remoteCert));
1624
1625 if (scRet != SEC_E_OK)
1626 {
1627 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_REMOTE_CERT_CONTEXT): %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
1628 return (-1);
1629 }
1630
1631 /*
1632 * Find out how big the header/trailer will be:
1633 */
1634
1635 scRet = QueryContextAttributes(&sspi->context, SECPKG_ATTR_STREAM_SIZES, &sspi->streamSizes);
1636
1637 if (scRet != SEC_E_OK)
1638 {
1639 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_STREAM_SIZES): %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
1640 ret = -1;
1641 }
1642 }
1643
1644 return (ret);
1645 }
1646
1647
1648 /*
1649 * 'http_sspi_create_credential()' - Create an SSPI certificate context.
1650 */
1651
1652 static PCCERT_CONTEXT /* O - Certificate context */
1653 http_sspi_create_credential(
1654 http_credential_t *cred) /* I - Credential */
1655 {
1656 if (cred)
1657 return (CertCreateCertificateContext(X509_ASN_ENCODING, cred->data, cred->datalen));
1658 else
1659 return (NULL);
1660 }
1661
1662
1663 /*
1664 * 'http_sspi_find_credentials()' - Retrieve a TLS certificate from the system store.
1665 */
1666
1667 static BOOL /* O - 1 on success, 0 on failure */
1668 http_sspi_find_credentials(
1669 http_t *http, /* I - HTTP connection */
1670 const LPWSTR container, /* I - Cert container name */
1671 const char *common_name) /* I - Common name of certificate */
1672 {
1673 _http_sspi_t *sspi = http->tls; /* SSPI data */
1674 HCERTSTORE store = NULL; /* Certificate store */
1675 PCCERT_CONTEXT storedContext = NULL; /* Context created from the store */
1676 DWORD dwSize = 0; /* 32 bit size */
1677 PBYTE p = NULL; /* Temporary storage */
1678 HCRYPTPROV hProv = (HCRYPTPROV)NULL;
1679 /* Handle to a CSP */
1680 CERT_NAME_BLOB sib; /* Arbitrary array of bytes */
1681 SCHANNEL_CRED SchannelCred; /* Schannel credential data */
1682 TimeStamp tsExpiry; /* Time stamp */
1683 SECURITY_STATUS Status; /* Status */
1684 BOOL ok = TRUE; /* Return value */
1685
1686
1687 if (!CryptAcquireContextW(&hProv, (LPWSTR)container, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET))
1688 {
1689 if (GetLastError() == NTE_EXISTS)
1690 {
1691 if (!CryptAcquireContextW(&hProv, (LPWSTR)container, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
1692 {
1693 DEBUG_printf(("5http_sspi_find_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1694 ok = FALSE;
1695 goto cleanup;
1696 }
1697 }
1698 }
1699
1700 store = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, hProv, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_OPEN_EXISTING_FLAG, L"MY");
1701
1702 if (!store)
1703 {
1704 DEBUG_printf(("5http_sspi_find_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1705 ok = FALSE;
1706 goto cleanup;
1707 }
1708
1709 dwSize = 0;
1710
1711 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, NULL, &dwSize, NULL))
1712 {
1713 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1714 ok = FALSE;
1715 goto cleanup;
1716 }
1717
1718 p = (PBYTE)malloc(dwSize);
1719
1720 if (!p)
1721 {
1722 DEBUG_printf(("5http_sspi_find_credentials: malloc failed for %d bytes.", dwSize));
1723 ok = FALSE;
1724 goto cleanup;
1725 }
1726
1727 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, p, &dwSize, NULL))
1728 {
1729 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1730 ok = FALSE;
1731 goto cleanup;
1732 }
1733
1734 sib.cbData = dwSize;
1735 sib.pbData = p;
1736
1737 storedContext = CertFindCertificateInStore(store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_NAME, &sib, NULL);
1738
1739 if (!storedContext)
1740 {
1741 DEBUG_printf(("5http_sspi_find_credentials: Unable to find credentials for \"%s\".", common_name));
1742 ok = FALSE;
1743 goto cleanup;
1744 }
1745
1746 ZeroMemory(&SchannelCred, sizeof(SchannelCred));
1747
1748 SchannelCred.dwVersion = SCHANNEL_CRED_VERSION;
1749 SchannelCred.cCreds = 1;
1750 SchannelCred.paCred = &storedContext;
1751
1752 /*
1753 * Set supported protocols (can also be overriden in the registry...)
1754 */
1755
1756 #ifdef SP_PROT_TLS1_2_SERVER
1757 if (http->mode == _HTTP_MODE_SERVER)
1758 {
1759 if (tls_options & _HTTP_TLS_DENY_TLS10)
1760 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_1_SERVER;
1761 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1762 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_0_SERVER | SP_PROT_SSL3_SERVER;
1763 else
1764 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_0_SERVER;
1765 }
1766 else
1767 {
1768 if (tls_options & _HTTP_TLS_DENY_TLS10)
1769 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_1_CLIENT;
1770 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1771 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_0_CLIENT | SP_PROT_SSL3_CLIENT;
1772 else
1773 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_0_CLIENT;
1774 }
1775
1776 #else
1777 if (http->mode == _HTTP_MODE_SERVER)
1778 {
1779 if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1780 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_SERVER | SP_PROT_SSL3_SERVER;
1781 else
1782 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_SERVER;
1783 }
1784 else
1785 {
1786 if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1787 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_CLIENT | SP_PROT_SSL3_CLIENT;
1788 else
1789 SchannelCred.grbitEnabledProtocols = SP_PROT_TLS1_CLIENT;
1790 }
1791 #endif /* SP_PROT_TLS1_2_SERVER */
1792
1793 /* TODO: Support _HTTP_TLS_ALLOW_RC4 and _HTTP_TLS_ALLOW_DH options; right now we'll rely on Windows registry to enable/disable RC4/DH... */
1794
1795 /*
1796 * Create an SSPI credential.
1797 */
1798
1799 Status = AcquireCredentialsHandle(NULL, UNISP_NAME, http->mode == _HTTP_MODE_SERVER ? SECPKG_CRED_INBOUND : SECPKG_CRED_OUTBOUND, NULL, &SchannelCred, NULL, NULL, &sspi->creds, &tsExpiry);
1800 if (Status != SEC_E_OK)
1801 {
1802 DEBUG_printf(("5http_sspi_find_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), Status)));
1803 ok = FALSE;
1804 goto cleanup;
1805 }
1806
1807 cleanup:
1808
1809 /*
1810 * Cleanup
1811 */
1812
1813 if (storedContext)
1814 CertFreeCertificateContext(storedContext);
1815
1816 if (p)
1817 free(p);
1818
1819 if (store)
1820 CertCloseStore(store, 0);
1821
1822 if (hProv)
1823 CryptReleaseContext(hProv, 0);
1824
1825 return (ok);
1826 }
1827
1828
1829 /*
1830 * 'http_sspi_free()' - Close a connection and free resources.
1831 */
1832
1833 static void
1834 http_sspi_free(_http_sspi_t *sspi) /* I - SSPI data */
1835 {
1836 if (!sspi)
1837 return;
1838
1839 if (sspi->contextInitialized)
1840 DeleteSecurityContext(&sspi->context);
1841
1842 if (sspi->decryptBuffer)
1843 free(sspi->decryptBuffer);
1844
1845 if (sspi->readBuffer)
1846 free(sspi->readBuffer);
1847
1848 if (sspi->writeBuffer)
1849 free(sspi->writeBuffer);
1850
1851 if (sspi->localCert)
1852 CertFreeCertificateContext(sspi->localCert);
1853
1854 if (sspi->remoteCert)
1855 CertFreeCertificateContext(sspi->remoteCert);
1856
1857 free(sspi);
1858 }
1859
1860
1861 /*
1862 * 'http_sspi_make_credentials()' - Create a TLS certificate in the system store.
1863 */
1864
1865 static BOOL /* O - 1 on success, 0 on failure */
1866 http_sspi_make_credentials(
1867 _http_sspi_t *sspi, /* I - SSPI data */
1868 const LPWSTR container, /* I - Cert container name */
1869 const char *common_name, /* I - Common name of certificate */
1870 _http_mode_t mode, /* I - Client or server? */
1871 int years) /* I - Years until expiration */
1872 {
1873 HCERTSTORE store = NULL; /* Certificate store */
1874 PCCERT_CONTEXT storedContext = NULL; /* Context created from the store */
1875 PCCERT_CONTEXT createdContext = NULL; /* Context created by us */
1876 DWORD dwSize = 0; /* 32 bit size */
1877 PBYTE p = NULL; /* Temporary storage */
1878 HCRYPTPROV hProv = (HCRYPTPROV)NULL;
1879 /* Handle to a CSP */
1880 CERT_NAME_BLOB sib; /* Arbitrary array of bytes */
1881 SCHANNEL_CRED SchannelCred; /* Schannel credential data */
1882 TimeStamp tsExpiry; /* Time stamp */
1883 SECURITY_STATUS Status; /* Status */
1884 HCRYPTKEY hKey = (HCRYPTKEY)NULL; /* Handle to crypto key */
1885 CRYPT_KEY_PROV_INFO kpi; /* Key container info */
1886 SYSTEMTIME et; /* System time */
1887 CERT_EXTENSIONS exts; /* Array of cert extensions */
1888 CRYPT_KEY_PROV_INFO ckp; /* Handle to crypto key */
1889 BOOL ok = TRUE; /* Return value */
1890
1891
1892 DEBUG_printf(("4http_sspi_make_credentials(sspi=%p, container=%p, common_name=\"%s\", mode=%d, years=%d)", sspi, container, common_name, mode, years));
1893
1894 if (!CryptAcquireContextW(&hProv, (LPWSTR)container, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET))
1895 {
1896 if (GetLastError() == NTE_EXISTS)
1897 {
1898 if (!CryptAcquireContextW(&hProv, (LPWSTR)container, MS_DEF_PROV_W, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
1899 {
1900 DEBUG_printf(("5http_sspi_make_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1901 ok = FALSE;
1902 goto cleanup;
1903 }
1904 }
1905 }
1906
1907 store = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING|PKCS_7_ASN_ENCODING, hProv, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_OPEN_EXISTING_FLAG, L"MY");
1908
1909 if (!store)
1910 {
1911 DEBUG_printf(("5http_sspi_make_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1912 ok = FALSE;
1913 goto cleanup;
1914 }
1915
1916 dwSize = 0;
1917
1918 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, NULL, &dwSize, NULL))
1919 {
1920 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1921 ok = FALSE;
1922 goto cleanup;
1923 }
1924
1925 p = (PBYTE)malloc(dwSize);
1926
1927 if (!p)
1928 {
1929 DEBUG_printf(("5http_sspi_make_credentials: malloc failed for %d bytes", dwSize));
1930 ok = FALSE;
1931 goto cleanup;
1932 }
1933
1934 if (!CertStrToName(X509_ASN_ENCODING, common_name, CERT_OID_NAME_STR, NULL, p, &dwSize, NULL))
1935 {
1936 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1937 ok = FALSE;
1938 goto cleanup;
1939 }
1940
1941 /*
1942 * Create a private key and self-signed certificate...
1943 */
1944
1945 if (!CryptGenKey(hProv, AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &hKey))
1946 {
1947 DEBUG_printf(("5http_sspi_make_credentials: CryptGenKey failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1948 ok = FALSE;
1949 goto cleanup;
1950 }
1951
1952 ZeroMemory(&kpi, sizeof(kpi));
1953 kpi.pwszContainerName = (LPWSTR)container;
1954 kpi.pwszProvName = MS_DEF_PROV_W;
1955 kpi.dwProvType = PROV_RSA_FULL;
1956 kpi.dwFlags = CERT_SET_KEY_CONTEXT_PROP_ID;
1957 kpi.dwKeySpec = AT_KEYEXCHANGE;
1958
1959 GetSystemTime(&et);
1960 et.wYear += years;
1961
1962 ZeroMemory(&exts, sizeof(exts));
1963
1964 createdContext = CertCreateSelfSignCertificate(hProv, &sib, 0, &kpi, NULL, NULL, &et, &exts);
1965
1966 if (!createdContext)
1967 {
1968 DEBUG_printf(("5http_sspi_make_credentials: CertCreateSelfSignCertificate failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1969 ok = FALSE;
1970 goto cleanup;
1971 }
1972
1973 /*
1974 * Add the created context to the named store, and associate it with the named
1975 * container...
1976 */
1977
1978 if (!CertAddCertificateContextToStore(store, createdContext, CERT_STORE_ADD_REPLACE_EXISTING, &storedContext))
1979 {
1980 DEBUG_printf(("5http_sspi_make_credentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1981 ok = FALSE;
1982 goto cleanup;
1983 }
1984
1985 ZeroMemory(&ckp, sizeof(ckp));
1986 ckp.pwszContainerName = (LPWSTR) container;
1987 ckp.pwszProvName = MS_DEF_PROV_W;
1988 ckp.dwProvType = PROV_RSA_FULL;
1989 ckp.dwFlags = CRYPT_MACHINE_KEYSET;
1990 ckp.dwKeySpec = AT_KEYEXCHANGE;
1991
1992 if (!CertSetCertificateContextProperty(storedContext, CERT_KEY_PROV_INFO_PROP_ID, 0, &ckp))
1993 {
1994 DEBUG_printf(("5http_sspi_make_credentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), GetLastError())));
1995 ok = FALSE;
1996 goto cleanup;
1997 }
1998
1999 /*
2000 * Get a handle to use the certificate...
2001 */
2002
2003 ZeroMemory(&SchannelCred, sizeof(SchannelCred));
2004
2005 SchannelCred.dwVersion = SCHANNEL_CRED_VERSION;
2006 SchannelCred.cCreds = 1;
2007 SchannelCred.paCred = &storedContext;
2008
2009 /*
2010 * SSPI doesn't seem to like it if grbitEnabledProtocols is set for a client.
2011 */
2012
2013 if (mode == _HTTP_MODE_SERVER)
2014 SchannelCred.grbitEnabledProtocols = SP_PROT_SSL3TLS1;
2015
2016 /*
2017 * Create an SSPI credential.
2018 */
2019
2020 Status = AcquireCredentialsHandle(NULL, UNISP_NAME, mode == _HTTP_MODE_SERVER ? SECPKG_CRED_INBOUND : SECPKG_CRED_OUTBOUND, NULL, &SchannelCred, NULL, NULL, &sspi->creds, &tsExpiry);
2021 if (Status != SEC_E_OK)
2022 {
2023 DEBUG_printf(("5http_sspi_make_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), Status)));
2024 ok = FALSE;
2025 goto cleanup;
2026 }
2027
2028 cleanup:
2029
2030 /*
2031 * Cleanup
2032 */
2033
2034 if (hKey)
2035 CryptDestroyKey(hKey);
2036
2037 if (createdContext)
2038 CertFreeCertificateContext(createdContext);
2039
2040 if (storedContext)
2041 CertFreeCertificateContext(storedContext);
2042
2043 if (p)
2044 free(p);
2045
2046 if (store)
2047 CertCloseStore(store, 0);
2048
2049 if (hProv)
2050 CryptReleaseContext(hProv, 0);
2051
2052 return (ok);
2053 }
2054
2055
2056 /*
2057 * 'http_sspi_server()' - Negotiate a TLS connection as a server.
2058 */
2059
2060 static int /* O - 0 on success, -1 on failure */
2061 http_sspi_server(http_t *http, /* I - HTTP connection */
2062 const char *hostname) /* I - Hostname of server */
2063 {
2064 _http_sspi_t *sspi = http->tls; /* I - SSPI data */
2065 char common_name[512]; /* Common name for cert */
2066 DWORD dwSSPIFlags; /* SSL connection attributes we want */
2067 DWORD dwSSPIOutFlags; /* SSL connection attributes we got */
2068 TimeStamp tsExpiry; /* Time stamp */
2069 SECURITY_STATUS scRet; /* SSPI Status */
2070 SecBufferDesc inBuffer; /* Array of SecBuffer structs */
2071 SecBuffer inBuffers[2]; /* Security package buffer */
2072 SecBufferDesc outBuffer; /* Array of SecBuffer structs */
2073 SecBuffer outBuffers[1]; /* Security package buffer */
2074 int num = 0; /* 32 bit status value */
2075 BOOL fInitContext = TRUE; /* Has the context been init'd? */
2076 int ret = 0; /* Return value */
2077
2078
2079 DEBUG_printf(("4http_sspi_server(http=%p, hostname=\"%s\")", http, hostname));
2080
2081 dwSSPIFlags = ASC_REQ_SEQUENCE_DETECT |
2082 ASC_REQ_REPLAY_DETECT |
2083 ASC_REQ_CONFIDENTIALITY |
2084 ASC_REQ_EXTENDED_ERROR |
2085 ASC_REQ_ALLOCATE_MEMORY |
2086 ASC_REQ_STREAM;
2087
2088 sspi->decryptBufferUsed = 0;
2089
2090 /*
2091 * Lookup the server certificate...
2092 */
2093
2094 snprintf(common_name, sizeof(common_name), "CN=%s", hostname);
2095
2096 if (!http_sspi_find_credentials(http, L"ServerContainer", common_name))
2097 if (!http_sspi_make_credentials(http->tls, L"ServerContainer", common_name, _HTTP_MODE_SERVER, 10))
2098 {
2099 DEBUG_puts("5http_sspi_server: Unable to get server credentials.");
2100 return (-1);
2101 }
2102
2103 /*
2104 * Set OutBuffer for AcceptSecurityContext call
2105 */
2106
2107 outBuffer.cBuffers = 1;
2108 outBuffer.pBuffers = outBuffers;
2109 outBuffer.ulVersion = SECBUFFER_VERSION;
2110
2111 scRet = SEC_I_CONTINUE_NEEDED;
2112
2113 while (scRet == SEC_I_CONTINUE_NEEDED ||
2114 scRet == SEC_E_INCOMPLETE_MESSAGE ||
2115 scRet == SEC_I_INCOMPLETE_CREDENTIALS)
2116 {
2117 if (sspi->decryptBufferUsed == 0 || scRet == SEC_E_INCOMPLETE_MESSAGE)
2118 {
2119 if (sspi->decryptBufferLength <= sspi->decryptBufferUsed)
2120 {
2121 BYTE *temp; /* New buffer */
2122
2123 if (sspi->decryptBufferLength >= 262144)
2124 {
2125 WSASetLastError(E_OUTOFMEMORY);
2126 DEBUG_puts("5http_sspi_server: Decryption buffer too large (>256k)");
2127 return (-1);
2128 }
2129
2130 if ((temp = realloc(sspi->decryptBuffer, sspi->decryptBufferLength + 4096)) == NULL)
2131 {
2132 DEBUG_printf(("5http_sspi_server: Unable to allocate %d byte buffer.", sspi->decryptBufferLength + 4096));
2133 WSASetLastError(E_OUTOFMEMORY);
2134 return (-1);
2135 }
2136
2137 sspi->decryptBufferLength += 4096;
2138 sspi->decryptBuffer = temp;
2139 }
2140
2141 for (;;)
2142 {
2143 num = recv(http->fd, sspi->decryptBuffer + sspi->decryptBufferUsed, (int)(sspi->decryptBufferLength - sspi->decryptBufferUsed), 0);
2144
2145 if (num == -1 && WSAGetLastError() == WSAEWOULDBLOCK)
2146 Sleep(1);
2147 else
2148 break;
2149 }
2150
2151 if (num < 0)
2152 {
2153 DEBUG_printf(("5http_sspi_server: recv failed: %d", WSAGetLastError()));
2154 return (-1);
2155 }
2156 else if (num == 0)
2157 {
2158 DEBUG_puts("5http_sspi_server: client disconnected");
2159 return (-1);
2160 }
2161
2162 DEBUG_printf(("5http_sspi_server: received %d (handshake) bytes from client.", num));
2163 sspi->decryptBufferUsed += num;
2164 }
2165
2166 /*
2167 * InBuffers[1] is for getting extra data that SSPI/SCHANNEL doesn't process
2168 * on this run around the loop.
2169 */
2170
2171 inBuffers[0].pvBuffer = sspi->decryptBuffer;
2172 inBuffers[0].cbBuffer = (unsigned long)sspi->decryptBufferUsed;
2173 inBuffers[0].BufferType = SECBUFFER_TOKEN;
2174
2175 inBuffers[1].pvBuffer = NULL;
2176 inBuffers[1].cbBuffer = 0;
2177 inBuffers[1].BufferType = SECBUFFER_EMPTY;
2178
2179 inBuffer.cBuffers = 2;
2180 inBuffer.pBuffers = inBuffers;
2181 inBuffer.ulVersion = SECBUFFER_VERSION;
2182
2183 /*
2184 * Initialize these so if we fail, pvBuffer contains NULL, so we don't try to
2185 * free random garbage at the quit.
2186 */
2187
2188 outBuffers[0].pvBuffer = NULL;
2189 outBuffers[0].BufferType = SECBUFFER_TOKEN;
2190 outBuffers[0].cbBuffer = 0;
2191
2192 scRet = AcceptSecurityContext(&sspi->creds, (fInitContext?NULL:&sspi->context), &inBuffer, dwSSPIFlags, SECURITY_NATIVE_DREP, (fInitContext?&sspi->context:NULL), &outBuffer, &dwSSPIOutFlags, &tsExpiry);
2193
2194 fInitContext = FALSE;
2195
2196 if (scRet == SEC_E_OK ||
2197 scRet == SEC_I_CONTINUE_NEEDED ||
2198 (FAILED(scRet) && ((dwSSPIOutFlags & ISC_RET_EXTENDED_ERROR) != 0)))
2199 {
2200 if (outBuffers[0].cbBuffer && outBuffers[0].pvBuffer)
2201 {
2202 /*
2203 * Send response to server if there is one.
2204 */
2205
2206 num = send(http->fd, outBuffers[0].pvBuffer, outBuffers[0].cbBuffer, 0);
2207
2208 if (num <= 0)
2209 {
2210 DEBUG_printf(("5http_sspi_server: handshake send failed: %d", WSAGetLastError()));
2211 return (-1);
2212 }
2213
2214 DEBUG_printf(("5http_sspi_server: sent %d handshake bytes to client.", outBuffers[0].cbBuffer));
2215
2216 FreeContextBuffer(outBuffers[0].pvBuffer);
2217 outBuffers[0].pvBuffer = NULL;
2218 }
2219 }
2220
2221 if (scRet == SEC_E_OK)
2222 {
2223 /*
2224 * If there's extra data then save it for next time we go to decrypt.
2225 */
2226
2227 if (inBuffers[1].BufferType == SECBUFFER_EXTRA)
2228 {
2229 memcpy(sspi->decryptBuffer, (LPBYTE)(sspi->decryptBuffer + sspi->decryptBufferUsed - inBuffers[1].cbBuffer), inBuffers[1].cbBuffer);
2230 sspi->decryptBufferUsed = inBuffers[1].cbBuffer;
2231 }
2232 else
2233 {
2234 sspi->decryptBufferUsed = 0;
2235 }
2236 break;
2237 }
2238 else if (FAILED(scRet) && scRet != SEC_E_INCOMPLETE_MESSAGE)
2239 {
2240 DEBUG_printf(("5http_sspi_server: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
2241 ret = -1;
2242 break;
2243 }
2244
2245 if (scRet != SEC_E_INCOMPLETE_MESSAGE &&
2246 scRet != SEC_I_INCOMPLETE_CREDENTIALS)
2247 {
2248 if (inBuffers[1].BufferType == SECBUFFER_EXTRA)
2249 {
2250 memcpy(sspi->decryptBuffer, (LPBYTE)(sspi->decryptBuffer + sspi->decryptBufferUsed - inBuffers[1].cbBuffer), inBuffers[1].cbBuffer);
2251 sspi->decryptBufferUsed = inBuffers[1].cbBuffer;
2252 }
2253 else
2254 {
2255 sspi->decryptBufferUsed = 0;
2256 }
2257 }
2258 }
2259
2260 if (!ret)
2261 {
2262 sspi->contextInitialized = TRUE;
2263
2264 /*
2265 * Find out how big the header will be:
2266 */
2267
2268 scRet = QueryContextAttributes(&sspi->context, SECPKG_ATTR_STREAM_SIZES, &sspi->streamSizes);
2269
2270 if (scRet != SEC_E_OK)
2271 {
2272 DEBUG_printf(("5http_sspi_server: QueryContextAttributes failed: %s", http_sspi_strerror(sspi->error, sizeof(sspi->error), scRet)));
2273 ret = -1;
2274 }
2275 }
2276
2277 return (ret);
2278 }
2279
2280
2281 /*
2282 * 'http_sspi_strerror()' - Return a string for the specified error code.
2283 */
2284
2285 static const char * /* O - String for error */
2286 http_sspi_strerror(char *buffer, /* I - Error message buffer */
2287 size_t bufsize, /* I - Size of buffer */
2288 DWORD code) /* I - Error code */
2289 {
2290 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, 0, buffer, bufsize, NULL))
2291 {
2292 /*
2293 * Strip trailing CR + LF...
2294 */
2295
2296 char *ptr; /* Pointer into error message */
2297
2298 for (ptr = buffer + strlen(buffer) - 1; ptr >= buffer; ptr --)
2299 if (*ptr == '\n' || *ptr == '\r')
2300 *ptr = '\0';
2301 else
2302 break;
2303 }
2304 else
2305 snprintf(buffer, bufsize, "Unknown error %x", code);
2306
2307 return (buffer);
2308 }
2309
2310
2311 /*
2312 * 'http_sspi_verify()' - Verify a certificate.
2313 */
2314
2315 static DWORD /* O - Error code (0 == No error) */
2316 http_sspi_verify(
2317 PCCERT_CONTEXT cert, /* I - Server certificate */
2318 const char *common_name, /* I - Common name */
2319 DWORD dwCertFlags) /* I - Verification flags */
2320 {
2321 HTTPSPolicyCallbackData httpsPolicy; /* HTTPS Policy Struct */
2322 CERT_CHAIN_POLICY_PARA policyPara; /* Cert chain policy parameters */
2323 CERT_CHAIN_POLICY_STATUS policyStatus;/* Cert chain policy status */
2324 CERT_CHAIN_PARA chainPara; /* Used for searching and matching criteria */
2325 PCCERT_CHAIN_CONTEXT chainContext = NULL;
2326 /* Certificate chain */
2327 PWSTR commonNameUnicode = NULL;
2328 /* Unicode common name */
2329 LPSTR rgszUsages[] = { szOID_PKIX_KP_SERVER_AUTH,
2330 szOID_SERVER_GATED_CRYPTO,
2331 szOID_SGC_NETSCAPE };
2332 /* How are we using this certificate? */
2333 DWORD cUsages = sizeof(rgszUsages) / sizeof(LPSTR);
2334 /* Number of ites in rgszUsages */
2335 DWORD count; /* 32 bit count variable */
2336 DWORD status; /* Return value */
2337 #ifdef DEBUG
2338 char error[1024]; /* Error message string */
2339 #endif /* DEBUG */
2340
2341
2342 if (!cert)
2343 return (SEC_E_WRONG_PRINCIPAL);
2344
2345 /*
2346 * Convert common name to Unicode.
2347 */
2348
2349 if (!common_name || !*common_name)
2350 return (SEC_E_WRONG_PRINCIPAL);
2351
2352 count = MultiByteToWideChar(CP_ACP, 0, common_name, -1, NULL, 0);
2353 commonNameUnicode = LocalAlloc(LMEM_FIXED, count * sizeof(WCHAR));
2354 if (!commonNameUnicode)
2355 return (SEC_E_INSUFFICIENT_MEMORY);
2356
2357 if (!MultiByteToWideChar(CP_ACP, 0, common_name, -1, commonNameUnicode, count))
2358 {
2359 LocalFree(commonNameUnicode);
2360 return (SEC_E_WRONG_PRINCIPAL);
2361 }
2362
2363 /*
2364 * Build certificate chain.
2365 */
2366
2367 ZeroMemory(&chainPara, sizeof(chainPara));
2368
2369 chainPara.cbSize = sizeof(chainPara);
2370 chainPara.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
2371 chainPara.RequestedUsage.Usage.cUsageIdentifier = cUsages;
2372 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = rgszUsages;
2373
2374 if (!CertGetCertificateChain(NULL, cert, NULL, cert->hCertStore, &chainPara, 0, NULL, &chainContext))
2375 {
2376 status = GetLastError();
2377
2378 DEBUG_printf(("CertGetCertificateChain returned: %s", http_sspi_strerror(error, sizeof(error), status)));
2379
2380 LocalFree(commonNameUnicode);
2381 return (status);
2382 }
2383
2384 /*
2385 * Validate certificate chain.
2386 */
2387
2388 ZeroMemory(&httpsPolicy, sizeof(HTTPSPolicyCallbackData));
2389 httpsPolicy.cbStruct = sizeof(HTTPSPolicyCallbackData);
2390 httpsPolicy.dwAuthType = AUTHTYPE_SERVER;
2391 httpsPolicy.fdwChecks = dwCertFlags;
2392 httpsPolicy.pwszServerName = commonNameUnicode;
2393
2394 memset(&policyPara, 0, sizeof(policyPara));
2395 policyPara.cbSize = sizeof(policyPara);
2396 policyPara.pvExtraPolicyPara = &httpsPolicy;
2397
2398 memset(&policyStatus, 0, sizeof(policyStatus));
2399 policyStatus.cbSize = sizeof(policyStatus);
2400
2401 if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chainContext, &policyPara, &policyStatus))
2402 {
2403 status = GetLastError();
2404
2405 DEBUG_printf(("CertVerifyCertificateChainPolicy returned %s", http_sspi_strerror(error, sizeof(error), status)));
2406 }
2407 else if (policyStatus.dwError)
2408 status = policyStatus.dwError;
2409 else
2410 status = SEC_E_OK;
2411
2412 if (chainContext)
2413 CertFreeCertificateChain(chainContext);
2414
2415 if (commonNameUnicode)
2416 LocalFree(commonNameUnicode);
2417
2418 return (status);
2419 }
2420
2421
2422 /*
2423 * End of "$Id$".
2424 */