2 * TLS support for CUPS on Windows using the Security Support Provider
5 * Copyright 2010-2017 by Apple Inc.
7 * These coded instructions, statements, and computer programs are the
8 * property of Apple Inc. and are protected by Federal copyright
9 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
10 * which should have been included with this file. If this file is
11 * missing or damaged, see the license at "http://www.cups.org/".
13 * This file is subject to the Apple OS-Developed Software exception.
16 /**** This file is included from tls.c ****/
19 * Include necessary headers...
22 #include "debug-private.h"
26 * Include necessary libraries...
29 #pragma comment(lib, "Crypt32.lib")
30 #pragma comment(lib, "Secur32.lib")
31 #pragma comment(lib, "Ws2_32.lib")
38 #ifndef SECURITY_FLAG_IGNORE_UNKNOWN_CA
39 # define SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00000100 /* Untrusted root */
40 #endif /* SECURITY_FLAG_IGNORE_UNKNOWN_CA */
42 #ifndef SECURITY_FLAG_IGNORE_CERT_CN_INVALID
43 # define SECURITY_FLAG_IGNORE_CERT_CN_INVALID 0x00001000 /* Common name does not match */
44 #endif /* !SECURITY_FLAG_IGNORE_CERT_CN_INVALID */
46 #ifndef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
47 # define SECURITY_FLAG_IGNORE_CERT_DATE_INVALID 0x00002000 /* Expired X509 Cert. */
48 #endif /* !SECURITY_FLAG_IGNORE_CERT_DATE_INVALID */
55 static int tls_options
= -1,/* Options for TLS connections */
56 tls_min_version
= _HTTP_TLS_1_0
,
57 tls_max_version
= _HTTP_TLS_MAX
;
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
);
78 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
80 * @since CUPS 2.0/OS 10.10@
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 */
91 _http_sspi_t
*sspi
; /* SSPI data */
92 int ret
; /* Return value */
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
));
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));
104 http_sspi_free(sspi
);
111 * 'cupsSetServerCredentials()' - Set the default server credentials.
113 * Note: The server credentials are used by all threads in the running process.
114 * This function is threadsafe.
116 * @since CUPS 2.0/OS 10.10@
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 */
125 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
136 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
137 * an encrypted connection.
139 * @since CUPS 1.5/macOS 10.7@
142 int /* O - Status of call (0 = success) */
144 http_t
*http
, /* I - Connection to server */
145 cups_array_t
**credentials
) /* O - Array of credentials */
147 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
149 if (!http
|| !http
->tls
|| !http
->tls
->remoteCert
|| !credentials
)
157 *credentials
= cupsArrayNew(NULL
, NULL
);
158 httpAddCredential(*credentials
, http
->tls
->remoteCert
->pbCertEncoded
, http
->tls
->remoteCert
->cbCertEncoded
);
165 * '_httpCreateCredentials()' - Create credentials in the internal format.
168 http_tls_credentials_t
/* O - Internal credentials */
169 _httpCreateCredentials(
170 cups_array_t
*credentials
) /* I - Array of credentials */
172 return (http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
)));
177 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
179 * @since CUPS 2.0/OS 10.10@
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 */
187 int valid
= 1; /* Valid name? */
188 PCCERT_CONTEXT cert
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
190 char cert_name
[1024]; /* Name from certificate */
195 if (CertNameToStr(X509_ASN_ENCODING
, &(cert
->pCertInfo
->Subject
), CERT_SIMPLE_NAME_STR
, cert_name
, sizeof(cert_name
)))
198 * Extract common name at end...
201 char *ptr
= strrchr(cert_name
, ',');
203 _cups_strcpy(cert_name
, ptr
+ 2);
206 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
208 CertFreeCertificateContext(cert
);
211 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
214 * Compare the common names...
217 if (_cups_strcasecmp(common_name
, cert_name
))
220 * Not an exact match for the common name, check for wildcard certs...
223 const char *domain
= strchr(common_name
, '.');
224 /* Domain in common name */
226 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
229 * Not a wildcard match.
232 /* TODO: Check subject alternate names */
242 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
244 * @since CUPS 2.0/OS 10.10@
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 */
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 */
259 return (HTTP_TRUST_UNKNOWN
);
261 cert
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
263 return (HTTP_TRUST_UNKNOWN
);
265 if (cg
->any_root
< 0)
269 certFlags
|= SECURITY_FLAG_IGNORE_UNKNOWN_CA
;
271 if (cg
->expired_certs
)
272 certFlags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
274 if (!cg
->validate_certs
)
275 certFlags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
277 if (http_sspi_verify(cert
, common_name
, certFlags
) != SEC_E_OK
)
278 trust
= HTTP_TRUST_INVALID
;
280 CertFreeCertificateContext(cert
);
287 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
289 * @since CUPS 2.0/OS 10.10@
292 time_t /* O - Expiration date of credentials */
293 httpCredentialsGetExpiration(
294 cups_array_t
*credentials
) /* I - Credentials */
296 time_t expiration_date
= 0; /* Expiration data of credentials */
297 PCCERT_CONTEXT cert
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
302 SYSTEMTIME systime
; /* System time */
303 struct tm tm
; /* UNIX date/time */
305 FileTimeToSystemTime(&(cert
->pCertInfo
->NotAfter
), &systime
);
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
;
314 expiration_date
= mktime(&tm
);
316 CertFreeCertificateContext(cert
);
319 return (expiration_date
);
324 * 'httpCredentialsString()' - Return a string representing the credentials.
326 * @since CUPS 2.0/OS 10.10@
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 */
335 http_credential_t
*first
= (http_credential_t
*)cupsArrayFirst(credentials
);
336 /* First certificate */
337 PCCERT_CONTEXT cert
; /* Certificate */
340 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
345 if (buffer
&& bufsize
> 0)
348 cert
= http_sspi_create_credential(first
);
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 unsigned char md5_digest
[16]; /* MD5 result */
358 FileTimeToSystemTime(&(cert
->pCertInfo
->NotAfter
), &systime
);
360 tm
.tm_year
= systime
.wYear
- 1900;
361 tm
.tm_mon
= systime
.wMonth
- 1;
362 tm
.tm_mday
= systime
.wDay
;
363 tm
.tm_hour
= systime
.wHour
;
364 tm
.tm_min
= systime
.wMinute
;
365 tm
.tm_sec
= systime
.wSecond
;
367 expiration
= mktime(&tm
);
369 if (CertNameToStr(X509_ASN_ENCODING
, &(cert
->pCertInfo
->Subject
), CERT_SIMPLE_NAME_STR
, cert_name
, sizeof(cert_name
)))
372 * Extract common name at end...
375 char *ptr
= strrchr(cert_name
, ',');
377 _cups_strcpy(cert_name
, ptr
+ 2);
380 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
382 cupsHashData("md5", first
->data
, first
->datalen
, md5_digest
, sizeof(md5_digest
));
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]);
386 CertFreeCertificateContext(cert
);
389 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
391 return (strlen(buffer
));
396 * '_httpFreeCredentials()' - Free internal credentials.
400 _httpFreeCredentials(
401 http_tls_credentials_t credentials
) /* I - Internal credentials */
406 CertFreeCertificateContext(credentials
);
411 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
413 * @since CUPS 2.0/OS 10.10@
416 int /* O - 0 on success, -1 on error */
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 */
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 */
430 char error
[1024]; /* Error message buffer */
434 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
444 DEBUG_puts("1httpLoadCredentials: NULL credentials pointer, returning -1.");
450 DEBUG_puts("1httpLoadCredentials: Bad common name, returning -1.");
454 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
456 if (GetLastError() == NTE_EXISTS
)
458 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
460 DEBUG_printf(("1httpLoadCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
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");
470 DEBUG_printf(("1httpLoadCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
476 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
478 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
482 p
= (PBYTE
)malloc(dwSize
);
486 DEBUG_printf(("1httpLoadCredentials: malloc failed for %d bytes.", dwSize
));
490 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
492 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
499 storedContext
= CertFindCertificateInStore(store
, X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, 0, CERT_FIND_SUBJECT_NAME
, &sib
, NULL
);
503 DEBUG_printf(("1httpLoadCredentials: Unable to find credentials for \"%s\".", common_name
));
507 *credentials
= cupsArrayNew(NULL
, NULL
);
508 httpAddCredential(*credentials
, storedContext
->pbCertEncoded
, storedContext
->cbCertEncoded
);
517 CertFreeCertificateContext(storedContext
);
523 CertCloseStore(store
, 0);
526 CryptReleaseContext(hProv
, 0);
528 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
530 return (*credentials
? 0 : -1);
535 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
537 * @since CUPS 2.0/OS 10.10@
540 int /* O - -1 on error, 0 on success */
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 */
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 */
553 CRYPT_KEY_PROV_INFO ckp
; /* Handle to crypto key */
554 int ret
= -1; /* Return value */
556 char error
[1024]; /* Error message buffer */
560 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
566 DEBUG_puts("1httpSaveCredentials: Bad common name, returning -1.");
570 createdContext
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
573 DEBUG_puts("1httpSaveCredentials: Bad credentials, returning -1.");
577 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
579 if (GetLastError() == NTE_EXISTS
)
581 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
583 DEBUG_printf(("1httpSaveCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
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");
593 DEBUG_printf(("1httpSaveCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
599 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
601 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
605 p
= (PBYTE
)malloc(dwSize
);
609 DEBUG_printf(("1httpSaveCredentials: malloc failed for %d bytes.", dwSize
));
613 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
615 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
620 * Add the created context to the named store, and associate it with the named
624 if (!CertAddCertificateContextToStore(store
, createdContext
, CERT_STORE_ADD_REPLACE_EXISTING
, &storedContext
))
626 DEBUG_printf(("1httpSaveCredentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
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
;
637 if (!CertSetCertificateContextProperty(storedContext
, CERT_KEY_PROV_INFO_PROP_ID
, 0, &ckp
))
639 DEBUG_printf(("1httpSaveCredentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
652 CertFreeCertificateContext(createdContext
);
655 CertFreeCertificateContext(storedContext
);
661 CertCloseStore(store
, 0);
664 CryptReleaseContext(hProv
, 0);
666 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
672 * '_httpTLSInitialize()' - Initialize the TLS stack.
676 _httpTLSInitialize(void)
685 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
688 size_t /* O - Bytes available */
689 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
692 return (http
->tls
->readBufferUsed
);
699 * '_httpTLSRead()' - Read from a SSL/TLS connection.
702 int /* 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 */
707 int i
; /* Looping var */
708 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
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 */
717 DEBUG_printf(("4_httpTLSRead(http=%p, buf=%p, len=%d)", http
, buf
, len
));
720 * If there are bytes that have already been decrypted and have not yet been
721 * read, return those...
724 if (sspi
->readBufferUsed
> 0)
726 int bytesToCopy
= min(sspi
->readBufferUsed
, len
);
727 /* Number of bytes to copy */
729 memcpy(buf
, sspi
->readBuffer
, bytesToCopy
);
730 sspi
->readBufferUsed
-= bytesToCopy
;
732 if (sspi
->readBufferUsed
> 0)
733 memmove(sspi
->readBuffer
, sspi
->readBuffer
+ bytesToCopy
, sspi
->readBufferUsed
);
735 DEBUG_printf(("5_httpTLSRead: Returning %d bytes previously decrypted.", bytesToCopy
));
737 return (bytesToCopy
);
741 * Initialize security buffer structs
744 message
.ulVersion
= SECBUFFER_VERSION
;
745 message
.cBuffers
= 4;
746 message
.pBuffers
= buffers
;
751 * If there is not enough space in the buffer, then increase its size...
754 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
756 BYTE
*temp
; /* New buffer */
758 if (sspi
->decryptBufferLength
>= 262144)
760 WSASetLastError(E_OUTOFMEMORY
);
761 DEBUG_puts("_httpTLSRead: Decryption buffer too large (>256k)");
765 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
767 DEBUG_printf(("_httpTLSRead: Unable to allocate %d byte decryption buffer.", sspi
->decryptBufferLength
+ 4096));
768 WSASetLastError(E_OUTOFMEMORY
);
772 sspi
->decryptBufferLength
+= 4096;
773 sspi
->decryptBuffer
= temp
;
775 DEBUG_printf(("_httpTLSRead: Resized decryption buffer to %d bytes.", sspi
->decryptBufferLength
));
778 buffers
[0].pvBuffer
= sspi
->decryptBuffer
;
779 buffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
780 buffers
[0].BufferType
= SECBUFFER_DATA
;
781 buffers
[1].BufferType
= SECBUFFER_EMPTY
;
782 buffers
[2].BufferType
= SECBUFFER_EMPTY
;
783 buffers
[3].BufferType
= SECBUFFER_EMPTY
;
785 DEBUG_printf(("5_httpTLSRead: decryptBufferUsed=%d", sspi
->decryptBufferUsed
));
787 scRet
= DecryptMessage(&sspi
->context
, &message
, 0, NULL
);
789 if (scRet
== SEC_E_INCOMPLETE_MESSAGE
)
791 num
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
794 DEBUG_printf(("5_httpTLSRead: recv failed: %d", WSAGetLastError()));
799 DEBUG_puts("5_httpTLSRead: Server disconnected.");
803 DEBUG_printf(("5_httpTLSRead: Read %d bytes into decryption buffer.", num
));
805 sspi
->decryptBufferUsed
+= num
;
808 while (scRet
== SEC_E_INCOMPLETE_MESSAGE
);
810 if (scRet
== SEC_I_CONTEXT_EXPIRED
)
812 DEBUG_puts("5_httpTLSRead: Context expired.");
813 WSASetLastError(WSAECONNRESET
);
816 else if (scRet
!= SEC_E_OK
)
818 DEBUG_printf(("5_httpTLSRead: DecryptMessage failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
819 WSASetLastError(WSASYSCALLFAILURE
);
824 * The decryption worked. Now, locate data buffer.
830 for (i
= 1; i
< 4; i
++)
832 if (buffers
[i
].BufferType
== SECBUFFER_DATA
)
833 pDataBuffer
= &buffers
[i
];
834 else if (!pExtraBuffer
&& (buffers
[i
].BufferType
== SECBUFFER_EXTRA
))
835 pExtraBuffer
= &buffers
[i
];
839 * If a data buffer is found, then copy the decrypted bytes to the passed-in
845 int bytesToCopy
= min((int)pDataBuffer
->cbBuffer
, len
);
846 /* Number of bytes to copy into buf */
847 int bytesToSave
= pDataBuffer
->cbBuffer
- bytesToCopy
;
848 /* Number of bytes to save in our read buffer */
851 memcpy(buf
, pDataBuffer
->pvBuffer
, bytesToCopy
);
854 * If there are more decrypted bytes than can be copied to the passed in
855 * buffer, then save them...
860 if ((sspi
->readBufferLength
- sspi
->readBufferUsed
) < bytesToSave
)
862 BYTE
*temp
; /* New buffer pointer */
864 if ((temp
= realloc(sspi
->readBuffer
, sspi
->readBufferUsed
+ bytesToSave
)) == NULL
)
866 DEBUG_printf(("_httpTLSRead: Unable to allocate %d bytes.", sspi
->readBufferUsed
+ bytesToSave
));
867 WSASetLastError(E_OUTOFMEMORY
);
871 sspi
->readBufferLength
= sspi
->readBufferUsed
+ bytesToSave
;
872 sspi
->readBuffer
= temp
;
875 memcpy(((BYTE
*)sspi
->readBuffer
) + sspi
->readBufferUsed
, ((BYTE
*)pDataBuffer
->pvBuffer
) + bytesToCopy
, bytesToSave
);
877 sspi
->readBufferUsed
+= bytesToSave
;
884 DEBUG_puts("_httpTLSRead: Unable to find data buffer.");
885 WSASetLastError(WSASYSCALLFAILURE
);
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.
896 memmove(sspi
->decryptBuffer
, pExtraBuffer
->pvBuffer
, pExtraBuffer
->cbBuffer
);
897 sspi
->decryptBufferUsed
= pExtraBuffer
->cbBuffer
;
901 sspi
->decryptBufferUsed
= 0;
909 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
913 _httpTLSSetOptions(int options
) /* I - Options */
915 if (!(options
& _HTTP_TLS_SET_DEFAULT
) || tls_options
< 0)
917 tls_options
= options
;
918 tls_min_version
= min_version
;
919 tls_max_version
= max_version
;
925 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
928 int /* O - 0 on success, -1 on failure */
929 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
931 char hostname
[256], /* Hostname */
932 *hostptr
; /* Pointer into hostname */
935 DEBUG_printf(("3_httpTLSStart(http=%p)", http
));
939 DEBUG_puts("4_httpTLSStart: Setting defaults.");
941 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
944 if ((http
->tls
= http_sspi_alloc()) == NULL
)
947 if (http
->mode
== _HTTP_MODE_CLIENT
)
950 * Client: determine hostname...
953 if (httpAddrLocalhost(http
->hostaddr
))
955 strlcpy(hostname
, "localhost", sizeof(hostname
));
960 * Otherwise make sure the hostname we have does not end in a trailing dot.
963 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
964 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
969 return (http_sspi_client(http
, hostname
));
974 * Server: determine hostname to use...
977 if (http
->fields
[HTTP_FIELD_HOST
][0])
980 * Use hostname for TLS upgrade...
983 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
988 * Resolve hostname from connection address...
991 http_addr_t addr
; /* Connection address */
992 socklen_t addrlen
; /* Length of address */
994 addrlen
= sizeof(addr
);
995 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
997 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
1000 else if (httpAddrLocalhost(&addr
))
1004 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1005 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1009 return (http_sspi_server(http
, hostname
));
1015 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1019 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1021 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1024 if (sspi
->contextInitialized
&& http
->fd
>= 0)
1026 SecBufferDesc message
; /* Array of SecBuffer struct */
1027 SecBuffer buffers
[1] = { 0 };
1028 /* Security package buffer */
1029 DWORD dwType
; /* Type */
1030 DWORD status
; /* Status */
1033 * Notify schannel that we are about to close the connection.
1036 dwType
= SCHANNEL_SHUTDOWN
;
1038 buffers
[0].pvBuffer
= &dwType
;
1039 buffers
[0].BufferType
= SECBUFFER_TOKEN
;
1040 buffers
[0].cbBuffer
= sizeof(dwType
);
1042 message
.cBuffers
= 1;
1043 message
.pBuffers
= buffers
;
1044 message
.ulVersion
= SECBUFFER_VERSION
;
1046 status
= ApplyControlToken(&sspi
->context
, &message
);
1048 if (SUCCEEDED(status
))
1050 PBYTE pbMessage
; /* Message buffer */
1051 DWORD cbMessage
; /* Message buffer count */
1052 DWORD cbData
; /* Data count */
1053 DWORD dwSSPIFlags
; /* SSL attributes we requested */
1054 DWORD dwSSPIOutFlags
; /* SSL attributes we received */
1055 TimeStamp tsExpiry
; /* Time stamp */
1057 dwSSPIFlags
= ASC_REQ_SEQUENCE_DETECT
|
1058 ASC_REQ_REPLAY_DETECT
|
1059 ASC_REQ_CONFIDENTIALITY
|
1060 ASC_REQ_EXTENDED_ERROR
|
1061 ASC_REQ_ALLOCATE_MEMORY
|
1064 buffers
[0].pvBuffer
= NULL
;
1065 buffers
[0].BufferType
= SECBUFFER_TOKEN
;
1066 buffers
[0].cbBuffer
= 0;
1068 message
.cBuffers
= 1;
1069 message
.pBuffers
= buffers
;
1070 message
.ulVersion
= SECBUFFER_VERSION
;
1072 status
= AcceptSecurityContext(&sspi
->creds
, &sspi
->context
, NULL
,
1073 dwSSPIFlags
, SECURITY_NATIVE_DREP
, NULL
,
1074 &message
, &dwSSPIOutFlags
, &tsExpiry
);
1076 if (SUCCEEDED(status
))
1078 pbMessage
= buffers
[0].pvBuffer
;
1079 cbMessage
= buffers
[0].cbBuffer
;
1082 * Send the close notify message to the client.
1085 if (pbMessage
&& cbMessage
)
1087 cbData
= send(http
->fd
, pbMessage
, cbMessage
, 0);
1088 if ((cbData
== SOCKET_ERROR
) || (cbData
== 0))
1090 status
= WSAGetLastError();
1091 DEBUG_printf(("_httpTLSStop: sending close notify failed: %d", status
));
1095 FreeContextBuffer(pbMessage
);
1101 DEBUG_printf(("_httpTLSStop: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), status
)));
1106 DEBUG_printf(("_httpTLSStop: ApplyControlToken failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), status
)));
1110 http_sspi_free(sspi
);
1117 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1120 int /* O - Bytes written */
1121 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1122 const char *buf
, /* I - Buffer holding data */
1123 int len
) /* I - Length of buffer */
1125 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1126 SecBufferDesc message
; /* Array of SecBuffer struct */
1127 SecBuffer buffers
[4] = { 0 }; /* Security package buffer */
1128 int bufferLen
; /* Buffer length */
1129 int bytesLeft
; /* Bytes left to write */
1130 const char *bufptr
; /* Pointer into buffer */
1131 int num
= 0; /* Return value */
1134 bufferLen
= sspi
->streamSizes
.cbMaximumMessage
+ sspi
->streamSizes
.cbHeader
+ sspi
->streamSizes
.cbTrailer
;
1136 if (bufferLen
> sspi
->writeBufferLength
)
1138 BYTE
*temp
; /* New buffer pointer */
1140 if ((temp
= (BYTE
*)realloc(sspi
->writeBuffer
, bufferLen
)) == NULL
)
1142 DEBUG_printf(("_httpTLSWrite: Unable to allocate buffer of %d bytes.", bufferLen
));
1143 WSASetLastError(E_OUTOFMEMORY
);
1147 sspi
->writeBuffer
= temp
;
1148 sspi
->writeBufferLength
= bufferLen
;
1156 int chunk
= min((int)sspi
->streamSizes
.cbMaximumMessage
, bytesLeft
);
1157 /* Size of data to write */
1158 SECURITY_STATUS scRet
; /* SSPI status */
1161 * Copy user data into the buffer, starting just past the header...
1164 memcpy(sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
, bufptr
, chunk
);
1167 * Setup the SSPI buffers
1170 message
.ulVersion
= SECBUFFER_VERSION
;
1171 message
.cBuffers
= 4;
1172 message
.pBuffers
= buffers
;
1174 buffers
[0].pvBuffer
= sspi
->writeBuffer
;
1175 buffers
[0].cbBuffer
= sspi
->streamSizes
.cbHeader
;
1176 buffers
[0].BufferType
= SECBUFFER_STREAM_HEADER
;
1177 buffers
[1].pvBuffer
= sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
;
1178 buffers
[1].cbBuffer
= (unsigned long) chunk
;
1179 buffers
[1].BufferType
= SECBUFFER_DATA
;
1180 buffers
[2].pvBuffer
= sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
+ chunk
;
1181 buffers
[2].cbBuffer
= sspi
->streamSizes
.cbTrailer
;
1182 buffers
[2].BufferType
= SECBUFFER_STREAM_TRAILER
;
1183 buffers
[3].BufferType
= SECBUFFER_EMPTY
;
1189 scRet
= EncryptMessage(&sspi
->context
, 0, &message
, 0);
1193 DEBUG_printf(("_httpTLSWrite: EncryptMessage failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1194 WSASetLastError(WSASYSCALLFAILURE
);
1199 * Send the data. Remember the size of the total data to send is the size
1200 * of the header, the size of the data the caller passed in and the size
1204 num
= send(http
->fd
, sspi
->writeBuffer
, buffers
[0].cbBuffer
+ buffers
[1].cbBuffer
+ buffers
[2].cbBuffer
, 0);
1208 DEBUG_printf(("_httpTLSWrite: send failed: %ld", WSAGetLastError()));
1222 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
1225 static int /* O - 0 on success, -1 on failure */
1226 http_setup_ssl(http_t
*http
) /* I - Connection to server */
1228 char hostname
[256], /* Hostname */
1229 *hostptr
; /* Pointer into hostname */
1231 TCHAR username
[256]; /* Username returned from GetUserName() */
1232 TCHAR commonName
[256];/* Common name for certificate */
1233 DWORD dwSize
; /* 32 bit size */
1236 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
1239 * Get the hostname to use for SSL...
1242 if (httpAddrLocalhost(http
->hostaddr
))
1244 strlcpy(hostname
, "localhost", sizeof(hostname
));
1249 * Otherwise make sure the hostname we have does not end in a trailing dot.
1252 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1253 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1258 http
->tls
= http_sspi_alloc();
1262 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1266 dwSize
= sizeof(username
) / sizeof(TCHAR
);
1267 GetUserName(username
, &dwSize
);
1268 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
1269 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
1271 if (!_sspiGetCredentials(http
->tls
, L
"ClientContainer",
1274 _sspiFree(http
->tls
);
1278 http
->status
= HTTP_STATUS_ERROR
;
1280 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
1281 _("Unable to establish a secure connection to host."), 1);
1286 _sspiSetAllowsAnyRoot(http
->tls
, TRUE
);
1287 _sspiSetAllowsExpiredCerts(http
->tls
, TRUE
);
1289 if (!_sspiConnect(http
->tls
, hostname
))
1291 _sspiFree(http
->tls
);
1295 http
->status
= HTTP_STATUS_ERROR
;
1297 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
1298 _("Unable to establish a secure connection to host."), 1);
1309 * 'http_sspi_alloc()' - Allocate SSPI object.
1312 static _http_sspi_t
* /* O - New SSPI/SSL object */
1313 http_sspi_alloc(void)
1315 return ((_http_sspi_t
*)calloc(sizeof(_http_sspi_t
), 1));
1320 * 'http_sspi_client()' - Negotiate a TLS connection as a client.
1323 static int /* O - 0 on success, -1 on failure */
1324 http_sspi_client(http_t
*http
, /* I - Client connection */
1325 const char *hostname
) /* I - Server hostname */
1327 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1328 DWORD dwSize
; /* Size for buffer */
1329 DWORD dwSSPIFlags
; /* SSL connection attributes we want */
1330 DWORD dwSSPIOutFlags
; /* SSL connection attributes we got */
1331 TimeStamp tsExpiry
; /* Time stamp */
1332 SECURITY_STATUS scRet
; /* Status */
1333 int cbData
; /* Data count */
1334 SecBufferDesc inBuffer
; /* Array of SecBuffer structs */
1335 SecBuffer inBuffers
[2]; /* Security package buffer */
1336 SecBufferDesc outBuffer
; /* Array of SecBuffer structs */
1337 SecBuffer outBuffers
[1]; /* Security package buffer */
1338 int ret
= 0; /* Return value */
1339 char username
[1024], /* Current username */
1340 common_name
[1024]; /* CN=username */
1343 DEBUG_printf(("4http_sspi_client(http=%p, hostname=\"%s\")", http
, hostname
));
1345 dwSSPIFlags
= ISC_REQ_SEQUENCE_DETECT
|
1346 ISC_REQ_REPLAY_DETECT
|
1347 ISC_REQ_CONFIDENTIALITY
|
1348 ISC_RET_EXTENDED_ERROR
|
1349 ISC_REQ_ALLOCATE_MEMORY
|
1353 * Lookup the client certificate...
1356 dwSize
= sizeof(username
);
1357 GetUserName(username
, &dwSize
);
1358 snprintf(common_name
, sizeof(common_name
), "CN=%s", username
);
1360 if (!http_sspi_find_credentials(http
, L
"ClientContainer", common_name
))
1361 if (!http_sspi_make_credentials(http
->tls
, L
"ClientContainer", common_name
, _HTTP_MODE_CLIENT
, 10))
1363 DEBUG_puts("5http_sspi_client: Unable to get client credentials.");
1368 * Initiate a ClientHello message and generate a token.
1371 outBuffers
[0].pvBuffer
= NULL
;
1372 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1373 outBuffers
[0].cbBuffer
= 0;
1375 outBuffer
.cBuffers
= 1;
1376 outBuffer
.pBuffers
= outBuffers
;
1377 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
1379 scRet
= InitializeSecurityContext(&sspi
->creds
, NULL
, TEXT(""), dwSSPIFlags
, 0, SECURITY_NATIVE_DREP
, NULL
, 0, &sspi
->context
, &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
1381 if (scRet
!= SEC_I_CONTINUE_NEEDED
)
1383 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(1) failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1388 * Send response to server if there is one.
1391 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
1393 if ((cbData
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0)) <= 0)
1395 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1396 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1397 DeleteSecurityContext(&sspi
->context
);
1401 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData
));
1403 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1404 outBuffers
[0].pvBuffer
= NULL
;
1407 dwSSPIFlags
= ISC_REQ_MANUAL_CRED_VALIDATION
|
1408 ISC_REQ_SEQUENCE_DETECT
|
1409 ISC_REQ_REPLAY_DETECT
|
1410 ISC_REQ_CONFIDENTIALITY
|
1411 ISC_RET_EXTENDED_ERROR
|
1412 ISC_REQ_ALLOCATE_MEMORY
|
1415 sspi
->decryptBufferUsed
= 0;
1418 * Loop until the handshake is finished or an error occurs.
1421 scRet
= SEC_I_CONTINUE_NEEDED
;
1423 while(scRet
== SEC_I_CONTINUE_NEEDED
||
1424 scRet
== SEC_E_INCOMPLETE_MESSAGE
||
1425 scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
1427 if (sspi
->decryptBufferUsed
== 0 || scRet
== SEC_E_INCOMPLETE_MESSAGE
)
1429 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
1431 BYTE
*temp
; /* New buffer */
1433 if (sspi
->decryptBufferLength
>= 262144)
1435 WSASetLastError(E_OUTOFMEMORY
);
1436 DEBUG_puts("5http_sspi_client: Decryption buffer too large (>256k)");
1440 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
1442 DEBUG_printf(("5http_sspi_client: Unable to allocate %d byte buffer.", sspi
->decryptBufferLength
+ 4096));
1443 WSASetLastError(E_OUTOFMEMORY
);
1447 sspi
->decryptBufferLength
+= 4096;
1448 sspi
->decryptBuffer
= temp
;
1451 cbData
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
1455 DEBUG_printf(("5http_sspi_client: recv failed: %d", WSAGetLastError()));
1458 else if (cbData
== 0)
1460 DEBUG_printf(("5http_sspi_client: Server unexpectedly disconnected."));
1464 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data received", cbData
));
1466 sspi
->decryptBufferUsed
+= cbData
;
1470 * Set up the input buffers. Buffer 0 is used to pass in data received from
1471 * the server. Schannel will consume some or all of this. Leftover data
1472 * (if any) will be placed in buffer 1 and given a buffer type of
1476 inBuffers
[0].pvBuffer
= sspi
->decryptBuffer
;
1477 inBuffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
1478 inBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1480 inBuffers
[1].pvBuffer
= NULL
;
1481 inBuffers
[1].cbBuffer
= 0;
1482 inBuffers
[1].BufferType
= SECBUFFER_EMPTY
;
1484 inBuffer
.cBuffers
= 2;
1485 inBuffer
.pBuffers
= inBuffers
;
1486 inBuffer
.ulVersion
= SECBUFFER_VERSION
;
1489 * Set up the output buffers. These are initialized to NULL so as to make it
1490 * less likely we'll attempt to free random garbage later.
1493 outBuffers
[0].pvBuffer
= NULL
;
1494 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1495 outBuffers
[0].cbBuffer
= 0;
1497 outBuffer
.cBuffers
= 1;
1498 outBuffer
.pBuffers
= outBuffers
;
1499 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
1502 * Call InitializeSecurityContext.
1505 scRet
= InitializeSecurityContext(&sspi
->creds
, &sspi
->context
, NULL
, dwSSPIFlags
, 0, SECURITY_NATIVE_DREP
, &inBuffer
, 0, NULL
, &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
1508 * If InitializeSecurityContext was successful (or if the error was one of
1509 * the special extended ones), send the contents of the output buffer to the
1513 if (scRet
== SEC_E_OK
||
1514 scRet
== SEC_I_CONTINUE_NEEDED
||
1515 FAILED(scRet
) && (dwSSPIOutFlags
& ISC_RET_EXTENDED_ERROR
))
1517 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
1519 cbData
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0);
1523 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1524 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1525 DeleteSecurityContext(&sspi
->context
);
1529 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData
));
1532 * Free output buffer.
1535 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1536 outBuffers
[0].pvBuffer
= NULL
;
1541 * If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, then we
1542 * need to read more data from the server and try again.
1545 if (scRet
== SEC_E_INCOMPLETE_MESSAGE
)
1549 * If InitializeSecurityContext returned SEC_E_OK, then the handshake
1550 * completed successfully.
1553 if (scRet
== SEC_E_OK
)
1556 * If the "extra" buffer contains data, this is encrypted application
1557 * protocol layer stuff. It needs to be saved. The application layer will
1558 * later decrypt it with DecryptMessage.
1561 DEBUG_puts("5http_sspi_client: Handshake was successful.");
1563 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
1565 memmove(sspi
->decryptBuffer
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
, inBuffers
[1].cbBuffer
);
1567 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
1569 DEBUG_printf(("5http_sspi_client: %d bytes of app data was bundled with handshake data", sspi
->decryptBufferUsed
));
1572 sspi
->decryptBufferUsed
= 0;
1582 * Check for fatal error.
1587 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(2) failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1593 * If InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS,
1594 * then the server just requested client authentication.
1597 if (scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
1603 DEBUG_printf(("5http_sspi_client: server requested client credentials."));
1609 * Copy any leftover data from the "extra" buffer, and go around again.
1612 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
1614 memmove(sspi
->decryptBuffer
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
, inBuffers
[1].cbBuffer
);
1616 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
1620 sspi
->decryptBufferUsed
= 0;
1627 * Success! Get the server cert
1630 sspi
->contextInitialized
= TRUE
;
1632 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_REMOTE_CERT_CONTEXT
, (VOID
*)&(sspi
->remoteCert
));
1634 if (scRet
!= SEC_E_OK
)
1636 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_REMOTE_CERT_CONTEXT): %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1641 * Find out how big the header/trailer will be:
1644 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_STREAM_SIZES
, &sspi
->streamSizes
);
1646 if (scRet
!= SEC_E_OK
)
1648 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_STREAM_SIZES): %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1658 * 'http_sspi_create_credential()' - Create an SSPI certificate context.
1661 static PCCERT_CONTEXT
/* O - Certificate context */
1662 http_sspi_create_credential(
1663 http_credential_t
*cred
) /* I - Credential */
1666 return (CertCreateCertificateContext(X509_ASN_ENCODING
, cred
->data
, cred
->datalen
));
1673 * 'http_sspi_find_credentials()' - Retrieve a TLS certificate from the system store.
1676 static BOOL
/* O - 1 on success, 0 on failure */
1677 http_sspi_find_credentials(
1678 http_t
*http
, /* I - HTTP connection */
1679 const LPWSTR container
, /* I - Cert container name */
1680 const char *common_name
) /* I - Common name of certificate */
1682 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1683 HCERTSTORE store
= NULL
; /* Certificate store */
1684 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
1685 DWORD dwSize
= 0; /* 32 bit size */
1686 PBYTE p
= NULL
; /* Temporary storage */
1687 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
1688 /* Handle to a CSP */
1689 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
1690 SCHANNEL_CRED SchannelCred
; /* Schannel credential data */
1691 TimeStamp tsExpiry
; /* Time stamp */
1692 SECURITY_STATUS Status
; /* Status */
1693 BOOL ok
= TRUE
; /* Return value */
1696 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
1698 if (GetLastError() == NTE_EXISTS
)
1700 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
1702 DEBUG_printf(("5http_sspi_find_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1709 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");
1713 DEBUG_printf(("5http_sspi_find_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1720 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
1722 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1727 p
= (PBYTE
)malloc(dwSize
);
1731 DEBUG_printf(("5http_sspi_find_credentials: malloc failed for %d bytes.", dwSize
));
1736 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
1738 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1743 sib
.cbData
= dwSize
;
1746 storedContext
= CertFindCertificateInStore(store
, X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, 0, CERT_FIND_SUBJECT_NAME
, &sib
, NULL
);
1750 DEBUG_printf(("5http_sspi_find_credentials: Unable to find credentials for \"%s\".", common_name
));
1755 ZeroMemory(&SchannelCred
, sizeof(SchannelCred
));
1757 SchannelCred
.dwVersion
= SCHANNEL_CRED_VERSION
;
1758 SchannelCred
.cCreds
= 1;
1759 SchannelCred
.paCred
= &storedContext
;
1762 * Set supported protocols (can also be overriden in the registry...)
1765 #ifdef SP_PROT_TLS1_2_SERVER
1766 if (http
->mode
== _HTTP_MODE_SERVER
)
1768 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1769 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
;
1770 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1771 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
| SP_PROT_TLS1_0_SERVER
| SP_PROT_SSL3_SERVER
;
1773 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
| SP_PROT_TLS1_0_SERVER
;
1777 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1778 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
;
1779 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1780 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
| SP_PROT_TLS1_0_CLIENT
| SP_PROT_SSL3_CLIENT
;
1782 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
| SP_PROT_TLS1_0_CLIENT
;
1786 if (http
->mode
== _HTTP_MODE_SERVER
)
1788 if (tls_min_version
== _HTTP_TLS_SSL3
)
1789 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_SERVER
| SP_PROT_SSL3_SERVER
;
1791 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_SERVER
;
1795 if (tls_min_version
== _HTTP_TLS_SSL3
)
1796 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_CLIENT
| SP_PROT_SSL3_CLIENT
;
1798 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_CLIENT
;
1800 #endif /* SP_PROT_TLS1_2_SERVER */
1802 /* TODO: Support _HTTP_TLS_ALLOW_RC4, _HTTP_TLS_ALLOW_DH, and _HTTP_TLS_DENY_CBC options; right now we'll rely on Windows registry to enable/disable RC4/DH/CBC... */
1805 * Create an SSPI credential.
1808 Status
= AcquireCredentialsHandle(NULL
, UNISP_NAME
, http
->mode
== _HTTP_MODE_SERVER
? SECPKG_CRED_INBOUND
: SECPKG_CRED_OUTBOUND
, NULL
, &SchannelCred
, NULL
, NULL
, &sspi
->creds
, &tsExpiry
);
1809 if (Status
!= SEC_E_OK
)
1811 DEBUG_printf(("5http_sspi_find_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), Status
)));
1823 CertFreeCertificateContext(storedContext
);
1829 CertCloseStore(store
, 0);
1832 CryptReleaseContext(hProv
, 0);
1839 * 'http_sspi_free()' - Close a connection and free resources.
1843 http_sspi_free(_http_sspi_t
*sspi
) /* I - SSPI data */
1848 if (sspi
->contextInitialized
)
1849 DeleteSecurityContext(&sspi
->context
);
1851 if (sspi
->decryptBuffer
)
1852 free(sspi
->decryptBuffer
);
1854 if (sspi
->readBuffer
)
1855 free(sspi
->readBuffer
);
1857 if (sspi
->writeBuffer
)
1858 free(sspi
->writeBuffer
);
1860 if (sspi
->localCert
)
1861 CertFreeCertificateContext(sspi
->localCert
);
1863 if (sspi
->remoteCert
)
1864 CertFreeCertificateContext(sspi
->remoteCert
);
1871 * 'http_sspi_make_credentials()' - Create a TLS certificate in the system store.
1874 static BOOL
/* O - 1 on success, 0 on failure */
1875 http_sspi_make_credentials(
1876 _http_sspi_t
*sspi
, /* I - SSPI data */
1877 const LPWSTR container
, /* I - Cert container name */
1878 const char *common_name
, /* I - Common name of certificate */
1879 _http_mode_t mode
, /* I - Client or server? */
1880 int years
) /* I - Years until expiration */
1882 HCERTSTORE store
= NULL
; /* Certificate store */
1883 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
1884 PCCERT_CONTEXT createdContext
= NULL
; /* Context created by us */
1885 DWORD dwSize
= 0; /* 32 bit size */
1886 PBYTE p
= NULL
; /* Temporary storage */
1887 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
1888 /* Handle to a CSP */
1889 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
1890 SCHANNEL_CRED SchannelCred
; /* Schannel credential data */
1891 TimeStamp tsExpiry
; /* Time stamp */
1892 SECURITY_STATUS Status
; /* Status */
1893 HCRYPTKEY hKey
= (HCRYPTKEY
)NULL
; /* Handle to crypto key */
1894 CRYPT_KEY_PROV_INFO kpi
; /* Key container info */
1895 SYSTEMTIME et
; /* System time */
1896 CERT_EXTENSIONS exts
; /* Array of cert extensions */
1897 CRYPT_KEY_PROV_INFO ckp
; /* Handle to crypto key */
1898 BOOL ok
= TRUE
; /* Return value */
1901 DEBUG_printf(("4http_sspi_make_credentials(sspi=%p, container=%p, common_name=\"%s\", mode=%d, years=%d)", sspi
, container
, common_name
, mode
, years
));
1903 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
1905 if (GetLastError() == NTE_EXISTS
)
1907 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
1909 DEBUG_printf(("5http_sspi_make_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1916 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");
1920 DEBUG_printf(("5http_sspi_make_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1927 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
1929 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1934 p
= (PBYTE
)malloc(dwSize
);
1938 DEBUG_printf(("5http_sspi_make_credentials: malloc failed for %d bytes", dwSize
));
1943 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
1945 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1951 * Create a private key and self-signed certificate...
1954 if (!CryptGenKey(hProv
, AT_KEYEXCHANGE
, CRYPT_EXPORTABLE
, &hKey
))
1956 DEBUG_printf(("5http_sspi_make_credentials: CryptGenKey failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1961 ZeroMemory(&kpi
, sizeof(kpi
));
1962 kpi
.pwszContainerName
= (LPWSTR
)container
;
1963 kpi
.pwszProvName
= MS_DEF_PROV_W
;
1964 kpi
.dwProvType
= PROV_RSA_FULL
;
1965 kpi
.dwFlags
= CERT_SET_KEY_CONTEXT_PROP_ID
;
1966 kpi
.dwKeySpec
= AT_KEYEXCHANGE
;
1971 ZeroMemory(&exts
, sizeof(exts
));
1973 createdContext
= CertCreateSelfSignCertificate(hProv
, &sib
, 0, &kpi
, NULL
, NULL
, &et
, &exts
);
1975 if (!createdContext
)
1977 DEBUG_printf(("5http_sspi_make_credentials: CertCreateSelfSignCertificate failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1983 * Add the created context to the named store, and associate it with the named
1987 if (!CertAddCertificateContextToStore(store
, createdContext
, CERT_STORE_ADD_REPLACE_EXISTING
, &storedContext
))
1989 DEBUG_printf(("5http_sspi_make_credentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1994 ZeroMemory(&ckp
, sizeof(ckp
));
1995 ckp
.pwszContainerName
= (LPWSTR
) container
;
1996 ckp
.pwszProvName
= MS_DEF_PROV_W
;
1997 ckp
.dwProvType
= PROV_RSA_FULL
;
1998 ckp
.dwFlags
= CRYPT_MACHINE_KEYSET
;
1999 ckp
.dwKeySpec
= AT_KEYEXCHANGE
;
2001 if (!CertSetCertificateContextProperty(storedContext
, CERT_KEY_PROV_INFO_PROP_ID
, 0, &ckp
))
2003 DEBUG_printf(("5http_sspi_make_credentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
2009 * Get a handle to use the certificate...
2012 ZeroMemory(&SchannelCred
, sizeof(SchannelCred
));
2014 SchannelCred
.dwVersion
= SCHANNEL_CRED_VERSION
;
2015 SchannelCred
.cCreds
= 1;
2016 SchannelCred
.paCred
= &storedContext
;
2019 * SSPI doesn't seem to like it if grbitEnabledProtocols is set for a client.
2022 if (mode
== _HTTP_MODE_SERVER
)
2023 SchannelCred
.grbitEnabledProtocols
= SP_PROT_SSL3TLS1
;
2026 * Create an SSPI credential.
2029 Status
= AcquireCredentialsHandle(NULL
, UNISP_NAME
, mode
== _HTTP_MODE_SERVER
? SECPKG_CRED_INBOUND
: SECPKG_CRED_OUTBOUND
, NULL
, &SchannelCred
, NULL
, NULL
, &sspi
->creds
, &tsExpiry
);
2030 if (Status
!= SEC_E_OK
)
2032 DEBUG_printf(("5http_sspi_make_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), Status
)));
2044 CryptDestroyKey(hKey
);
2047 CertFreeCertificateContext(createdContext
);
2050 CertFreeCertificateContext(storedContext
);
2056 CertCloseStore(store
, 0);
2059 CryptReleaseContext(hProv
, 0);
2066 * 'http_sspi_server()' - Negotiate a TLS connection as a server.
2069 static int /* O - 0 on success, -1 on failure */
2070 http_sspi_server(http_t
*http
, /* I - HTTP connection */
2071 const char *hostname
) /* I - Hostname of server */
2073 _http_sspi_t
*sspi
= http
->tls
; /* I - SSPI data */
2074 char common_name
[512]; /* Common name for cert */
2075 DWORD dwSSPIFlags
; /* SSL connection attributes we want */
2076 DWORD dwSSPIOutFlags
; /* SSL connection attributes we got */
2077 TimeStamp tsExpiry
; /* Time stamp */
2078 SECURITY_STATUS scRet
; /* SSPI Status */
2079 SecBufferDesc inBuffer
; /* Array of SecBuffer structs */
2080 SecBuffer inBuffers
[2]; /* Security package buffer */
2081 SecBufferDesc outBuffer
; /* Array of SecBuffer structs */
2082 SecBuffer outBuffers
[1]; /* Security package buffer */
2083 int num
= 0; /* 32 bit status value */
2084 BOOL fInitContext
= TRUE
; /* Has the context been init'd? */
2085 int ret
= 0; /* Return value */
2088 DEBUG_printf(("4http_sspi_server(http=%p, hostname=\"%s\")", http
, hostname
));
2090 dwSSPIFlags
= ASC_REQ_SEQUENCE_DETECT
|
2091 ASC_REQ_REPLAY_DETECT
|
2092 ASC_REQ_CONFIDENTIALITY
|
2093 ASC_REQ_EXTENDED_ERROR
|
2094 ASC_REQ_ALLOCATE_MEMORY
|
2097 sspi
->decryptBufferUsed
= 0;
2100 * Lookup the server certificate...
2103 snprintf(common_name
, sizeof(common_name
), "CN=%s", hostname
);
2105 if (!http_sspi_find_credentials(http
, L
"ServerContainer", common_name
))
2106 if (!http_sspi_make_credentials(http
->tls
, L
"ServerContainer", common_name
, _HTTP_MODE_SERVER
, 10))
2108 DEBUG_puts("5http_sspi_server: Unable to get server credentials.");
2113 * Set OutBuffer for AcceptSecurityContext call
2116 outBuffer
.cBuffers
= 1;
2117 outBuffer
.pBuffers
= outBuffers
;
2118 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
2120 scRet
= SEC_I_CONTINUE_NEEDED
;
2122 while (scRet
== SEC_I_CONTINUE_NEEDED
||
2123 scRet
== SEC_E_INCOMPLETE_MESSAGE
||
2124 scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
2126 if (sspi
->decryptBufferUsed
== 0 || scRet
== SEC_E_INCOMPLETE_MESSAGE
)
2128 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
2130 BYTE
*temp
; /* New buffer */
2132 if (sspi
->decryptBufferLength
>= 262144)
2134 WSASetLastError(E_OUTOFMEMORY
);
2135 DEBUG_puts("5http_sspi_server: Decryption buffer too large (>256k)");
2139 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
2141 DEBUG_printf(("5http_sspi_server: Unable to allocate %d byte buffer.", sspi
->decryptBufferLength
+ 4096));
2142 WSASetLastError(E_OUTOFMEMORY
);
2146 sspi
->decryptBufferLength
+= 4096;
2147 sspi
->decryptBuffer
= temp
;
2152 num
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
2154 if (num
== -1 && WSAGetLastError() == WSAEWOULDBLOCK
)
2162 DEBUG_printf(("5http_sspi_server: recv failed: %d", WSAGetLastError()));
2167 DEBUG_puts("5http_sspi_server: client disconnected");
2171 DEBUG_printf(("5http_sspi_server: received %d (handshake) bytes from client.", num
));
2172 sspi
->decryptBufferUsed
+= num
;
2176 * InBuffers[1] is for getting extra data that SSPI/SCHANNEL doesn't process
2177 * on this run around the loop.
2180 inBuffers
[0].pvBuffer
= sspi
->decryptBuffer
;
2181 inBuffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
2182 inBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
2184 inBuffers
[1].pvBuffer
= NULL
;
2185 inBuffers
[1].cbBuffer
= 0;
2186 inBuffers
[1].BufferType
= SECBUFFER_EMPTY
;
2188 inBuffer
.cBuffers
= 2;
2189 inBuffer
.pBuffers
= inBuffers
;
2190 inBuffer
.ulVersion
= SECBUFFER_VERSION
;
2193 * Initialize these so if we fail, pvBuffer contains NULL, so we don't try to
2194 * free random garbage at the quit.
2197 outBuffers
[0].pvBuffer
= NULL
;
2198 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
2199 outBuffers
[0].cbBuffer
= 0;
2201 scRet
= AcceptSecurityContext(&sspi
->creds
, (fInitContext
?NULL
:&sspi
->context
), &inBuffer
, dwSSPIFlags
, SECURITY_NATIVE_DREP
, (fInitContext
?&sspi
->context
:NULL
), &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
2203 fInitContext
= FALSE
;
2205 if (scRet
== SEC_E_OK
||
2206 scRet
== SEC_I_CONTINUE_NEEDED
||
2207 (FAILED(scRet
) && ((dwSSPIOutFlags
& ISC_RET_EXTENDED_ERROR
) != 0)))
2209 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
2212 * Send response to server if there is one.
2215 num
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0);
2219 DEBUG_printf(("5http_sspi_server: handshake send failed: %d", WSAGetLastError()));
2223 DEBUG_printf(("5http_sspi_server: sent %d handshake bytes to client.", outBuffers
[0].cbBuffer
));
2225 FreeContextBuffer(outBuffers
[0].pvBuffer
);
2226 outBuffers
[0].pvBuffer
= NULL
;
2230 if (scRet
== SEC_E_OK
)
2233 * If there's extra data then save it for next time we go to decrypt.
2236 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
2238 memcpy(sspi
->decryptBuffer
, (LPBYTE
)(sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
), inBuffers
[1].cbBuffer
);
2239 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
2243 sspi
->decryptBufferUsed
= 0;
2247 else if (FAILED(scRet
) && scRet
!= SEC_E_INCOMPLETE_MESSAGE
)
2249 DEBUG_printf(("5http_sspi_server: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
2254 if (scRet
!= SEC_E_INCOMPLETE_MESSAGE
&&
2255 scRet
!= SEC_I_INCOMPLETE_CREDENTIALS
)
2257 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
2259 memcpy(sspi
->decryptBuffer
, (LPBYTE
)(sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
), inBuffers
[1].cbBuffer
);
2260 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
2264 sspi
->decryptBufferUsed
= 0;
2271 sspi
->contextInitialized
= TRUE
;
2274 * Find out how big the header will be:
2277 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_STREAM_SIZES
, &sspi
->streamSizes
);
2279 if (scRet
!= SEC_E_OK
)
2281 DEBUG_printf(("5http_sspi_server: QueryContextAttributes failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
2291 * 'http_sspi_strerror()' - Return a string for the specified error code.
2294 static const char * /* O - String for error */
2295 http_sspi_strerror(char *buffer
, /* I - Error message buffer */
2296 size_t bufsize
, /* I - Size of buffer */
2297 DWORD code
) /* I - Error code */
2299 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, code
, 0, buffer
, bufsize
, NULL
))
2302 * Strip trailing CR + LF...
2305 char *ptr
; /* Pointer into error message */
2307 for (ptr
= buffer
+ strlen(buffer
) - 1; ptr
>= buffer
; ptr
--)
2308 if (*ptr
== '\n' || *ptr
== '\r')
2314 snprintf(buffer
, bufsize
, "Unknown error %x", code
);
2321 * 'http_sspi_verify()' - Verify a certificate.
2324 static DWORD
/* O - Error code (0 == No error) */
2326 PCCERT_CONTEXT cert
, /* I - Server certificate */
2327 const char *common_name
, /* I - Common name */
2328 DWORD dwCertFlags
) /* I - Verification flags */
2330 HTTPSPolicyCallbackData httpsPolicy
; /* HTTPS Policy Struct */
2331 CERT_CHAIN_POLICY_PARA policyPara
; /* Cert chain policy parameters */
2332 CERT_CHAIN_POLICY_STATUS policyStatus
;/* Cert chain policy status */
2333 CERT_CHAIN_PARA chainPara
; /* Used for searching and matching criteria */
2334 PCCERT_CHAIN_CONTEXT chainContext
= NULL
;
2335 /* Certificate chain */
2336 PWSTR commonNameUnicode
= NULL
;
2337 /* Unicode common name */
2338 LPSTR rgszUsages
[] = { szOID_PKIX_KP_SERVER_AUTH
,
2339 szOID_SERVER_GATED_CRYPTO
,
2340 szOID_SGC_NETSCAPE
};
2341 /* How are we using this certificate? */
2342 DWORD cUsages
= sizeof(rgszUsages
) / sizeof(LPSTR
);
2343 /* Number of ites in rgszUsages */
2344 DWORD count
; /* 32 bit count variable */
2345 DWORD status
; /* Return value */
2347 char error
[1024]; /* Error message string */
2352 return (SEC_E_WRONG_PRINCIPAL
);
2355 * Convert common name to Unicode.
2358 if (!common_name
|| !*common_name
)
2359 return (SEC_E_WRONG_PRINCIPAL
);
2361 count
= MultiByteToWideChar(CP_ACP
, 0, common_name
, -1, NULL
, 0);
2362 commonNameUnicode
= LocalAlloc(LMEM_FIXED
, count
* sizeof(WCHAR
));
2363 if (!commonNameUnicode
)
2364 return (SEC_E_INSUFFICIENT_MEMORY
);
2366 if (!MultiByteToWideChar(CP_ACP
, 0, common_name
, -1, commonNameUnicode
, count
))
2368 LocalFree(commonNameUnicode
);
2369 return (SEC_E_WRONG_PRINCIPAL
);
2373 * Build certificate chain.
2376 ZeroMemory(&chainPara
, sizeof(chainPara
));
2378 chainPara
.cbSize
= sizeof(chainPara
);
2379 chainPara
.RequestedUsage
.dwType
= USAGE_MATCH_TYPE_OR
;
2380 chainPara
.RequestedUsage
.Usage
.cUsageIdentifier
= cUsages
;
2381 chainPara
.RequestedUsage
.Usage
.rgpszUsageIdentifier
= rgszUsages
;
2383 if (!CertGetCertificateChain(NULL
, cert
, NULL
, cert
->hCertStore
, &chainPara
, 0, NULL
, &chainContext
))
2385 status
= GetLastError();
2387 DEBUG_printf(("CertGetCertificateChain returned: %s", http_sspi_strerror(error
, sizeof(error
), status
)));
2389 LocalFree(commonNameUnicode
);
2394 * Validate certificate chain.
2397 ZeroMemory(&httpsPolicy
, sizeof(HTTPSPolicyCallbackData
));
2398 httpsPolicy
.cbStruct
= sizeof(HTTPSPolicyCallbackData
);
2399 httpsPolicy
.dwAuthType
= AUTHTYPE_SERVER
;
2400 httpsPolicy
.fdwChecks
= dwCertFlags
;
2401 httpsPolicy
.pwszServerName
= commonNameUnicode
;
2403 memset(&policyPara
, 0, sizeof(policyPara
));
2404 policyPara
.cbSize
= sizeof(policyPara
);
2405 policyPara
.pvExtraPolicyPara
= &httpsPolicy
;
2407 memset(&policyStatus
, 0, sizeof(policyStatus
));
2408 policyStatus
.cbSize
= sizeof(policyStatus
);
2410 if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL
, chainContext
, &policyPara
, &policyStatus
))
2412 status
= GetLastError();
2414 DEBUG_printf(("CertVerifyCertificateChainPolicy returned %s", http_sspi_strerror(error
, sizeof(error
), status
)));
2416 else if (policyStatus
.dwError
)
2417 status
= policyStatus
.dwError
;
2422 CertFreeCertificateChain(chainContext
);
2424 if (commonNameUnicode
)
2425 LocalFree(commonNameUnicode
);