4 * TLS support for CUPS on Windows using the Security Support Provider
7 * Copyright 2010-2015 by Apple Inc.
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
15 * This file is subject to the Apple OS-Developed Software exception.
18 /**** This file is included from tls.c ****/
21 * Include necessary headers...
24 #include "debug-private.h"
28 * Include necessary libraries...
31 #pragma comment(lib, "Crypt32.lib")
32 #pragma comment(lib, "Secur32.lib")
33 #pragma comment(lib, "Ws2_32.lib")
40 #ifndef SECURITY_FLAG_IGNORE_UNKNOWN_CA
41 # define SECURITY_FLAG_IGNORE_UNKNOWN_CA 0x00000100 /* Untrusted root */
42 #endif /* SECURITY_FLAG_IGNORE_UNKNOWN_CA */
44 #ifndef SECURITY_FLAG_IGNORE_CERT_CN_INVALID
45 # define SECURITY_FLAG_IGNORE_CERT_CN_INVALID 0x00001000 /* Common name does not match */
46 #endif /* !SECURITY_FLAG_IGNORE_CERT_CN_INVALID */
48 #ifndef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
49 # define SECURITY_FLAG_IGNORE_CERT_DATE_INVALID 0x00002000 /* Expired X509 Cert. */
50 #endif /* !SECURITY_FLAG_IGNORE_CERT_DATE_INVALID */
57 static int tls_options
= -1;/* Options for TLS connections */
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/OS X 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 _cups_md5_state_t md5_state
; /* MD5 state */
357 unsigned char md5_digest
[16]; /* MD5 result */
359 FileTimeToSystemTime(&(cert
->pCertInfo
->NotAfter
), &systime
);
361 tm
.tm_year
= systime
.wYear
- 1900;
362 tm
.tm_mon
= systime
.wMonth
- 1;
363 tm
.tm_mday
= systime
.wDay
;
364 tm
.tm_hour
= systime
.wHour
;
365 tm
.tm_min
= systime
.wMinute
;
366 tm
.tm_sec
= systime
.wSecond
;
368 expiration
= mktime(&tm
);
370 if (CertNameToStr(X509_ASN_ENCODING
, &(cert
->pCertInfo
->Subject
), CERT_SIMPLE_NAME_STR
, cert_name
, sizeof(cert_name
)))
373 * Extract common name at end...
376 char *ptr
= strrchr(cert_name
, ',');
378 _cups_strcpy(cert_name
, ptr
+ 2);
381 strlcpy(cert_name
, "unknown", sizeof(cert_name
));
383 _cupsMD5Init(&md5_state
);
384 _cupsMD5Append(&md5_state
, first
->data
, (int)first
->datalen
);
385 _cupsMD5Finish(&md5_state
, md5_digest
);
387 snprintf(buffer
, bufsize
, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", cert_name
, httpGetDateString(expiration
), md5_digest
[0], md5_digest
[1], md5_digest
[2], md5_digest
[3], md5_digest
[4], md5_digest
[5], md5_digest
[6], md5_digest
[7], md5_digest
[8], md5_digest
[9], md5_digest
[10], md5_digest
[11], md5_digest
[12], md5_digest
[13], md5_digest
[14], md5_digest
[15]);
389 CertFreeCertificateContext(cert
);
392 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer
));
394 return (strlen(buffer
));
399 * '_httpFreeCredentials()' - Free internal credentials.
403 _httpFreeCredentials(
404 http_tls_credentials_t credentials
) /* I - Internal credentials */
409 CertFreeCertificateContext(credentials
);
414 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
416 * @since CUPS 2.0/OS 10.10@
419 int /* O - 0 on success, -1 on error */
421 const char *path
, /* I - Keychain path or @code NULL@ for default */
422 cups_array_t
**credentials
, /* IO - Credentials */
423 const char *common_name
) /* I - Common name for credentials */
425 HCERTSTORE store
= NULL
; /* Certificate store */
426 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
427 DWORD dwSize
= 0; /* 32 bit size */
428 PBYTE p
= NULL
; /* Temporary storage */
429 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
430 /* Handle to a CSP */
431 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
433 char error
[1024]; /* Error message buffer */
437 DEBUG_printf(("httpLoadCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
447 DEBUG_puts("1httpLoadCredentials: NULL credentials pointer, returning -1.");
453 DEBUG_puts("1httpLoadCredentials: Bad common name, returning -1.");
457 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
459 if (GetLastError() == NTE_EXISTS
)
461 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
463 DEBUG_printf(("1httpLoadCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
469 store
= CertOpenStore(CERT_STORE_PROV_SYSTEM
, X509_ASN_ENCODING
|PKCS_7_ASN_ENCODING
, hProv
, CERT_SYSTEM_STORE_LOCAL_MACHINE
| CERT_STORE_NO_CRYPT_RELEASE_FLAG
| CERT_STORE_OPEN_EXISTING_FLAG
, L
"MY");
473 DEBUG_printf(("1httpLoadCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
479 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
481 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
485 p
= (PBYTE
)malloc(dwSize
);
489 DEBUG_printf(("1httpLoadCredentials: malloc failed for %d bytes.", dwSize
));
493 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
495 DEBUG_printf(("1httpLoadCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
502 storedContext
= CertFindCertificateInStore(store
, X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, 0, CERT_FIND_SUBJECT_NAME
, &sib
, NULL
);
506 DEBUG_printf(("1httpLoadCredentials: Unable to find credentials for \"%s\".", common_name
));
510 *credentials
= cupsArrayNew(NULL
, NULL
);
511 httpAddCredential(*credentials
, storedContext
->pbCertEncoded
, storedContext
->cbCertEncoded
);
520 CertFreeCertificateContext(storedContext
);
526 CertCloseStore(store
, 0);
529 CryptReleaseContext(hProv
, 0);
531 DEBUG_printf(("1httpLoadCredentials: Returning %d.", *credentials
? 0 : -1));
533 return (*credentials
? 0 : -1);
538 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
540 * @since CUPS 2.0/OS 10.10@
543 int /* O - -1 on error, 0 on success */
545 const char *path
, /* I - Keychain path or @code NULL@ for default */
546 cups_array_t
*credentials
, /* I - Credentials */
547 const char *common_name
) /* I - Common name for credentials */
549 HCERTSTORE store
= NULL
; /* Certificate store */
550 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
551 PCCERT_CONTEXT createdContext
= NULL
; /* Context created by us */
552 DWORD dwSize
= 0; /* 32 bit size */
553 PBYTE p
= NULL
; /* Temporary storage */
554 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
555 /* Handle to a CSP */
556 CRYPT_KEY_PROV_INFO ckp
; /* Handle to crypto key */
557 int ret
= -1; /* Return value */
559 char error
[1024]; /* Error message buffer */
563 DEBUG_printf(("httpSaveCredentials(path=\"%s\", credentials=%p, common_name=\"%s\")", path
, credentials
, common_name
));
569 DEBUG_puts("1httpSaveCredentials: Bad common name, returning -1.");
573 createdContext
= http_sspi_create_credential((http_credential_t
*)cupsArrayFirst(credentials
));
576 DEBUG_puts("1httpSaveCredentials: Bad credentials, returning -1.");
580 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
582 if (GetLastError() == NTE_EXISTS
)
584 if (!CryptAcquireContextW(&hProv
, L
"RememberedContainer", MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
586 DEBUG_printf(("1httpSaveCredentials: CryptAcquireContext failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
592 store
= CertOpenStore(CERT_STORE_PROV_SYSTEM
, X509_ASN_ENCODING
|PKCS_7_ASN_ENCODING
, hProv
, CERT_SYSTEM_STORE_LOCAL_MACHINE
| CERT_STORE_NO_CRYPT_RELEASE_FLAG
| CERT_STORE_OPEN_EXISTING_FLAG
, L
"MY");
596 DEBUG_printf(("1httpSaveCredentials: CertOpenSystemStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
602 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
604 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
608 p
= (PBYTE
)malloc(dwSize
);
612 DEBUG_printf(("1httpSaveCredentials: malloc failed for %d bytes.", dwSize
));
616 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
618 DEBUG_printf(("1httpSaveCredentials: CertStrToName failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
623 * Add the created context to the named store, and associate it with the named
627 if (!CertAddCertificateContextToStore(store
, createdContext
, CERT_STORE_ADD_REPLACE_EXISTING
, &storedContext
))
629 DEBUG_printf(("1httpSaveCredentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
633 ZeroMemory(&ckp
, sizeof(ckp
));
634 ckp
.pwszContainerName
= L
"RememberedContainer";
635 ckp
.pwszProvName
= MS_DEF_PROV_W
;
636 ckp
.dwProvType
= PROV_RSA_FULL
;
637 ckp
.dwFlags
= CRYPT_MACHINE_KEYSET
;
638 ckp
.dwKeySpec
= AT_KEYEXCHANGE
;
640 if (!CertSetCertificateContextProperty(storedContext
, CERT_KEY_PROV_INFO_PROP_ID
, 0, &ckp
))
642 DEBUG_printf(("1httpSaveCredentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(error
, sizeof(error
), GetLastError())));
655 CertFreeCertificateContext(createdContext
);
658 CertFreeCertificateContext(storedContext
);
664 CertCloseStore(store
, 0);
667 CryptReleaseContext(hProv
, 0);
669 DEBUG_printf(("1httpSaveCredentials: Returning %d.", ret
));
675 * '_httpTLSInitialize()' - Initialize the TLS stack.
679 _httpTLSInitialize(void)
688 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
691 size_t /* O - Bytes available */
692 _httpTLSPending(http_t
*http
) /* I - HTTP connection */
695 return (http
->tls
->readBufferUsed
);
702 * '_httpTLSRead()' - Read from a SSL/TLS connection.
705 int /* O - Bytes read */
706 _httpTLSRead(http_t
*http
, /* I - HTTP connection */
707 char *buf
, /* I - Buffer to store data */
708 int len
) /* I - Length of buffer */
710 int i
; /* Looping var */
711 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
712 SecBufferDesc message
; /* Array of SecBuffer struct */
713 SecBuffer buffers
[4] = { 0 }; /* Security package buffer */
714 int num
= 0; /* Return value */
715 PSecBuffer pDataBuffer
; /* Data buffer */
716 PSecBuffer pExtraBuffer
; /* Excess data buffer */
717 SECURITY_STATUS scRet
; /* SSPI status */
720 DEBUG_printf(("4_httpTLSRead(http=%p, buf=%p, len=%d)", http
, buf
, len
));
723 * If there are bytes that have already been decrypted and have not yet been
724 * read, return those...
727 if (sspi
->readBufferUsed
> 0)
729 int bytesToCopy
= min(sspi
->readBufferUsed
, len
);
730 /* Number of bytes to copy */
732 memcpy(buf
, sspi
->readBuffer
, bytesToCopy
);
733 sspi
->readBufferUsed
-= bytesToCopy
;
735 if (sspi
->readBufferUsed
> 0)
736 memmove(sspi
->readBuffer
, sspi
->readBuffer
+ bytesToCopy
, sspi
->readBufferUsed
);
738 DEBUG_printf(("5_httpTLSRead: Returning %d bytes previously decrypted.", bytesToCopy
));
740 return (bytesToCopy
);
744 * Initialize security buffer structs
747 message
.ulVersion
= SECBUFFER_VERSION
;
748 message
.cBuffers
= 4;
749 message
.pBuffers
= buffers
;
754 * If there is not enough space in the buffer, then increase its size...
757 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
759 BYTE
*temp
; /* New buffer */
761 if (sspi
->decryptBufferLength
>= 262144)
763 WSASetLastError(E_OUTOFMEMORY
);
764 DEBUG_puts("_httpTLSRead: Decryption buffer too large (>256k)");
768 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
770 DEBUG_printf(("_httpTLSRead: Unable to allocate %d byte decryption buffer.", sspi
->decryptBufferLength
+ 4096));
771 WSASetLastError(E_OUTOFMEMORY
);
775 sspi
->decryptBufferLength
+= 4096;
776 sspi
->decryptBuffer
= temp
;
778 DEBUG_printf(("_httpTLSRead: Resized decryption buffer to %d bytes.", sspi
->decryptBufferLength
));
781 buffers
[0].pvBuffer
= sspi
->decryptBuffer
;
782 buffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
783 buffers
[0].BufferType
= SECBUFFER_DATA
;
784 buffers
[1].BufferType
= SECBUFFER_EMPTY
;
785 buffers
[2].BufferType
= SECBUFFER_EMPTY
;
786 buffers
[3].BufferType
= SECBUFFER_EMPTY
;
788 DEBUG_printf(("5_httpTLSRead: decryptBufferUsed=%d", sspi
->decryptBufferUsed
));
790 scRet
= DecryptMessage(&sspi
->context
, &message
, 0, NULL
);
792 if (scRet
== SEC_E_INCOMPLETE_MESSAGE
)
794 num
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
797 DEBUG_printf(("5_httpTLSRead: recv failed: %d", WSAGetLastError()));
802 DEBUG_puts("5_httpTLSRead: Server disconnected.");
806 DEBUG_printf(("5_httpTLSRead: Read %d bytes into decryption buffer.", num
));
808 sspi
->decryptBufferUsed
+= num
;
811 while (scRet
== SEC_E_INCOMPLETE_MESSAGE
);
813 if (scRet
== SEC_I_CONTEXT_EXPIRED
)
815 DEBUG_puts("5_httpTLSRead: Context expired.");
816 WSASetLastError(WSAECONNRESET
);
819 else if (scRet
!= SEC_E_OK
)
821 DEBUG_printf(("5_httpTLSRead: DecryptMessage failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
822 WSASetLastError(WSASYSCALLFAILURE
);
827 * The decryption worked. Now, locate data buffer.
833 for (i
= 1; i
< 4; i
++)
835 if (buffers
[i
].BufferType
== SECBUFFER_DATA
)
836 pDataBuffer
= &buffers
[i
];
837 else if (!pExtraBuffer
&& (buffers
[i
].BufferType
== SECBUFFER_EXTRA
))
838 pExtraBuffer
= &buffers
[i
];
842 * If a data buffer is found, then copy the decrypted bytes to the passed-in
848 int bytesToCopy
= min((int)pDataBuffer
->cbBuffer
, len
);
849 /* Number of bytes to copy into buf */
850 int bytesToSave
= pDataBuffer
->cbBuffer
- bytesToCopy
;
851 /* Number of bytes to save in our read buffer */
854 memcpy(buf
, pDataBuffer
->pvBuffer
, bytesToCopy
);
857 * If there are more decrypted bytes than can be copied to the passed in
858 * buffer, then save them...
863 if ((sspi
->readBufferLength
- sspi
->readBufferUsed
) < bytesToSave
)
865 BYTE
*temp
; /* New buffer pointer */
867 if ((temp
= realloc(sspi
->readBuffer
, sspi
->readBufferUsed
+ bytesToSave
)) == NULL
)
869 DEBUG_printf(("_httpTLSRead: Unable to allocate %d bytes.", sspi
->readBufferUsed
+ bytesToSave
));
870 WSASetLastError(E_OUTOFMEMORY
);
874 sspi
->readBufferLength
= sspi
->readBufferUsed
+ bytesToSave
;
875 sspi
->readBuffer
= temp
;
878 memcpy(((BYTE
*)sspi
->readBuffer
) + sspi
->readBufferUsed
, ((BYTE
*)pDataBuffer
->pvBuffer
) + bytesToCopy
, bytesToSave
);
880 sspi
->readBufferUsed
+= bytesToSave
;
887 DEBUG_puts("_httpTLSRead: Unable to find data buffer.");
888 WSASetLastError(WSASYSCALLFAILURE
);
893 * If the decryption process left extra bytes, then save those back in
894 * decryptBuffer. They will be processed the next time through the loop.
899 memmove(sspi
->decryptBuffer
, pExtraBuffer
->pvBuffer
, pExtraBuffer
->cbBuffer
);
900 sspi
->decryptBufferUsed
= pExtraBuffer
->cbBuffer
;
904 sspi
->decryptBufferUsed
= 0;
912 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
916 _httpTLSSetOptions(int options
) /* I - Options */
918 tls_options
= options
;
923 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
926 int /* O - 0 on success, -1 on failure */
927 _httpTLSStart(http_t
*http
) /* I - HTTP connection */
929 char hostname
[256], /* Hostname */
930 *hostptr
; /* Pointer into hostname */
933 DEBUG_printf(("3_httpTLSStart(http=%p)", http
));
937 DEBUG_puts("4_httpTLSStart: Setting defaults.");
939 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options
));
942 if ((http
->tls
= http_sspi_alloc()) == NULL
)
945 if (http
->mode
== _HTTP_MODE_CLIENT
)
948 * Client: determine hostname...
951 if (httpAddrLocalhost(http
->hostaddr
))
953 strlcpy(hostname
, "localhost", sizeof(hostname
));
958 * Otherwise make sure the hostname we have does not end in a trailing dot.
961 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
962 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
967 return (http_sspi_client(http
, hostname
));
972 * Server: determine hostname to use...
975 if (http
->fields
[HTTP_FIELD_HOST
][0])
978 * Use hostname for TLS upgrade...
981 strlcpy(hostname
, http
->fields
[HTTP_FIELD_HOST
], sizeof(hostname
));
986 * Resolve hostname from connection address...
989 http_addr_t addr
; /* Connection address */
990 socklen_t addrlen
; /* Length of address */
992 addrlen
= sizeof(addr
);
993 if (getsockname(http
->fd
, (struct sockaddr
*)&addr
, &addrlen
))
995 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno
)));
998 else if (httpAddrLocalhost(&addr
))
1002 httpAddrLookup(&addr
, hostname
, sizeof(hostname
));
1003 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname
));
1007 return (http_sspi_server(http
, hostname
));
1013 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1017 _httpTLSStop(http_t
*http
) /* I - HTTP connection */
1019 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1022 if (sspi
->contextInitialized
&& http
->fd
>= 0)
1024 SecBufferDesc message
; /* Array of SecBuffer struct */
1025 SecBuffer buffers
[1] = { 0 };
1026 /* Security package buffer */
1027 DWORD dwType
; /* Type */
1028 DWORD status
; /* Status */
1031 * Notify schannel that we are about to close the connection.
1034 dwType
= SCHANNEL_SHUTDOWN
;
1036 buffers
[0].pvBuffer
= &dwType
;
1037 buffers
[0].BufferType
= SECBUFFER_TOKEN
;
1038 buffers
[0].cbBuffer
= sizeof(dwType
);
1040 message
.cBuffers
= 1;
1041 message
.pBuffers
= buffers
;
1042 message
.ulVersion
= SECBUFFER_VERSION
;
1044 status
= ApplyControlToken(&sspi
->context
, &message
);
1046 if (SUCCEEDED(status
))
1048 PBYTE pbMessage
; /* Message buffer */
1049 DWORD cbMessage
; /* Message buffer count */
1050 DWORD cbData
; /* Data count */
1051 DWORD dwSSPIFlags
; /* SSL attributes we requested */
1052 DWORD dwSSPIOutFlags
; /* SSL attributes we received */
1053 TimeStamp tsExpiry
; /* Time stamp */
1055 dwSSPIFlags
= ASC_REQ_SEQUENCE_DETECT
|
1056 ASC_REQ_REPLAY_DETECT
|
1057 ASC_REQ_CONFIDENTIALITY
|
1058 ASC_REQ_EXTENDED_ERROR
|
1059 ASC_REQ_ALLOCATE_MEMORY
|
1062 buffers
[0].pvBuffer
= NULL
;
1063 buffers
[0].BufferType
= SECBUFFER_TOKEN
;
1064 buffers
[0].cbBuffer
= 0;
1066 message
.cBuffers
= 1;
1067 message
.pBuffers
= buffers
;
1068 message
.ulVersion
= SECBUFFER_VERSION
;
1070 status
= AcceptSecurityContext(&sspi
->creds
, &sspi
->context
, NULL
,
1071 dwSSPIFlags
, SECURITY_NATIVE_DREP
, NULL
,
1072 &message
, &dwSSPIOutFlags
, &tsExpiry
);
1074 if (SUCCEEDED(status
))
1076 pbMessage
= buffers
[0].pvBuffer
;
1077 cbMessage
= buffers
[0].cbBuffer
;
1080 * Send the close notify message to the client.
1083 if (pbMessage
&& cbMessage
)
1085 cbData
= send(http
->fd
, pbMessage
, cbMessage
, 0);
1086 if ((cbData
== SOCKET_ERROR
) || (cbData
== 0))
1088 status
= WSAGetLastError();
1089 DEBUG_printf(("_httpTLSStop: sending close notify failed: %d", status
));
1093 FreeContextBuffer(pbMessage
);
1099 DEBUG_printf(("_httpTLSStop: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), status
)));
1104 DEBUG_printf(("_httpTLSStop: ApplyControlToken failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), status
)));
1108 http_sspi_free(sspi
);
1115 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1118 int /* O - Bytes written */
1119 _httpTLSWrite(http_t
*http
, /* I - HTTP connection */
1120 const char *buf
, /* I - Buffer holding data */
1121 int len
) /* I - Length of buffer */
1123 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1124 SecBufferDesc message
; /* Array of SecBuffer struct */
1125 SecBuffer buffers
[4] = { 0 }; /* Security package buffer */
1126 int bufferLen
; /* Buffer length */
1127 int bytesLeft
; /* Bytes left to write */
1128 const char *bufptr
; /* Pointer into buffer */
1129 int num
= 0; /* Return value */
1132 bufferLen
= sspi
->streamSizes
.cbMaximumMessage
+ sspi
->streamSizes
.cbHeader
+ sspi
->streamSizes
.cbTrailer
;
1134 if (bufferLen
> sspi
->writeBufferLength
)
1136 BYTE
*temp
; /* New buffer pointer */
1138 if ((temp
= (BYTE
*)realloc(sspi
->writeBuffer
, bufferLen
)) == NULL
)
1140 DEBUG_printf(("_httpTLSWrite: Unable to allocate buffer of %d bytes.", bufferLen
));
1141 WSASetLastError(E_OUTOFMEMORY
);
1145 sspi
->writeBuffer
= temp
;
1146 sspi
->writeBufferLength
= bufferLen
;
1154 int chunk
= min((int)sspi
->streamSizes
.cbMaximumMessage
, bytesLeft
);
1155 /* Size of data to write */
1156 SECURITY_STATUS scRet
; /* SSPI status */
1159 * Copy user data into the buffer, starting just past the header...
1162 memcpy(sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
, bufptr
, chunk
);
1165 * Setup the SSPI buffers
1168 message
.ulVersion
= SECBUFFER_VERSION
;
1169 message
.cBuffers
= 4;
1170 message
.pBuffers
= buffers
;
1172 buffers
[0].pvBuffer
= sspi
->writeBuffer
;
1173 buffers
[0].cbBuffer
= sspi
->streamSizes
.cbHeader
;
1174 buffers
[0].BufferType
= SECBUFFER_STREAM_HEADER
;
1175 buffers
[1].pvBuffer
= sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
;
1176 buffers
[1].cbBuffer
= (unsigned long) chunk
;
1177 buffers
[1].BufferType
= SECBUFFER_DATA
;
1178 buffers
[2].pvBuffer
= sspi
->writeBuffer
+ sspi
->streamSizes
.cbHeader
+ chunk
;
1179 buffers
[2].cbBuffer
= sspi
->streamSizes
.cbTrailer
;
1180 buffers
[2].BufferType
= SECBUFFER_STREAM_TRAILER
;
1181 buffers
[3].BufferType
= SECBUFFER_EMPTY
;
1187 scRet
= EncryptMessage(&sspi
->context
, 0, &message
, 0);
1191 DEBUG_printf(("_httpTLSWrite: EncryptMessage failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1192 WSASetLastError(WSASYSCALLFAILURE
);
1197 * Send the data. Remember the size of the total data to send is the size
1198 * of the header, the size of the data the caller passed in and the size
1202 num
= send(http
->fd
, sspi
->writeBuffer
, buffers
[0].cbBuffer
+ buffers
[1].cbBuffer
+ buffers
[2].cbBuffer
, 0);
1206 DEBUG_printf(("_httpTLSWrite: send failed: %ld", WSAGetLastError()));
1220 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
1223 static int /* O - 0 on success, -1 on failure */
1224 http_setup_ssl(http_t
*http
) /* I - Connection to server */
1226 char hostname
[256], /* Hostname */
1227 *hostptr
; /* Pointer into hostname */
1229 TCHAR username
[256]; /* Username returned from GetUserName() */
1230 TCHAR commonName
[256];/* Common name for certificate */
1231 DWORD dwSize
; /* 32 bit size */
1234 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
1237 * Get the hostname to use for SSL...
1240 if (httpAddrLocalhost(http
->hostaddr
))
1242 strlcpy(hostname
, "localhost", sizeof(hostname
));
1247 * Otherwise make sure the hostname we have does not end in a trailing dot.
1250 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
1251 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
1256 http
->tls
= http_sspi_alloc();
1260 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
1264 dwSize
= sizeof(username
) / sizeof(TCHAR
);
1265 GetUserName(username
, &dwSize
);
1266 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
1267 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
1269 if (!_sspiGetCredentials(http
->tls
, L
"ClientContainer",
1272 _sspiFree(http
->tls
);
1276 http
->status
= HTTP_STATUS_ERROR
;
1278 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
1279 _("Unable to establish a secure connection to host."), 1);
1284 _sspiSetAllowsAnyRoot(http
->tls
, TRUE
);
1285 _sspiSetAllowsExpiredCerts(http
->tls
, TRUE
);
1287 if (!_sspiConnect(http
->tls
, hostname
))
1289 _sspiFree(http
->tls
);
1293 http
->status
= HTTP_STATUS_ERROR
;
1295 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
1296 _("Unable to establish a secure connection to host."), 1);
1307 * 'http_sspi_alloc()' - Allocate SSPI object.
1310 static _http_sspi_t
* /* O - New SSPI/SSL object */
1311 http_sspi_alloc(void)
1313 return ((_http_sspi_t
*)calloc(sizeof(_http_sspi_t
), 1));
1318 * 'http_sspi_client()' - Negotiate a TLS connection as a client.
1321 static int /* O - 0 on success, -1 on failure */
1322 http_sspi_client(http_t
*http
, /* I - Client connection */
1323 const char *hostname
) /* I - Server hostname */
1325 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1326 DWORD dwSize
; /* Size for buffer */
1327 DWORD dwSSPIFlags
; /* SSL connection attributes we want */
1328 DWORD dwSSPIOutFlags
; /* SSL connection attributes we got */
1329 TimeStamp tsExpiry
; /* Time stamp */
1330 SECURITY_STATUS scRet
; /* Status */
1331 int cbData
; /* Data count */
1332 SecBufferDesc inBuffer
; /* Array of SecBuffer structs */
1333 SecBuffer inBuffers
[2]; /* Security package buffer */
1334 SecBufferDesc outBuffer
; /* Array of SecBuffer structs */
1335 SecBuffer outBuffers
[1]; /* Security package buffer */
1336 int ret
= 0; /* Return value */
1337 char username
[1024], /* Current username */
1338 common_name
[1024]; /* CN=username */
1341 DEBUG_printf(("4http_sspi_client(http=%p, hostname=\"%s\")", http
, hostname
));
1343 dwSSPIFlags
= ISC_REQ_SEQUENCE_DETECT
|
1344 ISC_REQ_REPLAY_DETECT
|
1345 ISC_REQ_CONFIDENTIALITY
|
1346 ISC_RET_EXTENDED_ERROR
|
1347 ISC_REQ_ALLOCATE_MEMORY
|
1351 * Lookup the client certificate...
1354 dwSize
= sizeof(username
);
1355 GetUserName(username
, &dwSize
);
1356 snprintf(common_name
, sizeof(common_name
), "CN=%s", username
);
1358 if (!http_sspi_find_credentials(http
, L
"ClientContainer", common_name
))
1359 if (!http_sspi_make_credentials(http
->tls
, L
"ClientContainer", common_name
, _HTTP_MODE_CLIENT
, 10))
1361 DEBUG_puts("5http_sspi_client: Unable to get client credentials.");
1366 * Initiate a ClientHello message and generate a token.
1369 outBuffers
[0].pvBuffer
= NULL
;
1370 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1371 outBuffers
[0].cbBuffer
= 0;
1373 outBuffer
.cBuffers
= 1;
1374 outBuffer
.pBuffers
= outBuffers
;
1375 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
1377 scRet
= InitializeSecurityContext(&sspi
->creds
, NULL
, TEXT(""), dwSSPIFlags
, 0, SECURITY_NATIVE_DREP
, NULL
, 0, &sspi
->context
, &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
1379 if (scRet
!= SEC_I_CONTINUE_NEEDED
)
1381 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(1) failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1386 * Send response to server if there is one.
1389 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
1391 if ((cbData
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0)) <= 0)
1393 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1394 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1395 DeleteSecurityContext(&sspi
->context
);
1399 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData
));
1401 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1402 outBuffers
[0].pvBuffer
= NULL
;
1405 dwSSPIFlags
= ISC_REQ_MANUAL_CRED_VALIDATION
|
1406 ISC_REQ_SEQUENCE_DETECT
|
1407 ISC_REQ_REPLAY_DETECT
|
1408 ISC_REQ_CONFIDENTIALITY
|
1409 ISC_RET_EXTENDED_ERROR
|
1410 ISC_REQ_ALLOCATE_MEMORY
|
1413 sspi
->decryptBufferUsed
= 0;
1416 * Loop until the handshake is finished or an error occurs.
1419 scRet
= SEC_I_CONTINUE_NEEDED
;
1421 while(scRet
== SEC_I_CONTINUE_NEEDED
||
1422 scRet
== SEC_E_INCOMPLETE_MESSAGE
||
1423 scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
1425 if (sspi
->decryptBufferUsed
== 0 || scRet
== SEC_E_INCOMPLETE_MESSAGE
)
1427 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
1429 BYTE
*temp
; /* New buffer */
1431 if (sspi
->decryptBufferLength
>= 262144)
1433 WSASetLastError(E_OUTOFMEMORY
);
1434 DEBUG_puts("5http_sspi_client: Decryption buffer too large (>256k)");
1438 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
1440 DEBUG_printf(("5http_sspi_client: Unable to allocate %d byte buffer.", sspi
->decryptBufferLength
+ 4096));
1441 WSASetLastError(E_OUTOFMEMORY
);
1445 sspi
->decryptBufferLength
+= 4096;
1446 sspi
->decryptBuffer
= temp
;
1449 cbData
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
1453 DEBUG_printf(("5http_sspi_client: recv failed: %d", WSAGetLastError()));
1456 else if (cbData
== 0)
1458 DEBUG_printf(("5http_sspi_client: Server unexpectedly disconnected."));
1462 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data received", cbData
));
1464 sspi
->decryptBufferUsed
+= cbData
;
1468 * Set up the input buffers. Buffer 0 is used to pass in data received from
1469 * the server. Schannel will consume some or all of this. Leftover data
1470 * (if any) will be placed in buffer 1 and given a buffer type of
1474 inBuffers
[0].pvBuffer
= sspi
->decryptBuffer
;
1475 inBuffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
1476 inBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1478 inBuffers
[1].pvBuffer
= NULL
;
1479 inBuffers
[1].cbBuffer
= 0;
1480 inBuffers
[1].BufferType
= SECBUFFER_EMPTY
;
1482 inBuffer
.cBuffers
= 2;
1483 inBuffer
.pBuffers
= inBuffers
;
1484 inBuffer
.ulVersion
= SECBUFFER_VERSION
;
1487 * Set up the output buffers. These are initialized to NULL so as to make it
1488 * less likely we'll attempt to free random garbage later.
1491 outBuffers
[0].pvBuffer
= NULL
;
1492 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
1493 outBuffers
[0].cbBuffer
= 0;
1495 outBuffer
.cBuffers
= 1;
1496 outBuffer
.pBuffers
= outBuffers
;
1497 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
1500 * Call InitializeSecurityContext.
1503 scRet
= InitializeSecurityContext(&sspi
->creds
, &sspi
->context
, NULL
, dwSSPIFlags
, 0, SECURITY_NATIVE_DREP
, &inBuffer
, 0, NULL
, &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
1506 * If InitializeSecurityContext was successful (or if the error was one of
1507 * the special extended ones), send the contents of the output buffer to the
1511 if (scRet
== SEC_E_OK
||
1512 scRet
== SEC_I_CONTINUE_NEEDED
||
1513 FAILED(scRet
) && (dwSSPIOutFlags
& ISC_RET_EXTENDED_ERROR
))
1515 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
1517 cbData
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0);
1521 DEBUG_printf(("5http_sspi_client: send failed: %d", WSAGetLastError()));
1522 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1523 DeleteSecurityContext(&sspi
->context
);
1527 DEBUG_printf(("5http_sspi_client: %d bytes of handshake data sent.", cbData
));
1530 * Free output buffer.
1533 FreeContextBuffer(outBuffers
[0].pvBuffer
);
1534 outBuffers
[0].pvBuffer
= NULL
;
1539 * If InitializeSecurityContext returned SEC_E_INCOMPLETE_MESSAGE, then we
1540 * need to read more data from the server and try again.
1543 if (scRet
== SEC_E_INCOMPLETE_MESSAGE
)
1547 * If InitializeSecurityContext returned SEC_E_OK, then the handshake
1548 * completed successfully.
1551 if (scRet
== SEC_E_OK
)
1554 * If the "extra" buffer contains data, this is encrypted application
1555 * protocol layer stuff. It needs to be saved. The application layer will
1556 * later decrypt it with DecryptMessage.
1559 DEBUG_puts("5http_sspi_client: Handshake was successful.");
1561 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
1563 memmove(sspi
->decryptBuffer
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
, inBuffers
[1].cbBuffer
);
1565 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
1567 DEBUG_printf(("5http_sspi_client: %d bytes of app data was bundled with handshake data", sspi
->decryptBufferUsed
));
1570 sspi
->decryptBufferUsed
= 0;
1580 * Check for fatal error.
1585 DEBUG_printf(("5http_sspi_client: InitializeSecurityContext(2) failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1591 * If InitializeSecurityContext returned SEC_I_INCOMPLETE_CREDENTIALS,
1592 * then the server just requested client authentication.
1595 if (scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
1601 DEBUG_printf(("5http_sspi_client: server requested client credentials."));
1607 * Copy any leftover data from the "extra" buffer, and go around again.
1610 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
1612 memmove(sspi
->decryptBuffer
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
, inBuffers
[1].cbBuffer
);
1614 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
1618 sspi
->decryptBufferUsed
= 0;
1625 * Success! Get the server cert
1628 sspi
->contextInitialized
= TRUE
;
1630 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_REMOTE_CERT_CONTEXT
, (VOID
*)&(sspi
->remoteCert
));
1632 if (scRet
!= SEC_E_OK
)
1634 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_REMOTE_CERT_CONTEXT): %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1639 * Find out how big the header/trailer will be:
1642 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_STREAM_SIZES
, &sspi
->streamSizes
);
1644 if (scRet
!= SEC_E_OK
)
1646 DEBUG_printf(("5http_sspi_client: QueryContextAttributes failed(SECPKG_ATTR_STREAM_SIZES): %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
1656 * 'http_sspi_create_credential()' - Create an SSPI certificate context.
1659 static PCCERT_CONTEXT
/* O - Certificate context */
1660 http_sspi_create_credential(
1661 http_credential_t
*cred
) /* I - Credential */
1664 return (CertCreateCertificateContext(X509_ASN_ENCODING
, cred
->data
, cred
->datalen
));
1671 * 'http_sspi_find_credentials()' - Retrieve a TLS certificate from the system store.
1674 static BOOL
/* O - 1 on success, 0 on failure */
1675 http_sspi_find_credentials(
1676 http_t
*http
, /* I - HTTP connection */
1677 const LPWSTR container
, /* I - Cert container name */
1678 const char *common_name
) /* I - Common name of certificate */
1680 _http_sspi_t
*sspi
= http
->tls
; /* SSPI data */
1681 HCERTSTORE store
= NULL
; /* Certificate store */
1682 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
1683 DWORD dwSize
= 0; /* 32 bit size */
1684 PBYTE p
= NULL
; /* Temporary storage */
1685 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
1686 /* Handle to a CSP */
1687 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
1688 SCHANNEL_CRED SchannelCred
; /* Schannel credential data */
1689 TimeStamp tsExpiry
; /* Time stamp */
1690 SECURITY_STATUS Status
; /* Status */
1691 BOOL ok
= TRUE
; /* Return value */
1694 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
1696 if (GetLastError() == NTE_EXISTS
)
1698 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
1700 DEBUG_printf(("5http_sspi_find_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1707 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");
1711 DEBUG_printf(("5http_sspi_find_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1718 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
1720 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1725 p
= (PBYTE
)malloc(dwSize
);
1729 DEBUG_printf(("5http_sspi_find_credentials: malloc failed for %d bytes.", dwSize
));
1734 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
1736 DEBUG_printf(("5http_sspi_find_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1741 sib
.cbData
= dwSize
;
1744 storedContext
= CertFindCertificateInStore(store
, X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, 0, CERT_FIND_SUBJECT_NAME
, &sib
, NULL
);
1748 DEBUG_printf(("5http_sspi_find_credentials: Unable to find credentials for \"%s\".", common_name
));
1753 ZeroMemory(&SchannelCred
, sizeof(SchannelCred
));
1755 SchannelCred
.dwVersion
= SCHANNEL_CRED_VERSION
;
1756 SchannelCred
.cCreds
= 1;
1757 SchannelCred
.paCred
= &storedContext
;
1760 * Set supported protocols (can also be overriden in the registry...)
1763 #ifdef SP_PROT_TLS1_2_SERVER
1764 if (http
->mode
== _HTTP_MODE_SERVER
)
1766 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1767 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
;
1768 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1769 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
| SP_PROT_TLS1_0_SERVER
| SP_PROT_SSL3_SERVER
;
1771 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_SERVER
| SP_PROT_TLS1_1_SERVER
| SP_PROT_TLS1_0_SERVER
;
1775 if (tls_options
& _HTTP_TLS_DENY_TLS10
)
1776 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
;
1777 else if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1778 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
| SP_PROT_TLS1_0_CLIENT
| SP_PROT_SSL3_CLIENT
;
1780 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_2_CLIENT
| SP_PROT_TLS1_1_CLIENT
| SP_PROT_TLS1_0_CLIENT
;
1784 if (http
->mode
== _HTTP_MODE_SERVER
)
1786 if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1787 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_SERVER
| SP_PROT_SSL3_SERVER
;
1789 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_SERVER
;
1793 if (tls_options
& _HTTP_TLS_ALLOW_SSL3
)
1794 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_CLIENT
| SP_PROT_SSL3_CLIENT
;
1796 SchannelCred
.grbitEnabledProtocols
= SP_PROT_TLS1_CLIENT
;
1798 #endif /* SP_PROT_TLS1_2_SERVER */
1800 /* TODO: Support _HTTP_TLS_ALLOW_RC4 and _HTTP_TLS_ALLOW_DH options; right now we'll rely on Windows registry to enable/disable RC4/DH... */
1803 * Create an SSPI credential.
1806 Status
= AcquireCredentialsHandle(NULL
, UNISP_NAME
, http
->mode
== _HTTP_MODE_SERVER
? SECPKG_CRED_INBOUND
: SECPKG_CRED_OUTBOUND
, NULL
, &SchannelCred
, NULL
, NULL
, &sspi
->creds
, &tsExpiry
);
1807 if (Status
!= SEC_E_OK
)
1809 DEBUG_printf(("5http_sspi_find_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), Status
)));
1821 CertFreeCertificateContext(storedContext
);
1827 CertCloseStore(store
, 0);
1830 CryptReleaseContext(hProv
, 0);
1837 * 'http_sspi_free()' - Close a connection and free resources.
1841 http_sspi_free(_http_sspi_t
*sspi
) /* I - SSPI data */
1846 if (sspi
->contextInitialized
)
1847 DeleteSecurityContext(&sspi
->context
);
1849 if (sspi
->decryptBuffer
)
1850 free(sspi
->decryptBuffer
);
1852 if (sspi
->readBuffer
)
1853 free(sspi
->readBuffer
);
1855 if (sspi
->writeBuffer
)
1856 free(sspi
->writeBuffer
);
1858 if (sspi
->localCert
)
1859 CertFreeCertificateContext(sspi
->localCert
);
1861 if (sspi
->remoteCert
)
1862 CertFreeCertificateContext(sspi
->remoteCert
);
1869 * 'http_sspi_make_credentials()' - Create a TLS certificate in the system store.
1872 static BOOL
/* O - 1 on success, 0 on failure */
1873 http_sspi_make_credentials(
1874 _http_sspi_t
*sspi
, /* I - SSPI data */
1875 const LPWSTR container
, /* I - Cert container name */
1876 const char *common_name
, /* I - Common name of certificate */
1877 _http_mode_t mode
, /* I - Client or server? */
1878 int years
) /* I - Years until expiration */
1880 HCERTSTORE store
= NULL
; /* Certificate store */
1881 PCCERT_CONTEXT storedContext
= NULL
; /* Context created from the store */
1882 PCCERT_CONTEXT createdContext
= NULL
; /* Context created by us */
1883 DWORD dwSize
= 0; /* 32 bit size */
1884 PBYTE p
= NULL
; /* Temporary storage */
1885 HCRYPTPROV hProv
= (HCRYPTPROV
)NULL
;
1886 /* Handle to a CSP */
1887 CERT_NAME_BLOB sib
; /* Arbitrary array of bytes */
1888 SCHANNEL_CRED SchannelCred
; /* Schannel credential data */
1889 TimeStamp tsExpiry
; /* Time stamp */
1890 SECURITY_STATUS Status
; /* Status */
1891 HCRYPTKEY hKey
= (HCRYPTKEY
)NULL
; /* Handle to crypto key */
1892 CRYPT_KEY_PROV_INFO kpi
; /* Key container info */
1893 SYSTEMTIME et
; /* System time */
1894 CERT_EXTENSIONS exts
; /* Array of cert extensions */
1895 CRYPT_KEY_PROV_INFO ckp
; /* Handle to crypto key */
1896 BOOL ok
= TRUE
; /* Return value */
1899 DEBUG_printf(("4http_sspi_make_credentials(sspi=%p, container=%p, common_name=\"%s\", mode=%d, years=%d)", sspi
, container
, common_name
, mode
, years
));
1901 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_NEWKEYSET
| CRYPT_MACHINE_KEYSET
))
1903 if (GetLastError() == NTE_EXISTS
)
1905 if (!CryptAcquireContextW(&hProv
, (LPWSTR
)container
, MS_DEF_PROV_W
, PROV_RSA_FULL
, CRYPT_MACHINE_KEYSET
))
1907 DEBUG_printf(("5http_sspi_make_credentials: CryptAcquireContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1914 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");
1918 DEBUG_printf(("5http_sspi_make_credentials: CertOpenSystemStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1925 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, NULL
, &dwSize
, NULL
))
1927 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1932 p
= (PBYTE
)malloc(dwSize
);
1936 DEBUG_printf(("5http_sspi_make_credentials: malloc failed for %d bytes", dwSize
));
1941 if (!CertStrToName(X509_ASN_ENCODING
, common_name
, CERT_OID_NAME_STR
, NULL
, p
, &dwSize
, NULL
))
1943 DEBUG_printf(("5http_sspi_make_credentials: CertStrToName failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1949 * Create a private key and self-signed certificate...
1952 if (!CryptGenKey(hProv
, AT_KEYEXCHANGE
, CRYPT_EXPORTABLE
, &hKey
))
1954 DEBUG_printf(("5http_sspi_make_credentials: CryptGenKey failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1959 ZeroMemory(&kpi
, sizeof(kpi
));
1960 kpi
.pwszContainerName
= (LPWSTR
)container
;
1961 kpi
.pwszProvName
= MS_DEF_PROV_W
;
1962 kpi
.dwProvType
= PROV_RSA_FULL
;
1963 kpi
.dwFlags
= CERT_SET_KEY_CONTEXT_PROP_ID
;
1964 kpi
.dwKeySpec
= AT_KEYEXCHANGE
;
1969 ZeroMemory(&exts
, sizeof(exts
));
1971 createdContext
= CertCreateSelfSignCertificate(hProv
, &sib
, 0, &kpi
, NULL
, NULL
, &et
, &exts
);
1973 if (!createdContext
)
1975 DEBUG_printf(("5http_sspi_make_credentials: CertCreateSelfSignCertificate failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1981 * Add the created context to the named store, and associate it with the named
1985 if (!CertAddCertificateContextToStore(store
, createdContext
, CERT_STORE_ADD_REPLACE_EXISTING
, &storedContext
))
1987 DEBUG_printf(("5http_sspi_make_credentials: CertAddCertificateContextToStore failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
1992 ZeroMemory(&ckp
, sizeof(ckp
));
1993 ckp
.pwszContainerName
= (LPWSTR
) container
;
1994 ckp
.pwszProvName
= MS_DEF_PROV_W
;
1995 ckp
.dwProvType
= PROV_RSA_FULL
;
1996 ckp
.dwFlags
= CRYPT_MACHINE_KEYSET
;
1997 ckp
.dwKeySpec
= AT_KEYEXCHANGE
;
1999 if (!CertSetCertificateContextProperty(storedContext
, CERT_KEY_PROV_INFO_PROP_ID
, 0, &ckp
))
2001 DEBUG_printf(("5http_sspi_make_credentials: CertSetCertificateContextProperty failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), GetLastError())));
2007 * Get a handle to use the certificate...
2010 ZeroMemory(&SchannelCred
, sizeof(SchannelCred
));
2012 SchannelCred
.dwVersion
= SCHANNEL_CRED_VERSION
;
2013 SchannelCred
.cCreds
= 1;
2014 SchannelCred
.paCred
= &storedContext
;
2017 * SSPI doesn't seem to like it if grbitEnabledProtocols is set for a client.
2020 if (mode
== _HTTP_MODE_SERVER
)
2021 SchannelCred
.grbitEnabledProtocols
= SP_PROT_SSL3TLS1
;
2024 * Create an SSPI credential.
2027 Status
= AcquireCredentialsHandle(NULL
, UNISP_NAME
, mode
== _HTTP_MODE_SERVER
? SECPKG_CRED_INBOUND
: SECPKG_CRED_OUTBOUND
, NULL
, &SchannelCred
, NULL
, NULL
, &sspi
->creds
, &tsExpiry
);
2028 if (Status
!= SEC_E_OK
)
2030 DEBUG_printf(("5http_sspi_make_credentials: AcquireCredentialsHandle failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), Status
)));
2042 CryptDestroyKey(hKey
);
2045 CertFreeCertificateContext(createdContext
);
2048 CertFreeCertificateContext(storedContext
);
2054 CertCloseStore(store
, 0);
2057 CryptReleaseContext(hProv
, 0);
2064 * 'http_sspi_server()' - Negotiate a TLS connection as a server.
2067 static int /* O - 0 on success, -1 on failure */
2068 http_sspi_server(http_t
*http
, /* I - HTTP connection */
2069 const char *hostname
) /* I - Hostname of server */
2071 _http_sspi_t
*sspi
= http
->tls
; /* I - SSPI data */
2072 char common_name
[512]; /* Common name for cert */
2073 DWORD dwSSPIFlags
; /* SSL connection attributes we want */
2074 DWORD dwSSPIOutFlags
; /* SSL connection attributes we got */
2075 TimeStamp tsExpiry
; /* Time stamp */
2076 SECURITY_STATUS scRet
; /* SSPI Status */
2077 SecBufferDesc inBuffer
; /* Array of SecBuffer structs */
2078 SecBuffer inBuffers
[2]; /* Security package buffer */
2079 SecBufferDesc outBuffer
; /* Array of SecBuffer structs */
2080 SecBuffer outBuffers
[1]; /* Security package buffer */
2081 int num
= 0; /* 32 bit status value */
2082 BOOL fInitContext
= TRUE
; /* Has the context been init'd? */
2083 int ret
= 0; /* Return value */
2086 DEBUG_printf(("4http_sspi_server(http=%p, hostname=\"%s\")", http
, hostname
));
2088 dwSSPIFlags
= ASC_REQ_SEQUENCE_DETECT
|
2089 ASC_REQ_REPLAY_DETECT
|
2090 ASC_REQ_CONFIDENTIALITY
|
2091 ASC_REQ_EXTENDED_ERROR
|
2092 ASC_REQ_ALLOCATE_MEMORY
|
2095 sspi
->decryptBufferUsed
= 0;
2098 * Lookup the server certificate...
2101 snprintf(common_name
, sizeof(common_name
), "CN=%s", hostname
);
2103 if (!http_sspi_find_credentials(http
, L
"ServerContainer", common_name
))
2104 if (!http_sspi_make_credentials(http
->tls
, L
"ServerContainer", common_name
, _HTTP_MODE_SERVER
, 10))
2106 DEBUG_puts("5http_sspi_server: Unable to get server credentials.");
2111 * Set OutBuffer for AcceptSecurityContext call
2114 outBuffer
.cBuffers
= 1;
2115 outBuffer
.pBuffers
= outBuffers
;
2116 outBuffer
.ulVersion
= SECBUFFER_VERSION
;
2118 scRet
= SEC_I_CONTINUE_NEEDED
;
2120 while (scRet
== SEC_I_CONTINUE_NEEDED
||
2121 scRet
== SEC_E_INCOMPLETE_MESSAGE
||
2122 scRet
== SEC_I_INCOMPLETE_CREDENTIALS
)
2124 if (sspi
->decryptBufferUsed
== 0 || scRet
== SEC_E_INCOMPLETE_MESSAGE
)
2126 if (sspi
->decryptBufferLength
<= sspi
->decryptBufferUsed
)
2128 BYTE
*temp
; /* New buffer */
2130 if (sspi
->decryptBufferLength
>= 262144)
2132 WSASetLastError(E_OUTOFMEMORY
);
2133 DEBUG_puts("5http_sspi_server: Decryption buffer too large (>256k)");
2137 if ((temp
= realloc(sspi
->decryptBuffer
, sspi
->decryptBufferLength
+ 4096)) == NULL
)
2139 DEBUG_printf(("5http_sspi_server: Unable to allocate %d byte buffer.", sspi
->decryptBufferLength
+ 4096));
2140 WSASetLastError(E_OUTOFMEMORY
);
2144 sspi
->decryptBufferLength
+= 4096;
2145 sspi
->decryptBuffer
= temp
;
2150 num
= recv(http
->fd
, sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
, (int)(sspi
->decryptBufferLength
- sspi
->decryptBufferUsed
), 0);
2152 if (num
== -1 && WSAGetLastError() == WSAEWOULDBLOCK
)
2160 DEBUG_printf(("5http_sspi_server: recv failed: %d", WSAGetLastError()));
2165 DEBUG_puts("5http_sspi_server: client disconnected");
2169 DEBUG_printf(("5http_sspi_server: received %d (handshake) bytes from client.", num
));
2170 sspi
->decryptBufferUsed
+= num
;
2174 * InBuffers[1] is for getting extra data that SSPI/SCHANNEL doesn't process
2175 * on this run around the loop.
2178 inBuffers
[0].pvBuffer
= sspi
->decryptBuffer
;
2179 inBuffers
[0].cbBuffer
= (unsigned long)sspi
->decryptBufferUsed
;
2180 inBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
2182 inBuffers
[1].pvBuffer
= NULL
;
2183 inBuffers
[1].cbBuffer
= 0;
2184 inBuffers
[1].BufferType
= SECBUFFER_EMPTY
;
2186 inBuffer
.cBuffers
= 2;
2187 inBuffer
.pBuffers
= inBuffers
;
2188 inBuffer
.ulVersion
= SECBUFFER_VERSION
;
2191 * Initialize these so if we fail, pvBuffer contains NULL, so we don't try to
2192 * free random garbage at the quit.
2195 outBuffers
[0].pvBuffer
= NULL
;
2196 outBuffers
[0].BufferType
= SECBUFFER_TOKEN
;
2197 outBuffers
[0].cbBuffer
= 0;
2199 scRet
= AcceptSecurityContext(&sspi
->creds
, (fInitContext
?NULL
:&sspi
->context
), &inBuffer
, dwSSPIFlags
, SECURITY_NATIVE_DREP
, (fInitContext
?&sspi
->context
:NULL
), &outBuffer
, &dwSSPIOutFlags
, &tsExpiry
);
2201 fInitContext
= FALSE
;
2203 if (scRet
== SEC_E_OK
||
2204 scRet
== SEC_I_CONTINUE_NEEDED
||
2205 (FAILED(scRet
) && ((dwSSPIOutFlags
& ISC_RET_EXTENDED_ERROR
) != 0)))
2207 if (outBuffers
[0].cbBuffer
&& outBuffers
[0].pvBuffer
)
2210 * Send response to server if there is one.
2213 num
= send(http
->fd
, outBuffers
[0].pvBuffer
, outBuffers
[0].cbBuffer
, 0);
2217 DEBUG_printf(("5http_sspi_server: handshake send failed: %d", WSAGetLastError()));
2221 DEBUG_printf(("5http_sspi_server: sent %d handshake bytes to client.", outBuffers
[0].cbBuffer
));
2223 FreeContextBuffer(outBuffers
[0].pvBuffer
);
2224 outBuffers
[0].pvBuffer
= NULL
;
2228 if (scRet
== SEC_E_OK
)
2231 * If there's extra data then save it for next time we go to decrypt.
2234 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
2236 memcpy(sspi
->decryptBuffer
, (LPBYTE
)(sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
), inBuffers
[1].cbBuffer
);
2237 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
2241 sspi
->decryptBufferUsed
= 0;
2245 else if (FAILED(scRet
) && scRet
!= SEC_E_INCOMPLETE_MESSAGE
)
2247 DEBUG_printf(("5http_sspi_server: AcceptSecurityContext failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
2252 if (scRet
!= SEC_E_INCOMPLETE_MESSAGE
&&
2253 scRet
!= SEC_I_INCOMPLETE_CREDENTIALS
)
2255 if (inBuffers
[1].BufferType
== SECBUFFER_EXTRA
)
2257 memcpy(sspi
->decryptBuffer
, (LPBYTE
)(sspi
->decryptBuffer
+ sspi
->decryptBufferUsed
- inBuffers
[1].cbBuffer
), inBuffers
[1].cbBuffer
);
2258 sspi
->decryptBufferUsed
= inBuffers
[1].cbBuffer
;
2262 sspi
->decryptBufferUsed
= 0;
2269 sspi
->contextInitialized
= TRUE
;
2272 * Find out how big the header will be:
2275 scRet
= QueryContextAttributes(&sspi
->context
, SECPKG_ATTR_STREAM_SIZES
, &sspi
->streamSizes
);
2277 if (scRet
!= SEC_E_OK
)
2279 DEBUG_printf(("5http_sspi_server: QueryContextAttributes failed: %s", http_sspi_strerror(sspi
->error
, sizeof(sspi
->error
), scRet
)));
2289 * 'http_sspi_strerror()' - Return a string for the specified error code.
2292 static const char * /* O - String for error */
2293 http_sspi_strerror(char *buffer
, /* I - Error message buffer */
2294 size_t bufsize
, /* I - Size of buffer */
2295 DWORD code
) /* I - Error code */
2297 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
, NULL
, code
, 0, buffer
, bufsize
, NULL
))
2300 * Strip trailing CR + LF...
2303 char *ptr
; /* Pointer into error message */
2305 for (ptr
= buffer
+ strlen(buffer
) - 1; ptr
>= buffer
; ptr
--)
2306 if (*ptr
== '\n' || *ptr
== '\r')
2312 snprintf(buffer
, bufsize
, "Unknown error %x", code
);
2319 * 'http_sspi_verify()' - Verify a certificate.
2322 static DWORD
/* O - Error code (0 == No error) */
2324 PCCERT_CONTEXT cert
, /* I - Server certificate */
2325 const char *common_name
, /* I - Common name */
2326 DWORD dwCertFlags
) /* I - Verification flags */
2328 HTTPSPolicyCallbackData httpsPolicy
; /* HTTPS Policy Struct */
2329 CERT_CHAIN_POLICY_PARA policyPara
; /* Cert chain policy parameters */
2330 CERT_CHAIN_POLICY_STATUS policyStatus
;/* Cert chain policy status */
2331 CERT_CHAIN_PARA chainPara
; /* Used for searching and matching criteria */
2332 PCCERT_CHAIN_CONTEXT chainContext
= NULL
;
2333 /* Certificate chain */
2334 PWSTR commonNameUnicode
= NULL
;
2335 /* Unicode common name */
2336 LPSTR rgszUsages
[] = { szOID_PKIX_KP_SERVER_AUTH
,
2337 szOID_SERVER_GATED_CRYPTO
,
2338 szOID_SGC_NETSCAPE
};
2339 /* How are we using this certificate? */
2340 DWORD cUsages
= sizeof(rgszUsages
) / sizeof(LPSTR
);
2341 /* Number of ites in rgszUsages */
2342 DWORD count
; /* 32 bit count variable */
2343 DWORD status
; /* Return value */
2345 char error
[1024]; /* Error message string */
2350 return (SEC_E_WRONG_PRINCIPAL
);
2353 * Convert common name to Unicode.
2356 if (!common_name
|| !*common_name
)
2357 return (SEC_E_WRONG_PRINCIPAL
);
2359 count
= MultiByteToWideChar(CP_ACP
, 0, common_name
, -1, NULL
, 0);
2360 commonNameUnicode
= LocalAlloc(LMEM_FIXED
, count
* sizeof(WCHAR
));
2361 if (!commonNameUnicode
)
2362 return (SEC_E_INSUFFICIENT_MEMORY
);
2364 if (!MultiByteToWideChar(CP_ACP
, 0, common_name
, -1, commonNameUnicode
, count
))
2366 LocalFree(commonNameUnicode
);
2367 return (SEC_E_WRONG_PRINCIPAL
);
2371 * Build certificate chain.
2374 ZeroMemory(&chainPara
, sizeof(chainPara
));
2376 chainPara
.cbSize
= sizeof(chainPara
);
2377 chainPara
.RequestedUsage
.dwType
= USAGE_MATCH_TYPE_OR
;
2378 chainPara
.RequestedUsage
.Usage
.cUsageIdentifier
= cUsages
;
2379 chainPara
.RequestedUsage
.Usage
.rgpszUsageIdentifier
= rgszUsages
;
2381 if (!CertGetCertificateChain(NULL
, cert
, NULL
, cert
->hCertStore
, &chainPara
, 0, NULL
, &chainContext
))
2383 status
= GetLastError();
2385 DEBUG_printf(("CertGetCertificateChain returned: %s", http_sspi_strerror(error
, sizeof(error
), status
)));
2387 LocalFree(commonNameUnicode
);
2392 * Validate certificate chain.
2395 ZeroMemory(&httpsPolicy
, sizeof(HTTPSPolicyCallbackData
));
2396 httpsPolicy
.cbStruct
= sizeof(HTTPSPolicyCallbackData
);
2397 httpsPolicy
.dwAuthType
= AUTHTYPE_SERVER
;
2398 httpsPolicy
.fdwChecks
= dwCertFlags
;
2399 httpsPolicy
.pwszServerName
= commonNameUnicode
;
2401 memset(&policyPara
, 0, sizeof(policyPara
));
2402 policyPara
.cbSize
= sizeof(policyPara
);
2403 policyPara
.pvExtraPolicyPara
= &httpsPolicy
;
2405 memset(&policyStatus
, 0, sizeof(policyStatus
));
2406 policyStatus
.cbSize
= sizeof(policyStatus
);
2408 if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL
, chainContext
, &policyPara
, &policyStatus
))
2410 status
= GetLastError();
2412 DEBUG_printf(("CertVerifyCertificateChainPolicy returned %s", http_sspi_strerror(error
, sizeof(error
), status
)));
2414 else if (policyStatus
.dwError
)
2415 status
= policyStatus
.dwError
;
2420 CertFreeCertificateChain(chainContext
);
2422 if (commonNameUnicode
)
2423 LocalFree(commonNameUnicode
);