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