2 * TLS support for CUPS on Windows using the Security Support Provider
5 * Copyright 2010-2017 by Apple Inc.
7 * Licensed under Apache License v2.0. See the file "LICENSE" for more information.
10 /**** This file is included from tls.c ****/
13 * Include necessary headers...
16 #include "debug-private.h"
20 * Include necessary libraries...
23 #pragma comment(lib, "Crypt32.lib")
24 #pragma comment(lib, "Secur32.lib")
25 #pragma comment(lib, "Ws2_32.lib")
32 #ifndef SECURITY_FLAG_IGNORE_UNKNOWN_CA
33 # define SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00000100 /* Untrusted root */
34 #endif /* SECURITY_FLAG_IGNORE_UNKNOWN_CA */
36 #ifndef SECURITY_FLAG_IGNORE_CERT_CN_INVALID
37 # define SECURITY_FLAG_IGNORE_CERT_CN_INVALID 0x00001000 /* Common name does not match */
38 #endif /* !SECURITY_FLAG_IGNORE_CERT_CN_INVALID */
40 #ifndef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
41 # define SECURITY_FLAG_IGNORE_CERT_DATE_INVALID 0x00002000 /* Expired X509 Cert. */
42 #endif /* !SECURITY_FLAG_IGNORE_CERT_DATE_INVALID */
49 static int tls_options
= -1,/* Options for TLS connections */
50 tls_min_version
= _HTTP_TLS_1_0
,
51 tls_max_version
= _HTTP_TLS_MAX
;
58 static _http_sspi_t
*http_sspi_alloc(void);
59 static int http_sspi_client(http_t
*http
, const char *hostname
);
60 static PCCERT_CONTEXT
http_sspi_create_credential(http_credential_t
*cred
);
61 static BOOL
http_sspi_find_credentials(http_t
*http
, const LPWSTR containerName
, const char *common_name
);
62 static void http_sspi_free(_http_sspi_t
*sspi
);
63 static BOOL
http_sspi_make_credentials(_http_sspi_t
*sspi
, const LPWSTR containerName
, const char *common_name
, _http_mode_t mode
, int years
);
64 static int http_sspi_server(http_t
*http
, const char *hostname
);
65 static void http_sspi_set_allows_any_root(_http_sspi_t
*sspi
, BOOL allow
);
66 static void http_sspi_set_allows_expired_certs(_http_sspi_t
*sspi
, BOOL allow
);
67 static const char *http_sspi_strerror(char *buffer
, size_t bufsize
, DWORD code
);
68 static DWORD
http_sspi_verify(PCCERT_CONTEXT cert
, const char *common_name
, DWORD dwCertFlags
);
72 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
74 * @since CUPS 2.0/OS 10.10@
77 int /* O - 1 on success, 0 on failure */
78 cupsMakeServerCredentials(
79 const char *path
, /* I - Keychain path or @code NULL@ for default */
80 const char *common_name
, /* I - Common name */
81 int num_alt_names
, /* I - Number of subject alternate names */
82 const char **alt_names
, /* I - Subject Alternate Names */
83 time_t expiration_date
) /* I - Expiration date */
85 _http_sspi_t
*sspi
; /* SSPI data */
86 int ret
; /* Return value */
89 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
));
95 sspi
= http_sspi_alloc();
96 ret
= http_sspi_make_credentials(sspi
, L
"ServerContainer", common_name
, _HTTP_MODE_SERVER
, (int)((expiration_date
- time(NULL
) + 86399) / 86400 / 365));
105 * 'cupsSetServerCredentials()' - Set the default server credentials.
107 * Note: The server credentials are used by all threads in the running process.
108 * This function is threadsafe.
110 * @since CUPS 2.0/OS 10.10@
113 int /* O - 1 on success, 0 on failure */
114 cupsSetServerCredentials(
115 const char *path
, /* I - Keychain path or @code NULL@ for default */
116 const char *common_name
, /* I - Default common name for server */
117 int auto_create
) /* I - 1 = automatically create self-signed certificates */
119 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path
, common_name
, auto_create
));
130 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
131 * an encrypted connection.
133 * @since CUPS 1.5/macOS 10.7@
136 int /* O - Status of call (0 = success) */
138 http_t
*http
, /* I - Connection to server */
139 cups_array_t
**credentials
) /* O - Array of credentials */
141 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http
, credentials
));
143 if (!http
|| !http
->tls
|| !http
->tls
->remoteCert
|| !credentials
)
151 *credentials
= cupsArrayNew(NULL
, NULL
);
152 httpAddCredential(*credentials
, http
->tls
->remoteCert
->pbCertEncoded
, http
->tls
->remoteCert
->cbCertEncoded
);
159 * '_httpCreateCredentials()' - Create credentials in the internal format.
162 http_tls_credentials_t
/* O - Internal credentials */
163 _httpCreateCredentials(
164 cups_array_t
*credentials
) /* I - Array of credentials */
166 return (http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
)));
171 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
173 * @since CUPS 2.0/OS 10.10@
176 int /* O - 1 if valid, 0 otherwise */
177 httpCredentialsAreValidForName(
178 cups_array_t
*credentials
, /* I - Credentials */
179 const char *common_name
) /* I - Name to check */
181 int valid
= 1; /* Valid name? */
182 PCCERT_CONTEXT cert
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
184 char cert_name
[1024]; /* Name from certificate */
189 if (CertNameToStr(X509_ASN_ENCODING
, &(cert
->pCertInfo
->Subject
), CERT_SIMPLE_NAME_STR
, cert_name
, sizeof(cert_name
)))
192 * Extract common name at end...
195 char *ptr
= strrchr(cert_name
, ',');
197 _cups_strcpy(cert_name
, ptr
+ 2);
200 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
202 CertFreeCertificateContext(cert
);
205 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
208 * Compare the common names...
211 if (_cups_strcasecmp(common_name
, cert_name
))
214 * Not an exact match for the common name, check for wildcard certs...
217 const char *domain
= strchr(common_name
, '.');
218 /* Domain in common name */
220 if (strncmp(cert_name
, "*.", 2) || !domain
|| _cups_strcasecmp(domain
, cert_name
+ 1))
223 * Not a wildcard match.
226 /* TODO: Check subject alternate names */
236 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
238 * @since CUPS 2.0/OS 10.10@
241 http_trust_t
/* O - Level of trust */
242 httpCredentialsGetTrust(
243 cups_array_t
*credentials
, /* I - Credentials */
244 const char *common_name
) /* I - Common name for trust lookup */
246 http_trust_t trust
= HTTP_TRUST_OK
; /* Level of trust */
247 PCCERT_CONTEXT cert
= NULL
; /* Certificate to validate */
248 DWORD certFlags
= 0; /* Cert verification flags */
249 _cups_globals_t
*cg
= _cupsGlobals(); /* Per-thread global data */
253 return (HTTP_TRUST_UNKNOWN
);
255 cert
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
257 return (HTTP_TRUST_UNKNOWN
);
259 if (cg
->any_root
< 0)
263 certFlags
|= SECURITY_FLAG_IGNORE_UNKNOWN_CA
;
265 if (cg
->expired_certs
)
266 certFlags
|= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
;
268 if (!cg
->validate_certs
)
269 certFlags
|= SECURITY_FLAG_IGNORE_CERT_CN_INVALID
;
271 if (http_sspi_verify(cert
, common_name
, certFlags
) != SEC_E_OK
)
272 trust
= HTTP_TRUST_INVALID
;
274 CertFreeCertificateContext(cert
);
281 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
283 * @since CUPS 2.0/OS 10.10@
286 time_t /* O - Expiration date of credentials */
287 httpCredentialsGetExpiration(
288 cups_array_t
*credentials
) /* I - Credentials */
290 time_t expiration_date
= 0; /* Expiration data of credentials */
291 PCCERT_CONTEXT cert
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
296 SYSTEMTIME systime
; /* System time */
297 struct tm tm
; /* UNIX date/time */
299 FileTimeToSystemTime(&(cert
->pCertInfo
->NotAfter
), &systime
);
301 tm
.tm_year
= systime
.wYear
- 1900;
302 tm
.tm_mon
= systime
.wMonth
- 1;
303 tm
.tm_mday
= systime
.wDay
;
304 tm
.tm_hour
= systime
.wHour
;
305 tm
.tm_min
= systime
.wMinute
;
306 tm
.tm_sec
= systime
.wSecond
;
308 expiration_date
= mktime(&tm
);
310 CertFreeCertificateContext(cert
);
313 return (expiration_date
);
318 * 'httpCredentialsString()' - Return a string representing the credentials.
320 * @since CUPS 2.0/OS 10.10@
323 size_t /* O - Total size of credentials string */
324 httpCredentialsString(
325 cups_array_t
*credentials
, /* I - Credentials */
326 char *buffer
, /* I - Buffer or @code NULL@ */
327 size_t bufsize
) /* I - Size of buffer */
329 http_credential_t
*first
= (http_credential_t
*)cupsArrayFirst(credentials
);
330 /* First certificate */
331 PCCERT_CONTEXT cert
; /* Certificate */
334 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT
")", credentials
, buffer
, CUPS_LLCAST bufsize
));
339 if (buffer
&& bufsize
> 0)
342 cert
= http_sspi_create_credential(first
);
346 char cert_name
[256]; /* Common name */
347 SYSTEMTIME systime
; /* System time */
348 struct tm tm
; /* UNIX date/time */
349 time_t expiration
; /* Expiration date of cert */
350 unsigned char md5_digest
[16]; /* MD5 result */
352 FileTimeToSystemTime(&(cert
->pCertInfo
->NotAfter
), &systime
);
354 tm
.tm_year
= systime
.wYear
- 1900;
355 tm
.tm_mon
= systime
.wMonth
- 1;
356 tm
.tm_mday
= systime
.wDay
;
357 tm
.tm_hour
= systime
.wHour
;
358 tm
.tm_min
= systime
.wMinute
;
359 tm
.tm_sec
= systime
.wSecond
;
361 expiration
= mktime(&tm
);
363 if (CertNameToStr(X509_ASN_ENCODING
, &(cert
->pCertInfo
->Subject
), CERT_SIMPLE_NAME_STR
, cert_name
, sizeof(cert_name
)))
366 * Extract common name at end...
369 char *ptr
= strrchr(cert_name
, ',');
371 _cups_strcpy(cert_name
, ptr
+ 2);
374 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
376 cupsHashData("md5", first
->data
, first
->datalen
, md5_digest
, sizeof(md5_digest
));
378 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]);
380 CertFreeCertificateContext(cert
);
383 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
385 return (strlen(buffer
));
390 * '_httpFreeCredentials()' - Free internal credentials.
394 _httpFreeCredentials(
395 http_tls_credentials_t credentials
) /* I - Internal credentials */
400 CertFreeCertificateContext(credentials
);
405 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
407 * @since CUPS 2.0/OS 10.10@
410 int /* O - 0 on success, -1 on error */
412 const char *path
, /* I - Keychain path or @code NULL@ for default */
413 cups_array_t
**credentials
, /* IO - Credentials */
414 const char *common_name
) /* I - Common name for credentials */
416 HCERTSTORE store
= NULL
; /* Certificate store */
417 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
418 DWORD dwSize
= 0; /* 32 bit size */
419 PBYTE p
= NULL
; /* Temporary storage */
420 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
421 /* Handle to a CSP */
422 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
424 char error
[1024]; /* Error message buffer */
428 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
438 DEBUG_puts("1httpLoadCredentials: NULL credentials pointer, returning -1.");
444 DEBUG_puts("1httpLoadCredentials: Bad common name, returning -1.");
448 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
450 if (GetLastError() == NTE_EXISTS
)
452 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
454 DEBUG_printf(("1httpLoadCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
460 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");
464 DEBUG_printf(("1httpLoadCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
470 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
472 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
476 p
= (PBYTE
)malloc(dwSize
);
480 DEBUG_printf(("1httpLoadCredentials: malloc failed for %d bytes.", dwSize
));
484 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
486 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
493 storedContext
= CertFindCertificateInStore(store
, X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, 0, CERT_FIND_SUBJECT_NAME
, &sib
, NULL
);
497 DEBUG_printf(("1httpLoadCredentials: Unable to find credentials for \"%s\".", common_name
));
501 *credentials
= cupsArrayNew(NULL
, NULL
);
502 httpAddCredential(*credentials
, storedContext
->pbCertEncoded
, storedContext
->cbCertEncoded
);
511 CertFreeCertificateContext(storedContext
);
517 CertCloseStore(store
, 0);
520 CryptReleaseContext(hProv
, 0);
522 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
524 return (*credentials
? 0 : -1);
529 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
531 * @since CUPS 2.0/OS 10.10@
534 int /* O - -1 on error, 0 on success */
536 const char *path
, /* I - Keychain path or @code NULL@ for default */
537 cups_array_t
*credentials
, /* I - Credentials */
538 const char *common_name
) /* I - Common name for credentials */
540 HCERTSTORE store
= NULL
; /* Certificate store */
541 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
542 PCCERT_CONTEXT createdContext
= NULL
; /* Context created by us */
543 DWORD dwSize
= 0; /* 32 bit size */
544 PBYTE p
= NULL
; /* Temporary storage */
545 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
546 /* Handle to a CSP */
547 CRYPT_KEY_PROV_INFO ckp
; /* Handle to crypto key */
548 int ret
= -1; /* Return value */
550 char error
[1024]; /* Error message buffer */
554 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
560 DEBUG_puts("1httpSaveCredentials: Bad common name, returning -1.");
564 createdContext
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
567 DEBUG_puts("1httpSaveCredentials: Bad credentials, returning -1.");
571 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
573 if (GetLastError() == NTE_EXISTS
)
575 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
577 DEBUG_printf(("1httpSaveCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
583 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");
587 DEBUG_printf(("1httpSaveCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
593 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
595 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
599 p
= (PBYTE
)malloc(dwSize
);
603 DEBUG_printf(("1httpSaveCredentials: malloc failed for %d bytes.", dwSize
));
607 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
609 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
614 * Add the created context to the named store, and associate it with the named
618 if (!CertAddCertificateContextToStore(store
, createdContext
, CERT_STORE_ADD_REPLACE_EXISTING
, &storedContext
))
620 DEBUG_printf(("1httpSaveCredentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
624 ZeroMemory(&ckp
, sizeof(ckp
));
625 ckp
.pwszContainerName
= L
"RememberedContainer";
626 ckp
.pwszProvName
= MS_DEF_PROV_W
;
627 ckp
.dwProvType
= PROV_RSA_FULL
;
628 ckp
.dwFlags
= CRYPT_MACHINE_KEYSET
;
629 ckp
.dwKeySpec
= AT_KEYEXCHANGE
;
631 if (!CertSetCertificateContextProperty(storedContext
, CERT_KEY_PROV_INFO_PROP_ID
, 0, &ckp
))
633 DEBUG_printf(("1httpSaveCredentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
646 CertFreeCertificateContext(createdContext
);
649 CertFreeCertificateContext(storedContext
);
655 CertCloseStore(store
, 0);
658 CryptReleaseContext(hProv
, 0);
660 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
666 * '_httpTLSInitialize()' - Initialize the TLS stack.
670 _httpTLSInitialize(void)
679 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
682 size_t /* O - Bytes available */
683 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
686 return (http
->tls
->readBufferUsed
);
693 * '_httpTLSRead()' - Read from a SSL/TLS connection.
696 int /* O - Bytes read */
697 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
698 char *buf
, /* I - Buffer to store data */
699 int len
) /* I - Length of buffer */
701 int i
; /* Looping var */
702 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
703 SecBufferDesc message
; /* Array of SecBuffer struct */
704 SecBuffer buffers
[4] = { 0 }; /* Security package buffer */
705 int num
= 0; /* Return value */
706 PSecBuffer pDataBuffer
; /* Data buffer */
707 PSecBuffer pExtraBuffer
; /* Excess data buffer */
708 SECURITY_STATUS scRet
; /* SSPI status */
711 DEBUG_printf(("4_httpTLSRead(http=%p, buf=%p, len=%d)", http
, buf
, len
));
714 * If there are bytes that have already been decrypted and have not yet been
715 * read, return those...
718 if (sspi
->readBufferUsed
> 0)
720 int bytesToCopy
= min(sspi
->readBufferUsed
, len
);
721 /* Number of bytes to copy */
723 memcpy(buf
, sspi
->readBuffer
, bytesToCopy
);
724 sspi
->readBufferUsed
-= bytesToCopy
;
726 if (sspi
->readBufferUsed
> 0)
727 memmove(sspi
->readBuffer
, sspi
->readBuffer
+ bytesToCopy
, sspi
->readBufferUsed
);
729 DEBUG_printf(("5_httpTLSRead: Returning %d bytes previously decrypted.", bytesToCopy
));
731 return (bytesToCopy
);
735 * Initialize security buffer structs
738 message
.ulVersion
= SECBUFFER_VERSION
;
739 message
.cBuffers
= 4;
740 message
.pBuffers
= buffers
;
745 * If there is not enough space in the buffer, then increase its size...
748 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
750 BYTE
*temp
; /* New buffer */
752 if (sspi
->decryptBufferLength
>= 262144)
754 WSASetLastError(E_OUTOFMEMORY
);
755 DEBUG_puts("_httpTLSRead: Decryption buffer too large (>256k)");
759 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
761 DEBUG_printf(("_httpTLSRead: Unable to allocate %d byte decryption buffer.", sspi
->decryptBufferLength
+ 4096));
762 WSASetLastError(E_OUTOFMEMORY
);
766 sspi
->decryptBufferLength
+= 4096;
767 sspi
->decryptBuffer
= temp
;
769 DEBUG_printf(("_httpTLSRead: Resized decryption buffer to %d bytes.", sspi
->decryptBufferLength
));
772 buffers
[0].pvBuffer
= sspi
->decryptBuffer
;
773 buffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
774 buffers
[0].BufferType
= SECBUFFER_DATA
;
775 buffers
[1].BufferType
= SECBUFFER_EMPTY
;
776 buffers
[2].BufferType
= SECBUFFER_EMPTY
;
777 buffers
[3].BufferType
= SECBUFFER_EMPTY
;
779 DEBUG_printf(("5_httpTLSRead: decryptBufferUsed=%d", sspi
->decryptBufferUsed
));
781 scRet
= DecryptMessage(&sspi
->context
, &message
, 0, NULL
);
783 if (scRet
== SEC_E_INCOMPLETE_MESSAGE
)
785 num
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
788 DEBUG_printf(("5_httpTLSRead: recv failed: %d", WSAGetLastError()));
793 DEBUG_puts("5_httpTLSRead: Server disconnected.");
797 DEBUG_printf(("5_httpTLSRead: Read %d bytes into decryption buffer.", num
));
799 sspi
->decryptBufferUsed
+= num
;
802 while (scRet
== SEC_E_INCOMPLETE_MESSAGE
);
804 if (scRet
== SEC_I_CONTEXT_EXPIRED
)
806 DEBUG_puts("5_httpTLSRead: Context expired.");
807 WSASetLastError(WSAECONNRESET
);
810 else if (scRet
!= SEC_E_OK
)
812 DEBUG_printf(("5_httpTLSRead: DecryptMessage failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
813 WSASetLastError(WSASYSCALLFAILURE
);
818 * The decryption worked. Now, locate data buffer.
824 for (i
= 1; i
< 4; i
++)
826 if (buffers
[i
].BufferType
== SECBUFFER_DATA
)
827 pDataBuffer
= &buffers
[i
];
828 else if (!pExtraBuffer
&& (buffers
[i
].BufferType
== SECBUFFER_EXTRA
))
829 pExtraBuffer
= &buffers
[i
];
833 * If a data buffer is found, then copy the decrypted bytes to the passed-in
839 int bytesToCopy
= min((int)pDataBuffer
->cbBuffer
, len
);
840 /* Number of bytes to copy into buf */
841 int bytesToSave
= pDataBuffer
->cbBuffer
- bytesToCopy
;
842 /* Number of bytes to save in our read buffer */
845 memcpy(buf
, pDataBuffer
->pvBuffer
, bytesToCopy
);
848 * If there are more decrypted bytes than can be copied to the passed in
849 * buffer, then save them...
854 if ((sspi
->readBufferLength
- sspi
->readBufferUsed
) < bytesToSave
)
856 BYTE
*temp
; /* New buffer pointer */
858 if ((temp
= realloc(sspi
->readBuffer
, sspi
->readBufferUsed
+ bytesToSave
)) == NULL
)
860 DEBUG_printf(("_httpTLSRead: Unable to allocate %d bytes.", sspi
->readBufferUsed
+ bytesToSave
));
861 WSASetLastError(E_OUTOFMEMORY
);
865 sspi
->readBufferLength
= sspi
->readBufferUsed
+ bytesToSave
;
866 sspi
->readBuffer
= temp
;
869 memcpy(((BYTE
*)sspi
->readBuffer
) + sspi
->readBufferUsed
, ((BYTE
*)pDataBuffer
->pvBuffer
) + bytesToCopy
, bytesToSave
);
871 sspi
->readBufferUsed
+= bytesToSave
;
878 DEBUG_puts("_httpTLSRead: Unable to find data buffer.");
879 WSASetLastError(WSASYSCALLFAILURE
);
884 * If the decryption process left extra bytes, then save those back in
885 * decryptBuffer. They will be processed the next time through the loop.
890 memmove(sspi
->decryptBuffer
, pExtraBuffer
->pvBuffer
, pExtraBuffer
->cbBuffer
);
891 sspi
->decryptBufferUsed
= pExtraBuffer
->cbBuffer
;
895 sspi
->decryptBufferUsed
= 0;
903 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
907 _httpTLSSetOptions(int options
) /* I - Options */
909 if (!(options
& _HTTP_TLS_SET_DEFAULT
) || tls_options
< 0)
911 tls_options
= options
;
912 tls_min_version
= min_version
;
913 tls_max_version
= max_version
;
919 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
922 int /* O - 0 on success, -1 on failure */
923 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
925 char hostname
[256], /* Hostname */
926 *hostptr
; /* Pointer into hostname */
929 DEBUG_printf(("3_httpTLSStart(http=%p)", http
));
933 DEBUG_puts("4_httpTLSStart: Setting defaults.");
935 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
938 if ((http
->tls
= http_sspi_alloc()) == NULL
)
941 if (http
->mode
== _HTTP_MODE_CLIENT
)
944 * Client: determine hostname...
947 if (httpAddrLocalhost(http
->hostaddr
))
949 strlcpy(hostname
, "localhost", sizeof(hostname
));
954 * Otherwise make sure the hostname we have does not end in a trailing dot.
957 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
958 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
963 return (http_sspi_client(http
, hostname
));
968 * Server: determine hostname to use...
971 if (http
->fields
[HTTP_FIELD_HOST
][0])
974 * Use hostname for TLS upgrade...
977 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
982 * Resolve hostname from connection address...
985 http_addr_t addr
; /* Connection address */
986 socklen_t addrlen
; /* Length of address */
988 addrlen
= sizeof(addr
);
989 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
991 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
994 else if (httpAddrLocalhost(&addr
))
998 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
999 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1003 return (http_sspi_server(http
, hostname
));
1009 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1013 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1015 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1018 if (sspi
->contextInitialized
&& http
->fd
>= 0)
1020 SecBufferDesc message
; /* Array of SecBuffer struct */
1021 SecBuffer buffers
[1] = { 0 };
1022 /* Security package buffer */
1023 DWORD dwType
; /* Type */
1024 DWORD status
; /* Status */
1027 * Notify schannel that we are about to close the connection.
1030 dwType
= SCHANNEL_SHUTDOWN
;
1032 buffers
[0].pvBuffer
= &dwType
;
1033 buffers
[0].BufferType
= SECBUFFER_TOKEN
;
1034 buffers
[0].cbBuffer
= sizeof(dwType
);
1036 message
.cBuffers
= 1;
1037 message
.pBuffers
= buffers
;
1038 message
.ulVersion
= SECBUFFER_VERSION
;
1040 status
= ApplyControlToken(&sspi
->context
, &message
);
1042 if (SUCCEEDED(status
))
1044 PBYTE pbMessage
; /* Message buffer */
1045 DWORD cbMessage
; /* Message buffer count */
1046 DWORD cbData
; /* Data count */
1047 DWORD dwSSPIFlags
; /* SSL attributes we requested */
1048 DWORD dwSSPIOutFlags
; /* SSL attributes we received */
1049 TimeStamp tsExpiry
; /* Time stamp */
1051 dwSSPIFlags
= ASC_REQ_SEQUENCE_DETECT
|
1052 ASC_REQ_REPLAY_DETECT
|
1053 ASC_REQ_CONFIDENTIALITY
|
1054 ASC_REQ_EXTENDED_ERROR
|
1055 ASC_REQ_ALLOCATE_MEMORY
|
1058 buffers
[0].pvBuffer
= NULL
;
1059 buffers
[0].BufferType
= SECBUFFER_TOKEN
;
1060 buffers
[0].cbBuffer
= 0;
1062 message
.cBuffers
= 1;
1063 message
.pBuffers
= buffers
;
1064 message
.ulVersion
= SECBUFFER_VERSION
;
1066 status
= AcceptSecurityContext(&sspi
->creds
, &sspi
->context
, NULL
,
1067 dwSSPIFlags
, SECURITY_NATIVE_DREP
, NULL
,
1068 &message
, &dwSSPIOutFlags
, &tsExpiry
);
1070 if (SUCCEEDED(status
))
1072 pbMessage
= buffers
[0].pvBuffer
;
1073 cbMessage
= buffers
[0].cbBuffer
;
1076 * Send the close notify message to the client.
1079 if (pbMessage
&& cbMessage
)
1081 cbData
= send(http
->fd
, pbMessage
, cbMessage
, 0);
1082 if ((cbData
== SOCKET_ERROR
) || (cbData
== 0))
1084 status
= WSAGetLastError();
1085 DEBUG_printf(("_httpTLSStop: sending close notify failed: %d", status
));
1089 FreeContextBuffer(pbMessage
);
1095 DEBUG_printf(("_httpTLSStop: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), status
)));
1100 DEBUG_printf(("_httpTLSStop: ApplyControlToken failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), status
)));
1104 http_sspi_free(sspi
);
1111 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1114 int /* O - Bytes written */
1115 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1116 const char *buf
, /* I - Buffer holding data */
1117 int len
) /* I - Length of buffer */
1119 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1120 SecBufferDesc message
; /* Array of SecBuffer struct */
1121 SecBuffer buffers
[4] = { 0 }; /* Security package buffer */
1122 int bufferLen
; /* Buffer length */
1123 int bytesLeft
; /* Bytes left to write */
1124 const char *bufptr
; /* Pointer into buffer */
1125 int num
= 0; /* Return value */
1128 bufferLen
= sspi
->streamSizes
.cbMaximumMessage
+ sspi
->streamSizes
.cbHeader
+ sspi
->streamSizes
.cbTrailer
;
1130 if (bufferLen
> sspi
->writeBufferLength
)
1132 BYTE
*temp
; /* New buffer pointer */
1134 if ((temp
= (BYTE
*)realloc(sspi
->writeBuffer
, bufferLen
)) == NULL
)
1136 DEBUG_printf(("_httpTLSWrite: Unable to allocate buffer of %d bytes.", bufferLen
));
1137 WSASetLastError(E_OUTOFMEMORY
);
1141 sspi
->writeBuffer
= temp
;
1142 sspi
->writeBufferLength
= bufferLen
;
1150 int chunk
= min((int)sspi
->streamSizes
.cbMaximumMessage
, bytesLeft
);
1151 /* Size of data to write */
1152 SECURITY_STATUS scRet
; /* SSPI status */
1155 * Copy user data into the buffer, starting just past the header...
1158 memcpy(sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
, bufptr
, chunk
);
1161 * Setup the SSPI buffers
1164 message
.ulVersion
= SECBUFFER_VERSION
;
1165 message
.cBuffers
= 4;
1166 message
.pBuffers
= buffers
;
1168 buffers
[0].pvBuffer
= sspi
->writeBuffer
;
1169 buffers
[0].cbBuffer
= sspi
->streamSizes
.cbHeader
;
1170 buffers
[0].BufferType
= SECBUFFER_STREAM_HEADER
;
1171 buffers
[1].pvBuffer
= sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
;
1172 buffers
[1].cbBuffer
= (unsigned long) chunk
;
1173 buffers
[1].BufferType
= SECBUFFER_DATA
;
1174 buffers
[2].pvBuffer
= sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
+ chunk
;
1175 buffers
[2].cbBuffer
= sspi
->streamSizes
.cbTrailer
;
1176 buffers
[2].BufferType
= SECBUFFER_STREAM_TRAILER
;
1177 buffers
[3].BufferType
= SECBUFFER_EMPTY
;
1183 scRet
= EncryptMessage(&sspi
->context
, 0, &message
, 0);
1187 DEBUG_printf(("_httpTLSWrite: EncryptMessage failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1188 WSASetLastError(WSASYSCALLFAILURE
);
1193 * Send the data. Remember the size of the total data to send is the size
1194 * of the header, the size of the data the caller passed in and the size
1198 num
= send(http
->fd
, sspi
->writeBuffer
, buffers
[0].cbBuffer
+ buffers
[1].cbBuffer
+ buffers
[2].cbBuffer
, 0);
1202 DEBUG_printf(("_httpTLSWrite: send failed: %ld", WSAGetLastError()));
1216 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
1219 static int /* O - 0 on success, -1 on failure */
1220 http_setup_ssl(http_t
*http
) /* I - Connection to server */
1222 char hostname
[256], /* Hostname */
1223 *hostptr
; /* Pointer into hostname */
1225 TCHAR username
[256]; /* Username returned from GetUserName() */
1226 TCHAR commonName
[256];/* Common name for certificate */
1227 DWORD dwSize
; /* 32 bit size */
1230 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
1233 * Get the hostname to use for SSL...
1236 if (httpAddrLocalhost(http
->hostaddr
))
1238 strlcpy(hostname
, "localhost", sizeof(hostname
));
1243 * Otherwise make sure the hostname we have does not end in a trailing dot.
1246 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1247 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1252 http
->tls
= http_sspi_alloc();
1256 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1260 dwSize
= sizeof(username
) / sizeof(TCHAR
);
1261 GetUserName(username
, &dwSize
);
1262 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
1263 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
1265 if (!_sspiGetCredentials(http
->tls
, L
"ClientContainer",
1268 _sspiFree(http
->tls
);
1272 http
->status
= HTTP_STATUS_ERROR
;
1274 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
1275 _("Unable to establish a secure connection to host."), 1);
1280 _sspiSetAllowsAnyRoot(http
->tls
, TRUE
);
1281 _sspiSetAllowsExpiredCerts(http
->tls
, TRUE
);
1283 if (!_sspiConnect(http
->tls
, hostname
))
1285 _sspiFree(http
->tls
);
1289 http
->status
= HTTP_STATUS_ERROR
;
1291 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
1292 _("Unable to establish a secure connection to host."), 1);
1303 * 'http_sspi_alloc()' - Allocate SSPI object.
1306 static _http_sspi_t
* /* O - New SSPI/SSL object */
1307 http_sspi_alloc(void)
1309 return ((_http_sspi_t
*)calloc(sizeof(_http_sspi_t
), 1));
1314 * 'http_sspi_client()' - Negotiate a TLS connection as a client.
1317 static int /* O - 0 on success, -1 on failure */
1318 http_sspi_client(http_t
*http
, /* I - Client connection */
1319 const char *hostname
) /* I - Server hostname */
1321 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1322 DWORD dwSize
; /* Size for buffer */
1323 DWORD dwSSPIFlags
; /* SSL connection attributes we want */
1324 DWORD dwSSPIOutFlags
; /* SSL connection attributes we got */
1325 TimeStamp tsExpiry
; /* Time stamp */
1326 SECURITY_STATUS scRet
; /* Status */
1327 int cbData
; /* Data count */
1328 SecBufferDesc inBuffer
; /* Array of SecBuffer structs */
1329 SecBuffer inBuffers
[2]; /* Security package buffer */
1330 SecBufferDesc outBuffer
; /* Array of SecBuffer structs */
1331 SecBuffer outBuffers
[1]; /* Security package buffer */
1332 int ret
= 0; /* Return value */
1333 char username
[1024], /* Current username */
1334 common_name
[1024]; /* CN=username */
1337 DEBUG_printf(("4http_sspi_client(http=%p, hostname=\"%s\")", http
, hostname
));
1339 dwSSPIFlags
= ISC_REQ_SEQUENCE_DETECT
|
1340 ISC_REQ_REPLAY_DETECT
|
1341 ISC_REQ_CONFIDENTIALITY
|
1342 ISC_RET_EXTENDED_ERROR
|
1343 ISC_REQ_ALLOCATE_MEMORY
|
1347 * Lookup the client certificate...
1350 dwSize
= sizeof(username
);
1351 GetUserName(username
, &dwSize
);
1352 snprintf(common_name
, sizeof(common_name
), "CN=%s", username
);
1354 if (!http_sspi_find_credentials(http
, L
"ClientContainer", common_name
))
1355 if (!http_sspi_make_credentials(http
->tls
, L
"ClientContainer", common_name
, _HTTP_MODE_CLIENT
, 10))
1357 DEBUG_puts("5http_sspi_client: Unable to get client credentials.");
1362 * Initiate a ClientHello message and generate a token.
1365 outBuffers
[0].pvBuffer
= NULL
;
1366 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1367 outBuffers
[0].cbBuffer
= 0;
1369 outBuffer
.cBuffers
= 1;
1370 outBuffer
.pBuffers
= outBuffers
;
1371 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
1373 scRet
= InitializeSecurityContext(&sspi
->creds
, NULL
, TEXT(""), dwSSPIFlags
, 0, SECURITY_NATIVE_DREP
, NULL
, 0, &sspi
->context
, &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
1375 if (scRet
!= SEC_I_CONTINUE_NEEDED
)
1377 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(1) failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1382 * Send response to server if there is one.
1385 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
1387 if ((cbData
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0)) <= 0)
1389 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1390 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1391 DeleteSecurityContext(&sspi
->context
);
1395 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData
));
1397 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1398 outBuffers
[0].pvBuffer
= NULL
;
1401 dwSSPIFlags
= ISC_REQ_MANUAL_CRED_VALIDATION
|
1402 ISC_REQ_SEQUENCE_DETECT
|
1403 ISC_REQ_REPLAY_DETECT
|
1404 ISC_REQ_CONFIDENTIALITY
|
1405 ISC_RET_EXTENDED_ERROR
|
1406 ISC_REQ_ALLOCATE_MEMORY
|
1409 sspi
->decryptBufferUsed
= 0;
1412 * Loop until the handshake is finished or an error occurs.
1415 scRet
= SEC_I_CONTINUE_NEEDED
;
1417 while(scRet
== SEC_I_CONTINUE_NEEDED
||
1418 scRet
== SEC_E_INCOMPLETE_MESSAGE
||
1419 scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
1421 if (sspi
->decryptBufferUsed
== 0 || scRet
== SEC_E_INCOMPLETE_MESSAGE
)
1423 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
1425 BYTE
*temp
; /* New buffer */
1427 if (sspi
->decryptBufferLength
>= 262144)
1429 WSASetLastError(E_OUTOFMEMORY
);
1430 DEBUG_puts("5http_sspi_client: Decryption buffer too large (>256k)");
1434 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
1436 DEBUG_printf(("5http_sspi_client: Unable to allocate %d byte buffer.", sspi
->decryptBufferLength
+ 4096));
1437 WSASetLastError(E_OUTOFMEMORY
);
1441 sspi
->decryptBufferLength
+= 4096;
1442 sspi
->decryptBuffer
= temp
;
1445 cbData
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
1449 DEBUG_printf(("5http_sspi_client: recv failed: %d", WSAGetLastError()));
1452 else if (cbData
== 0)
1454 DEBUG_printf(("5http_sspi_client: Server unexpectedly disconnected."));
1458 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data received", cbData
));
1460 sspi
->decryptBufferUsed
+= cbData
;
1464 * Set up the input buffers. Buffer 0 is used to pass in data received from
1465 * the server. Schannel will consume some or all of this. Leftover data
1466 * (if any) will be placed in buffer 1 and given a buffer type of
1470 inBuffers
[0].pvBuffer
= sspi
->decryptBuffer
;
1471 inBuffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
1472 inBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1474 inBuffers
[1].pvBuffer
= NULL
;
1475 inBuffers
[1].cbBuffer
= 0;
1476 inBuffers
[1].BufferType
= SECBUFFER_EMPTY
;
1478 inBuffer
.cBuffers
= 2;
1479 inBuffer
.pBuffers
= inBuffers
;
1480 inBuffer
.ulVersion
= SECBUFFER_VERSION
;
1483 * Set up the output buffers. These are initialized to NULL so as to make it
1484 * less likely we'll attempt to free random garbage later.
1487 outBuffers
[0].pvBuffer
= NULL
;
1488 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1489 outBuffers
[0].cbBuffer
= 0;
1491 outBuffer
.cBuffers
= 1;
1492 outBuffer
.pBuffers
= outBuffers
;
1493 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
1496 * Call InitializeSecurityContext.
1499 scRet
= InitializeSecurityContext(&sspi
->creds
, &sspi
->context
, NULL
, dwSSPIFlags
, 0, SECURITY_NATIVE_DREP
, &inBuffer
, 0, NULL
, &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
1502 * If InitializeSecurityContext was successful (or if the error was one of
1503 * the special extended ones), send the contents of the output buffer to the
1507 if (scRet
== SEC_E_OK
||
1508 scRet
== SEC_I_CONTINUE_NEEDED
||
1509 FAILED(scRet
) && (dwSSPIOutFlags
& ISC_RET_EXTENDED_ERROR
))
1511 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
1513 cbData
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0);
1517 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1518 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1519 DeleteSecurityContext(&sspi
->context
);
1523 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData
));
1526 * Free output buffer.
1529 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1530 outBuffers
[0].pvBuffer
= NULL
;
1535 * If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, then we
1536 * need to read more data from the server and try again.
1539 if (scRet
== SEC_E_INCOMPLETE_MESSAGE
)
1543 * If InitializeSecurityContext returned SEC_E_OK, then the handshake
1544 * completed successfully.
1547 if (scRet
== SEC_E_OK
)
1550 * If the "extra" buffer contains data, this is encrypted application
1551 * protocol layer stuff. It needs to be saved. The application layer will
1552 * later decrypt it with DecryptMessage.
1555 DEBUG_puts("5http_sspi_client: Handshake was successful.");
1557 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
1559 memmove(sspi
->decryptBuffer
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
, inBuffers
[1].cbBuffer
);
1561 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
1563 DEBUG_printf(("5http_sspi_client: %d bytes of app data was bundled with handshake data", sspi
->decryptBufferUsed
));
1566 sspi
->decryptBufferUsed
= 0;
1576 * Check for fatal error.
1581 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(2) failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1587 * If InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS,
1588 * then the server just requested client authentication.
1591 if (scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
1597 DEBUG_printf(("5http_sspi_client: server requested client credentials."));
1603 * Copy any leftover data from the "extra" buffer, and go around again.
1606 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
1608 memmove(sspi
->decryptBuffer
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
, inBuffers
[1].cbBuffer
);
1610 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
1614 sspi
->decryptBufferUsed
= 0;
1621 * Success! Get the server cert
1624 sspi
->contextInitialized
= TRUE
;
1626 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_REMOTE_CERT_CONTEXT
, (VOID
*)&(sspi
->remoteCert
));
1628 if (scRet
!= SEC_E_OK
)
1630 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_REMOTE_CERT_CONTEXT): %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1635 * Find out how big the header/trailer will be:
1638 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_STREAM_SIZES
, &sspi
->streamSizes
);
1640 if (scRet
!= SEC_E_OK
)
1642 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_STREAM_SIZES): %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1652 * 'http_sspi_create_credential()' - Create an SSPI certificate context.
1655 static PCCERT_CONTEXT
/* O - Certificate context */
1656 http_sspi_create_credential(
1657 http_credential_t
*cred
) /* I - Credential */
1660 return (CertCreateCertificateContext(X509_ASN_ENCODING
, cred
->data
, cred
->datalen
));
1667 * 'http_sspi_find_credentials()' - Retrieve a TLS certificate from the system store.
1670 static BOOL
/* O - 1 on success, 0 on failure */
1671 http_sspi_find_credentials(
1672 http_t
*http
, /* I - HTTP connection */
1673 const LPWSTR container
, /* I - Cert container name */
1674 const char *common_name
) /* I - Common name of certificate */
1676 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1677 HCERTSTORE store
= NULL
; /* Certificate store */
1678 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
1679 DWORD dwSize
= 0; /* 32 bit size */
1680 PBYTE p
= NULL
; /* Temporary storage */
1681 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
1682 /* Handle to a CSP */
1683 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
1684 SCHANNEL_CRED SchannelCred
; /* Schannel credential data */
1685 TimeStamp tsExpiry
; /* Time stamp */
1686 SECURITY_STATUS Status
; /* Status */
1687 BOOL ok
= TRUE
; /* Return value */
1690 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
1692 if (GetLastError() == NTE_EXISTS
)
1694 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
1696 DEBUG_printf(("5http_sspi_find_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1703 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");
1707 DEBUG_printf(("5http_sspi_find_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1714 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
1716 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1721 p
= (PBYTE
)malloc(dwSize
);
1725 DEBUG_printf(("5http_sspi_find_credentials: malloc failed for %d bytes.", dwSize
));
1730 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
1732 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1737 sib
.cbData
= dwSize
;
1740 storedContext
= CertFindCertificateInStore(store
, X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, 0, CERT_FIND_SUBJECT_NAME
, &sib
, NULL
);
1744 DEBUG_printf(("5http_sspi_find_credentials: Unable to find credentials for \"%s\".", common_name
));
1749 ZeroMemory(&SchannelCred
, sizeof(SchannelCred
));
1751 SchannelCred
.dwVersion
= SCHANNEL_CRED_VERSION
;
1752 SchannelCred
.cCreds
= 1;
1753 SchannelCred
.paCred
= &storedContext
;
1756 * Set supported protocols (can also be overriden in the registry...)
1759 #ifdef SP_PROT_TLS1_2_SERVER
1760 if (http
->mode
== _HTTP_MODE_SERVER
)
1762 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1763 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
;
1764 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1765 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
| SP_PROT_TLS1_0_SERVER
| SP_PROT_SSL3_SERVER
;
1767 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
| SP_PROT_TLS1_0_SERVER
;
1771 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1772 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
;
1773 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1774 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
| SP_PROT_TLS1_0_CLIENT
| SP_PROT_SSL3_CLIENT
;
1776 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
| SP_PROT_TLS1_0_CLIENT
;
1780 if (http
->mode
== _HTTP_MODE_SERVER
)
1782 if (tls_min_version
== _HTTP_TLS_SSL3
)
1783 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_SERVER
| SP_PROT_SSL3_SERVER
;
1785 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_SERVER
;
1789 if (tls_min_version
== _HTTP_TLS_SSL3
)
1790 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_CLIENT
| SP_PROT_SSL3_CLIENT
;
1792 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_CLIENT
;
1794 #endif /* SP_PROT_TLS1_2_SERVER */
1796 /* 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... */
1799 * Create an SSPI credential.
1802 Status
= AcquireCredentialsHandle(NULL
, UNISP_NAME
, http
->mode
== _HTTP_MODE_SERVER
? SECPKG_CRED_INBOUND
: SECPKG_CRED_OUTBOUND
, NULL
, &SchannelCred
, NULL
, NULL
, &sspi
->creds
, &tsExpiry
);
1803 if (Status
!= SEC_E_OK
)
1805 DEBUG_printf(("5http_sspi_find_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), Status
)));
1817 CertFreeCertificateContext(storedContext
);
1823 CertCloseStore(store
, 0);
1826 CryptReleaseContext(hProv
, 0);
1833 * 'http_sspi_free()' - Close a connection and free resources.
1837 http_sspi_free(_http_sspi_t
*sspi
) /* I - SSPI data */
1842 if (sspi
->contextInitialized
)
1843 DeleteSecurityContext(&sspi
->context
);
1845 if (sspi
->decryptBuffer
)
1846 free(sspi
->decryptBuffer
);
1848 if (sspi
->readBuffer
)
1849 free(sspi
->readBuffer
);
1851 if (sspi
->writeBuffer
)
1852 free(sspi
->writeBuffer
);
1854 if (sspi
->localCert
)
1855 CertFreeCertificateContext(sspi
->localCert
);
1857 if (sspi
->remoteCert
)
1858 CertFreeCertificateContext(sspi
->remoteCert
);
1865 * 'http_sspi_make_credentials()' - Create a TLS certificate in the system store.
1868 static BOOL
/* O - 1 on success, 0 on failure */
1869 http_sspi_make_credentials(
1870 _http_sspi_t
*sspi
, /* I - SSPI data */
1871 const LPWSTR container
, /* I - Cert container name */
1872 const char *common_name
, /* I - Common name of certificate */
1873 _http_mode_t mode
, /* I - Client or server? */
1874 int years
) /* I - Years until expiration */
1876 HCERTSTORE store
= NULL
; /* Certificate store */
1877 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
1878 PCCERT_CONTEXT createdContext
= NULL
; /* Context created by us */
1879 DWORD dwSize
= 0; /* 32 bit size */
1880 PBYTE p
= NULL
; /* Temporary storage */
1881 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
1882 /* Handle to a CSP */
1883 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
1884 SCHANNEL_CRED SchannelCred
; /* Schannel credential data */
1885 TimeStamp tsExpiry
; /* Time stamp */
1886 SECURITY_STATUS Status
; /* Status */
1887 HCRYPTKEY hKey
= (HCRYPTKEY
)NULL
; /* Handle to crypto key */
1888 CRYPT_KEY_PROV_INFO kpi
; /* Key container info */
1889 SYSTEMTIME et
; /* System time */
1890 CERT_EXTENSIONS exts
; /* Array of cert extensions */
1891 CRYPT_KEY_PROV_INFO ckp
; /* Handle to crypto key */
1892 BOOL ok
= TRUE
; /* Return value */
1895 DEBUG_printf(("4http_sspi_make_credentials(sspi=%p, container=%p, common_name=\"%s\", mode=%d, years=%d)", sspi
, container
, common_name
, mode
, years
));
1897 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
1899 if (GetLastError() == NTE_EXISTS
)
1901 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
1903 DEBUG_printf(("5http_sspi_make_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1910 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");
1914 DEBUG_printf(("5http_sspi_make_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1921 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
1923 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1928 p
= (PBYTE
)malloc(dwSize
);
1932 DEBUG_printf(("5http_sspi_make_credentials: malloc failed for %d bytes", dwSize
));
1937 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
1939 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1945 * Create a private key and self-signed certificate...
1948 if (!CryptGenKey(hProv
, AT_KEYEXCHANGE
, CRYPT_EXPORTABLE
, &hKey
))
1950 DEBUG_printf(("5http_sspi_make_credentials: CryptGenKey failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1955 ZeroMemory(&kpi
, sizeof(kpi
));
1956 kpi
.pwszContainerName
= (LPWSTR
)container
;
1957 kpi
.pwszProvName
= MS_DEF_PROV_W
;
1958 kpi
.dwProvType
= PROV_RSA_FULL
;
1959 kpi
.dwFlags
= CERT_SET_KEY_CONTEXT_PROP_ID
;
1960 kpi
.dwKeySpec
= AT_KEYEXCHANGE
;
1965 ZeroMemory(&exts
, sizeof(exts
));
1967 createdContext
= CertCreateSelfSignCertificate(hProv
, &sib
, 0, &kpi
, NULL
, NULL
, &et
, &exts
);
1969 if (!createdContext
)
1971 DEBUG_printf(("5http_sspi_make_credentials: CertCreateSelfSignCertificate failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1977 * Add the created context to the named store, and associate it with the named
1981 if (!CertAddCertificateContextToStore(store
, createdContext
, CERT_STORE_ADD_REPLACE_EXISTING
, &storedContext
))
1983 DEBUG_printf(("5http_sspi_make_credentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1988 ZeroMemory(&ckp
, sizeof(ckp
));
1989 ckp
.pwszContainerName
= (LPWSTR
) container
;
1990 ckp
.pwszProvName
= MS_DEF_PROV_W
;
1991 ckp
.dwProvType
= PROV_RSA_FULL
;
1992 ckp
.dwFlags
= CRYPT_MACHINE_KEYSET
;
1993 ckp
.dwKeySpec
= AT_KEYEXCHANGE
;
1995 if (!CertSetCertificateContextProperty(storedContext
, CERT_KEY_PROV_INFO_PROP_ID
, 0, &ckp
))
1997 DEBUG_printf(("5http_sspi_make_credentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
2003 * Get a handle to use the certificate...
2006 ZeroMemory(&SchannelCred
, sizeof(SchannelCred
));
2008 SchannelCred
.dwVersion
= SCHANNEL_CRED_VERSION
;
2009 SchannelCred
.cCreds
= 1;
2010 SchannelCred
.paCred
= &storedContext
;
2013 * SSPI doesn't seem to like it if grbitEnabledProtocols is set for a client.
2016 if (mode
== _HTTP_MODE_SERVER
)
2017 SchannelCred
.grbitEnabledProtocols
= SP_PROT_SSL3TLS1
;
2020 * Create an SSPI credential.
2023 Status
= AcquireCredentialsHandle(NULL
, UNISP_NAME
, mode
== _HTTP_MODE_SERVER
? SECPKG_CRED_INBOUND
: SECPKG_CRED_OUTBOUND
, NULL
, &SchannelCred
, NULL
, NULL
, &sspi
->creds
, &tsExpiry
);
2024 if (Status
!= SEC_E_OK
)
2026 DEBUG_printf(("5http_sspi_make_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), Status
)));
2038 CryptDestroyKey(hKey
);
2041 CertFreeCertificateContext(createdContext
);
2044 CertFreeCertificateContext(storedContext
);
2050 CertCloseStore(store
, 0);
2053 CryptReleaseContext(hProv
, 0);
2060 * 'http_sspi_server()' - Negotiate a TLS connection as a server.
2063 static int /* O - 0 on success, -1 on failure */
2064 http_sspi_server(http_t
*http
, /* I - HTTP connection */
2065 const char *hostname
) /* I - Hostname of server */
2067 _http_sspi_t
*sspi
= http
->tls
; /* I - SSPI data */
2068 char common_name
[512]; /* Common name for cert */
2069 DWORD dwSSPIFlags
; /* SSL connection attributes we want */
2070 DWORD dwSSPIOutFlags
; /* SSL connection attributes we got */
2071 TimeStamp tsExpiry
; /* Time stamp */
2072 SECURITY_STATUS scRet
; /* SSPI Status */
2073 SecBufferDesc inBuffer
; /* Array of SecBuffer structs */
2074 SecBuffer inBuffers
[2]; /* Security package buffer */
2075 SecBufferDesc outBuffer
; /* Array of SecBuffer structs */
2076 SecBuffer outBuffers
[1]; /* Security package buffer */
2077 int num
= 0; /* 32 bit status value */
2078 BOOL fInitContext
= TRUE
; /* Has the context been init'd? */
2079 int ret
= 0; /* Return value */
2082 DEBUG_printf(("4http_sspi_server(http=%p, hostname=\"%s\")", http
, hostname
));
2084 dwSSPIFlags
= ASC_REQ_SEQUENCE_DETECT
|
2085 ASC_REQ_REPLAY_DETECT
|
2086 ASC_REQ_CONFIDENTIALITY
|
2087 ASC_REQ_EXTENDED_ERROR
|
2088 ASC_REQ_ALLOCATE_MEMORY
|
2091 sspi
->decryptBufferUsed
= 0;
2094 * Lookup the server certificate...
2097 snprintf(common_name
, sizeof(common_name
), "CN=%s", hostname
);
2099 if (!http_sspi_find_credentials(http
, L
"ServerContainer", common_name
))
2100 if (!http_sspi_make_credentials(http
->tls
, L
"ServerContainer", common_name
, _HTTP_MODE_SERVER
, 10))
2102 DEBUG_puts("5http_sspi_server: Unable to get server credentials.");
2107 * Set OutBuffer for AcceptSecurityContext call
2110 outBuffer
.cBuffers
= 1;
2111 outBuffer
.pBuffers
= outBuffers
;
2112 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
2114 scRet
= SEC_I_CONTINUE_NEEDED
;
2116 while (scRet
== SEC_I_CONTINUE_NEEDED
||
2117 scRet
== SEC_E_INCOMPLETE_MESSAGE
||
2118 scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
2120 if (sspi
->decryptBufferUsed
== 0 || scRet
== SEC_E_INCOMPLETE_MESSAGE
)
2122 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
2124 BYTE
*temp
; /* New buffer */
2126 if (sspi
->decryptBufferLength
>= 262144)
2128 WSASetLastError(E_OUTOFMEMORY
);
2129 DEBUG_puts("5http_sspi_server: Decryption buffer too large (>256k)");
2133 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
2135 DEBUG_printf(("5http_sspi_server: Unable to allocate %d byte buffer.", sspi
->decryptBufferLength
+ 4096));
2136 WSASetLastError(E_OUTOFMEMORY
);
2140 sspi
->decryptBufferLength
+= 4096;
2141 sspi
->decryptBuffer
= temp
;
2146 num
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
2148 if (num
== -1 && WSAGetLastError() == WSAEWOULDBLOCK
)
2156 DEBUG_printf(("5http_sspi_server: recv failed: %d", WSAGetLastError()));
2161 DEBUG_puts("5http_sspi_server: client disconnected");
2165 DEBUG_printf(("5http_sspi_server: received %d (handshake) bytes from client.", num
));
2166 sspi
->decryptBufferUsed
+= num
;
2170 * InBuffers[1] is for getting extra data that SSPI/SCHANNEL doesn't process
2171 * on this run around the loop.
2174 inBuffers
[0].pvBuffer
= sspi
->decryptBuffer
;
2175 inBuffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
2176 inBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
2178 inBuffers
[1].pvBuffer
= NULL
;
2179 inBuffers
[1].cbBuffer
= 0;
2180 inBuffers
[1].BufferType
= SECBUFFER_EMPTY
;
2182 inBuffer
.cBuffers
= 2;
2183 inBuffer
.pBuffers
= inBuffers
;
2184 inBuffer
.ulVersion
= SECBUFFER_VERSION
;
2187 * Initialize these so if we fail, pvBuffer contains NULL, so we don't try to
2188 * free random garbage at the quit.
2191 outBuffers
[0].pvBuffer
= NULL
;
2192 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
2193 outBuffers
[0].cbBuffer
= 0;
2195 scRet
= AcceptSecurityContext(&sspi
->creds
, (fInitContext
?NULL
:&sspi
->context
), &inBuffer
, dwSSPIFlags
, SECURITY_NATIVE_DREP
, (fInitContext
?&sspi
->context
:NULL
), &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
2197 fInitContext
= FALSE
;
2199 if (scRet
== SEC_E_OK
||
2200 scRet
== SEC_I_CONTINUE_NEEDED
||
2201 (FAILED(scRet
) && ((dwSSPIOutFlags
& ISC_RET_EXTENDED_ERROR
) != 0)))
2203 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
2206 * Send response to server if there is one.
2209 num
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0);
2213 DEBUG_printf(("5http_sspi_server: handshake send failed: %d", WSAGetLastError()));
2217 DEBUG_printf(("5http_sspi_server: sent %d handshake bytes to client.", outBuffers
[0].cbBuffer
));
2219 FreeContextBuffer(outBuffers
[0].pvBuffer
);
2220 outBuffers
[0].pvBuffer
= NULL
;
2224 if (scRet
== SEC_E_OK
)
2227 * If there's extra data then save it for next time we go to decrypt.
2230 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
2232 memcpy(sspi
->decryptBuffer
, (LPBYTE
)(sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
), inBuffers
[1].cbBuffer
);
2233 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
2237 sspi
->decryptBufferUsed
= 0;
2241 else if (FAILED(scRet
) && scRet
!= SEC_E_INCOMPLETE_MESSAGE
)
2243 DEBUG_printf(("5http_sspi_server: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
2248 if (scRet
!= SEC_E_INCOMPLETE_MESSAGE
&&
2249 scRet
!= SEC_I_INCOMPLETE_CREDENTIALS
)
2251 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
2253 memcpy(sspi
->decryptBuffer
, (LPBYTE
)(sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
), inBuffers
[1].cbBuffer
);
2254 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
2258 sspi
->decryptBufferUsed
= 0;
2265 sspi
->contextInitialized
= TRUE
;
2268 * Find out how big the header will be:
2271 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_STREAM_SIZES
, &sspi
->streamSizes
);
2273 if (scRet
!= SEC_E_OK
)
2275 DEBUG_printf(("5http_sspi_server: QueryContextAttributes failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
2285 * 'http_sspi_strerror()' - Return a string for the specified error code.
2288 static const char * /* O - String for error */
2289 http_sspi_strerror(char *buffer
, /* I - Error message buffer */
2290 size_t bufsize
, /* I - Size of buffer */
2291 DWORD code
) /* I - Error code */
2293 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, code
, 0, buffer
, bufsize
, NULL
))
2296 * Strip trailing CR + LF...
2299 char *ptr
; /* Pointer into error message */
2301 for (ptr
= buffer
+ strlen(buffer
) - 1; ptr
>= buffer
; ptr
--)
2302 if (*ptr
== '\n' || *ptr
== '\r')
2308 snprintf(buffer
, bufsize
, "Unknown error %x", code
);
2315 * 'http_sspi_verify()' - Verify a certificate.
2318 static DWORD
/* O - Error code (0 == No error) */
2320 PCCERT_CONTEXT cert
, /* I - Server certificate */
2321 const char *common_name
, /* I - Common name */
2322 DWORD dwCertFlags
) /* I - Verification flags */
2324 HTTPSPolicyCallbackData httpsPolicy
; /* HTTPS Policy Struct */
2325 CERT_CHAIN_POLICY_PARA policyPara
; /* Cert chain policy parameters */
2326 CERT_CHAIN_POLICY_STATUS policyStatus
;/* Cert chain policy status */
2327 CERT_CHAIN_PARA chainPara
; /* Used for searching and matching criteria */
2328 PCCERT_CHAIN_CONTEXT chainContext
= NULL
;
2329 /* Certificate chain */
2330 PWSTR commonNameUnicode
= NULL
;
2331 /* Unicode common name */
2332 LPSTR rgszUsages
[] = { szOID_PKIX_KP_SERVER_AUTH
,
2333 szOID_SERVER_GATED_CRYPTO
,
2334 szOID_SGC_NETSCAPE
};
2335 /* How are we using this certificate? */
2336 DWORD cUsages
= sizeof(rgszUsages
) / sizeof(LPSTR
);
2337 /* Number of ites in rgszUsages */
2338 DWORD count
; /* 32 bit count variable */
2339 DWORD status
; /* Return value */
2341 char error
[1024]; /* Error message string */
2346 return (SEC_E_WRONG_PRINCIPAL
);
2349 * Convert common name to Unicode.
2352 if (!common_name
|| !*common_name
)
2353 return (SEC_E_WRONG_PRINCIPAL
);
2355 count
= MultiByteToWideChar(CP_ACP
, 0, common_name
, -1, NULL
, 0);
2356 commonNameUnicode
= LocalAlloc(LMEM_FIXED
, count
* sizeof(WCHAR
));
2357 if (!commonNameUnicode
)
2358 return (SEC_E_INSUFFICIENT_MEMORY
);
2360 if (!MultiByteToWideChar(CP_ACP
, 0, common_name
, -1, commonNameUnicode
, count
))
2362 LocalFree(commonNameUnicode
);
2363 return (SEC_E_WRONG_PRINCIPAL
);
2367 * Build certificate chain.
2370 ZeroMemory(&chainPara
, sizeof(chainPara
));
2372 chainPara
.cbSize
= sizeof(chainPara
);
2373 chainPara
.RequestedUsage
.dwType
= USAGE_MATCH_TYPE_OR
;
2374 chainPara
.RequestedUsage
.Usage
.cUsageIdentifier
= cUsages
;
2375 chainPara
.RequestedUsage
.Usage
.rgpszUsageIdentifier
= rgszUsages
;
2377 if (!CertGetCertificateChain(NULL
, cert
, NULL
, cert
->hCertStore
, &chainPara
, 0, NULL
, &chainContext
))
2379 status
= GetLastError();
2381 DEBUG_printf(("CertGetCertificateChain returned: %s", http_sspi_strerror(error
, sizeof(error
), status
)));
2383 LocalFree(commonNameUnicode
);
2388 * Validate certificate chain.
2391 ZeroMemory(&httpsPolicy
, sizeof(HTTPSPolicyCallbackData
));
2392 httpsPolicy
.cbStruct
= sizeof(HTTPSPolicyCallbackData
);
2393 httpsPolicy
.dwAuthType
= AUTHTYPE_SERVER
;
2394 httpsPolicy
.fdwChecks
= dwCertFlags
;
2395 httpsPolicy
.pwszServerName
= commonNameUnicode
;
2397 memset(&policyPara
, 0, sizeof(policyPara
));
2398 policyPara
.cbSize
= sizeof(policyPara
);
2399 policyPara
.pvExtraPolicyPara
= &httpsPolicy
;
2401 memset(&policyStatus
, 0, sizeof(policyStatus
));
2402 policyStatus
.cbSize
= sizeof(policyStatus
);
2404 if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL
, chainContext
, &policyPara
, &policyStatus
))
2406 status
= GetLastError();
2408 DEBUG_printf(("CertVerifyCertificateChainPolicy returned %s", http_sspi_strerror(error
, sizeof(error
), status
)));
2410 else if (policyStatus
.dwError
)
2411 status
= policyStatus
.dwError
;
2416 CertFreeCertificateChain(chainContext
);
2418 if (commonNameUnicode
)
2419 LocalFree(commonNameUnicode
);