Debian Codegraph @

c/src/ssl/schannel.cpp

raw
1 /*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21
22 /*
23 * SChannel is designed to encrypt and decrypt data in place. So a
24 * given buffer is expected to sometimes contain encrypted data,
25 * sometimes decrypted data, and occasionally both. Outgoing buffers
26 * need to reserve space for the TLS header and trailer. Read
27 * operations need to ignore the same headers and trailers from
28 * incoming buffers. Outgoing is simple because we choose record
29 * boundaries. Incoming is complicated by handling incomplete TLS
30 * records, and buffering contiguous data for the app layer that may
31 * span many records. A lazy double buffering system is used for
32 * the latter.
33 */
34
35 #include "core/autodetect.h"
36 #include "core/engine-internal.h"
37 #include "core/logger_private.h"
38 #include "core/util.h"
39
40 #include "platform/platform.h"
41
42 #include <proton/ssl.h>
43 #include <proton/engine.h>
44
45 #include <assert.h>
46 #include <stdio.h>
47
48 // security.h needs to see this to distinguish from kernel use.
49 #include <windows.h>
50 #define SECURITY_WIN32
51 #include <security.h>
52 #include <Schnlsp.h>
53 #include <WinInet.h>
54 #undef SECURITY_WIN32
55
56 extern "C" {
57
58 /** @file
59 * SSL/TLS support API.
60 *
61 * This file contains an SChannel-based implemention of the SSL/TLS API for Windows platforms.
62 */
63
64 static void ssl_log(pn_transport_t *transport, pn_log_level_t sev, const char *fmt, ...);
65 static void ssl_log_error(const char *fmt, ...);
66 static void ssl_log_error_status(HRESULT status, const char *fmt, ...);
67 static HCERTSTORE open_cert_db(const char *store_name, const char *passwd, int *error);
68
69 // Thread support. Some SChannel objects are shared or ref-counted.
70 // Consistent with the rest of Proton, we assume a connection (and
71 // therefore its pn_ssl_t) will not be accessed concurrently by
72 // multiple threads.
73 class csguard {
74 public:
75 csguard(CRITICAL_SECTION *cs) : cs_(cs), set_(true) { EnterCriticalSection(cs_); }
76 ~csguard() { if (set_) LeaveCriticalSection(cs_); }
77 void release() {
78 if (set_) {
79 set_ = false;
80 LeaveCriticalSection(cs_);
81 }
82 }
83 private:
84 LPCRITICAL_SECTION cs_;
85 bool set_;
86 };
87
88 /*
89 * win_credential_t: SChannel context that must accompany TLS connections.
90 *
91 * SChannel attempts session resumption for shared CredHandle objects.
92 * To mimic openssl behavior, server CredHandle handles must be shared
93 * by derived connections, client CredHandle handles must be unique
94 * when app's session_id is null and tracked for reuse otherwise
95 * (TODO).
96 *
97 * Ref counted by parent ssl_domain_t and each derived connection.
98 */
99 struct win_credential_t {
100 CRITICAL_SECTION cslock;
101 pn_ssl_mode_t mode;
102 PCCERT_CONTEXT cert_context; // Particulars of the certificate (if any)
103 CredHandle cred_handle; // Bound session parameters, certificate, CAs, verification_mode
104 HCERTSTORE trust_store; // Store of root CAs for validating
105 HCERTSTORE server_CA_certs; // CAs advertised by server (may be a duplicate of the trust_store)
106 char *trust_store_name;
107 };
108
109 #define win_credential_compare NULL
110 #define win_credential_inspect NULL
111 #define win_credential_hashcode NULL
112
113 static void win_credential_initialize(void *object)
114 {
115 win_credential_t *c = (win_credential_t *) object;
116 InitializeCriticalSectionAndSpinCount(&c->cslock, 4000);
117 SecInvalidateHandle(&c->cred_handle);
118 c->cert_context = 0;
119 c->trust_store = 0;
120 c->server_CA_certs = 0;
121 c->trust_store_name = 0;
122 }
123
124 static void win_credential_finalize(void *object)
125 {
126 win_credential_t *c = (win_credential_t *) object;
127 if (SecIsValidHandle(&c->cred_handle))
128 FreeCredentialsHandle(&c->cred_handle);
129 if (c->cert_context)
130 CertFreeCertificateContext(c->cert_context);
131 if (c->trust_store)
132 CertCloseStore(c->trust_store, 0);
133 if (c->server_CA_certs)
134 CertCloseStore(c->server_CA_certs, 0);
135 DeleteCriticalSection(&c->cslock);
136 free(c->trust_store_name);
137 }
138
139 static win_credential_t *win_credential(pn_ssl_mode_t m)
140 {
141 static const pn_cid_t CID_win_credential = CID_pn_void;
142 static const pn_class_t clazz = PN_CLASS(win_credential);
143 win_credential_t *c = (win_credential_t *) pn_class_new(&clazz, sizeof(win_credential_t));
144 c->mode = m;
145 csguard g(&c->cslock);
146 pn_incref(c); // See next comment regarding refcounting and locks
147 return c;
148 }
149
150 // Hack strategy for Proton object refcounting. Just hold the lock for incref.
151 // Use the next two functions for decref, one with, the other without the lock.
152 // The refcount is artificially bumped by one in win_credential() so that we
153 // can use refcount == 1 to actually delete (by calling decref one last time).
154 static bool win_credential_decref(win_credential_t *c)
155 {
156 // Call with lock held. Caller MUST call win_credential_delete if this returns true.
157 return pn_decref(c) == 1;
158 }
159
160 static void win_credential_delete(win_credential_t *c)
161 {
162 // Call without lock held.
163 assert(pn_refcount(c) == 1);
164 pn_decref(c);
165 }
166
167 static int win_credential_load_cert(win_credential_t *cred, const char *store_name, const char *cert_name, const char *passwd)
168 {
169 if (!store_name)
170 return -2;
171
172 int ec = 0;
173 HCERTSTORE cert_store = open_cert_db(store_name, passwd, &ec);
174 if (!cert_store)
175 return ec;
176
177 // find friendly name that matches cert_name, or sole certificate
178 PCCERT_CONTEXT tmpctx = NULL;
179 PCCERT_CONTEXT found_ctx = NULL;
180 int cert_count = 0;
181 int name_len = cert_name ? strlen(cert_name) : 0;
182 char *fn = name_len ? (char *) malloc(name_len + 1) : 0;
183 while (tmpctx = CertEnumCertificatesInStore(cert_store, tmpctx)) {
184 cert_count++;
185 if (cert_name && *cert_name) {
186 DWORD len = CertGetNameString(tmpctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE,
187 0, NULL, NULL, 0);
188 if (len != name_len + 1)
189 continue;
190 CertGetNameString(tmpctx, CERT_NAME_FRIENDLY_DISPLAY_TYPE,
191 0, NULL, fn, len);
192 if (!strcmp(cert_name, fn)) {
193 found_ctx = tmpctx;
194 tmpctx= NULL;
195 break;
196 }
197 } else {
198 // Test for single certificate
199 if (cert_count == 1) {
200 found_ctx = CertDuplicateCertificateContext(tmpctx);
201 } else {
202 ssl_log_error("Multiple certificates to choose from certificate store %s", store_name);
203 found_ctx = NULL;
204 break;
205 }
206 }
207 }
208
209 if (tmpctx) {
210 CertFreeCertificateContext(tmpctx);
211 tmpctx = false;
212 }
213 if (!found_ctx && cert_name && cert_count == 1)
214 ssl_log_error("Could not find certificate %s in store %s", cert_name, store_name);
215 cred->cert_context = found_ctx;
216
217 free(fn);
218 CertCloseStore(cert_store, 0);
219 return found_ctx ? 0 : -8;
220 }
221
222
223 // call with win_credential lock held
224 static CredHandle win_credential_cred_handle(win_credential_t *cred, const char *session_id, SECURITY_STATUS *status)
225 {
226 if (cred->mode == PN_SSL_MODE_SERVER && SecIsValidHandle(&cred->cred_handle)) {
227 *status = SEC_E_OK;
228 return cred->cred_handle; // Server always reuses cached value
229 }
230 // TODO: if (is_client && session_id != NULL) create or use cached value based on
231 // session_id+server_host_name (per domain? reclaimed after X hours?)
232
233 CredHandle tmp_handle;
234 SecInvalidateHandle(&tmp_handle);
235 TimeStamp expiry; // Not used
236 SCHANNEL_CRED descriptor;
237 memset(&descriptor, 0, sizeof(descriptor));
238
239 descriptor.dwVersion = SCHANNEL_CRED_VERSION;
240 descriptor.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_MANUAL_CRED_VALIDATION;
241 if (cred->cert_context != NULL) {
242 // assign the certificate into the credentials
243 descriptor.paCred = &cred->cert_context;
244 descriptor.cCreds = 1;
245 }
246
247 if (cred->mode == PN_SSL_MODE_SERVER) {
248 descriptor.dwFlags |= SCH_CRED_NO_SYSTEM_MAPPER;
249 if (cred->server_CA_certs) {
250 descriptor.hRootStore = cred->server_CA_certs;
251 }
252 }
253
254 ULONG direction = (cred->mode == PN_SSL_MODE_SERVER) ? SECPKG_CRED_INBOUND : SECPKG_CRED_OUTBOUND;
255 *status = AcquireCredentialsHandle(NULL, UNISP_NAME, direction, NULL,
256 &descriptor, NULL, NULL, &tmp_handle, &expiry);
257 if (cred->mode == PN_SSL_MODE_SERVER && *status == SEC_E_OK)
258 cred->cred_handle = tmp_handle;
259
260 return tmp_handle;
261 }
262
263 static bool win_credential_has_certificate(win_credential_t *cred)
264 {
265 if (!cred) return false;
266 return (cred->cert_context != NULL);
267 }
268
269 #define SSL_DATA_SIZE 16384
270 #define SSL_BUF_SIZE (SSL_DATA_SIZE + 5 + 2048 + 32)
271
272 typedef enum { UNKNOWN_CONNECTION, SSL_CONNECTION, CLEAR_CONNECTION } connection_mode_t;
273 typedef struct pn_ssl_session_t pn_ssl_session_t;
274
275 struct pn_ssl_domain_t {
276 CRITICAL_SECTION cslock;
277 int ref_count;
278 pn_ssl_mode_t mode;
279 pn_ssl_verify_mode_t verify_mode;
280 bool allow_unsecured;
281 win_credential_t *cred;
282 };
283
284 typedef enum { CREATED, CLIENT_HELLO, NEGOTIATING,
285 RUNNING, SHUTTING_DOWN, SSL_CLOSED } ssl_state_t;
286
287 struct pni_ssl_t {
288 const char *session_id;
289 const char *peer_hostname;
290 ssl_state_t state;
291
292 bool protocol_detected;
293 bool queued_shutdown;
294 bool ssl_closed; // shutdown complete, or SSL error
295 ssize_t app_input_closed; // error code returned by upper layer process input
296 ssize_t app_output_closed; // error code returned by upper layer process output
297
298 // OpenSSL hides the protocol envelope bytes, SChannel has them in-line.
299 char *sc_outbuf; // SChannel output buffer
300 size_t sc_out_size;
301 size_t sc_out_count;
302 char *network_outp; // network ready bytes within sc_outbuf
303 size_t network_out_pending;
304
305 char *sc_inbuf; // SChannel input buffer
306 size_t sc_in_size;
307 size_t sc_in_count;
308 bool sc_in_incomplete;
309
310 char *inbuf_extra; // Still encrypted data from following Record(s)
311 size_t extra_count;
312
313 char *in_data; // Just the plaintext data part of sc_inbuf, decrypted in place
314 size_t in_data_size;
315 size_t in_data_count;
316 bool decrypting;
317 size_t max_data_size; // computed in the handshake
318
319 pn_bytes_t app_inbytes; // Virtual decrypted datastream, presented to app layer
320
321 pn_buffer_t *inbuf2; // Second input buf if longer contiguous bytes needed
322 bool double_buffered;
323
324 bool sc_input_shutdown;
325
326 CredHandle cred_handle;
327 CtxtHandle ctxt_handle;
328 SecPkgContext_StreamSizes sc_sizes;
329 pn_ssl_mode_t mode;
330 pn_ssl_verify_mode_t verify_mode;
331 win_credential_t *cred;
332 char *subject;
333 };
334
335 static inline pn_transport_t *get_transport_internal(pn_ssl_t *ssl)
336 {
337 // The external pn_sasl_t is really a pointer to the internal pni_transport_t
338 return ((pn_transport_t *)ssl);
339 }
340
341 static inline pni_ssl_t *get_ssl_internal(pn_ssl_t *ssl)
342 {
343 // The external pn_sasl_t is really a pointer to the internal pni_transport_t
344 return ssl ? ((pn_transport_t *)ssl)->ssl : NULL;
345 }
346
347 struct pn_ssl_session_t {
348 const char *id;
349 // TODO
350 pn_ssl_session_t *ssn_cache_next;
351 pn_ssl_session_t *ssn_cache_prev;
352 };
353
354
355 static ssize_t process_input_ssl( pn_transport_t *transport, unsigned int layer, const char *input_data, size_t len);
356 static ssize_t process_output_ssl( pn_transport_t *transport, unsigned int layer, char *input_data, size_t len);
357 static ssize_t process_input_done(pn_transport_t *transport, unsigned int layer, const char *input_data, size_t len);
358 static ssize_t process_output_done(pn_transport_t *transport, unsigned int layer, char *input_data, size_t len);
359 static pn_ssl_session_t *ssn_cache_find( pn_ssl_domain_t *, const char * );
360 static void ssl_session_free( pn_ssl_session_t *);
361 static size_t buffered_output( pn_transport_t *transport );
362 static void start_ssl_shutdown(pn_transport_t *transport);
363 static void rewind_sc_inbuf(pni_ssl_t *ssl);
364 static bool grow_inbuf2(pn_transport_t *ssl, size_t minimum_size);
365 static HRESULT verify_peer(pni_ssl_t *ssl, HCERTSTORE root_store, const char *server_name, bool tracing);
366
367 // @todo: used to avoid littering the code with calls to printf...
368 static void ssl_vlog(pn_transport_t *transport, pn_log_level_t sev, const char *fmt, va_list ap)
369 {
370 pn_logger_t *logger = transport ? &transport->logger : pn_default_logger();
371 if (PN_SHOULD_LOG(logger, PN_SUBSYSTEM_SSL, sev)) {
372 pni_logger_vlogf(logger, PN_SUBSYSTEM_SSL, sev, fmt, ap);
373 }
374 }
375
376 static void ssl_log(pn_transport_t *transport, pn_log_level_t sev, const char *fmt, ...)
377 {
378 va_list ap;
379 va_start(ap, fmt);
380 ssl_vlog(transport, sev, fmt, ap);
381 va_end(ap);
382 }
383
384 // @todo: used to avoid littering the code with calls to printf...
385 static void ssl_log_error(const char *fmt, ...)
386 {
387 va_list ap;
388 va_start(ap, fmt);
389 ssl_vlog(NULL, PN_LEVEL_ERROR, fmt, ap);
390 va_end(ap);
391 }
392
393 static void ssl_log_error_status(HRESULT status, const char *fmt, ...)
394 {
395 char buf[512];
396 va_list ap;
397
398 if (fmt) {
399 va_start(ap, fmt);
400 ssl_vlog(NULL, PN_LEVEL_ERROR, fmt, ap);
401 va_end(ap);
402 }
403
404 if (FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM,
405 0, status, 0, buf, sizeof(buf), 0))
406 ssl_log_error("%s", buf);
407 else
408 ssl_log_error("Internal Windows error: %x for %x", GetLastError(), status);
409 }
410
411 static void ssl_log_clear_data(pn_transport_t *transport, const char *data, size_t len)
412 {
413 PN_LOG_DATA(&transport->logger, PN_SUBSYSTEM_SSL, PN_LEVEL_RAW, "decrypted data", data, len );
414 }
415
416 static size_t _pni_min(size_t a, size_t b)
417 {
418 return (a < b) ? a : b;
419 }
420
421 // unrecoverable SSL failure occured, notify transport and generate error code.
422 static int ssl_failed(pn_transport_t *transport, const char *reason)
423 {
424 char buf[512] = "Unknown error.";
425 if (!reason) {
426 HRESULT status = GetLastError();
427
428 FormatMessage(FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM,
429 0, status, 0, buf, sizeof(buf), 0);
430 reason = buf;
431 }
432 pni_ssl_t *ssl = transport->ssl;
433 ssl->ssl_closed = true;
434 ssl->app_input_closed = ssl->app_output_closed = PN_EOS;
435 ssl->state = SSL_CLOSED;
436 pn_do_error(transport, "amqp:connection:framing-error", "SSL Failure: %s", reason);
437 return PN_EOS;
438 }
439
440 static pn_ssl_session_t *ssn_cache_find( pn_ssl_domain_t *domain, const char *id )
441 {
442 // TODO:
443 return NULL;
444 }
445
446 static void ssl_session_free( pn_ssl_session_t *ssn)
447 {
448 if (ssn) {
449 if (ssn->id) free( (void *)ssn->id );
450 free( ssn );
451 }
452 }
453
454
455 /** Public API - visible to application code */
456
457 bool pn_ssl_present(void)
458 {
459 return true;
460 }
461
462 pn_ssl_domain_t *pn_ssl_domain( pn_ssl_mode_t mode )
463 {
464 switch (mode) {
465 case PN_SSL_MODE_CLIENT:
466 case PN_SSL_MODE_SERVER:
467 break;
468
469 default:
470 ssl_log_error("Invalid mode for pn_ssl_mode_t: %d", mode);
471 return NULL;
472 }
473
474 pn_ssl_domain_t *domain = (pn_ssl_domain_t *) calloc(1, sizeof(pn_ssl_domain_t));
475 if (!domain) return NULL;
476
477 InitializeCriticalSectionAndSpinCount(&domain->cslock, 4000);
478 {
479 csguard(&domain->cslock);
480 domain->ref_count = 1;
481 domain->mode = mode;
482 domain->cred = win_credential(mode);
483 }
484
485 if (pn_ssl_domain_set_trusted_ca_db(domain, "ss:root") != 0) {
486 pn_ssl_domain_free(domain);
487 return NULL;
488 }
489 if (mode == PN_SSL_MODE_CLIENT)
490 domain->verify_mode = PN_SSL_VERIFY_PEER_NAME;
491 return domain;
492 }
493
494 // call with no locks
495 void pn_ssl_domain_free( pn_ssl_domain_t *domain )
496 {
497 if (!domain) return;
498 {
499 csguard g(&domain->cslock);
500 if (--domain->ref_count)
501 return;
502 }
503 {
504 csguard g2(&domain->cred->cslock);
505 if (win_credential_decref(domain->cred)) {
506 g2.release();
507 win_credential_delete(domain->cred);
508 }
509 }
510 DeleteCriticalSection(&domain->cslock);
511 free(domain);
512 }
513
514
515 int pn_ssl_domain_set_credentials( pn_ssl_domain_t *domain,
516 const char *certificate_file,
517 const char *private_key_file,
518 const char *password)
519 {
520 if (!domain) return -1;
521 csguard g(&domain->cslock);
522 csguard g2(&domain->cred->cslock);
523
524 if (win_credential_has_certificate(domain->cred)) {
525 // Need a new win_credential_t to hold new certificate
526 if (win_credential_decref(domain->cred)) {
527 g2.release();
528 win_credential_delete(domain->cred);
529 }
530 domain->cred = win_credential(domain->mode);
531 if (!domain->cred)
532 return -1;
533 }
534 return win_credential_load_cert(domain->cred, certificate_file, private_key_file, password);
535 }
536
537
538 int pn_ssl_domain_set_trusted_ca_db(pn_ssl_domain_t *domain,
539 const char *certificate_db)
540 {
541 if (!domain || !certificate_db) return -1;
542 csguard g(&domain->cslock);
543
544 int ec = 0;
545 HCERTSTORE store = open_cert_db(certificate_db, NULL, &ec);
546 if (!store)
547 return ec;
548
549 csguard g2(&domain->cred->cslock);
550 if (domain->cred->trust_store) {
551 win_credential_t *new_cred = win_credential(domain->mode);
552 if (!new_cred) {
553 CertCloseStore(store, 0);
554 return -1;
555 }
556 new_cred->cert_context = CertDuplicateCertificateContext(domain->cred->cert_context);
557 if (win_credential_decref(domain->cred)) {
558 g2.release();
559 win_credential_delete(domain->cred);
560 }
561 domain->cred = new_cred;
562 }
563
564 domain->cred->trust_store = store;
565 domain->cred->trust_store_name = pn_strdup(certificate_db);
566 return 0;
567 }
568
569
570 int pn_ssl_domain_set_peer_authentication(pn_ssl_domain_t *domain,
571 const pn_ssl_verify_mode_t mode,
572 const char *trusted_CAs)
573 {
574 if (!domain) return -1;
575 csguard g(&domain->cslock);
576 csguard g2(&domain->cred->cslock);
577
578 HCERTSTORE store = 0;
579 bool changed = domain->verify_mode && mode != domain->verify_mode;
580
581 switch (mode) {
582 case PN_SSL_VERIFY_PEER:
583 case PN_SSL_VERIFY_PEER_NAME:
584 if (domain->mode == PN_SSL_MODE_SERVER) {
585 if (!trusted_CAs) {
586 ssl_log_error("Error: a list of trusted CAs must be provided.");
587 return -1;
588 }
589 if (!win_credential_has_certificate(domain->cred)) {
590 ssl_log_error("Error: Server cannot verify peer without configuring a certificate, use pn_ssl_domain_set_credentials()");
591 return -1;
592 }
593 int ec = 0;
594 if (!strcmp(trusted_CAs, domain->cred->trust_store_name)) {
595 changed = true;
596 store = open_cert_db(trusted_CAs, NULL, &ec);
597 if (!store)
598 return ec;
599 }
600 }
601 break;
602
603 case PN_SSL_ANONYMOUS_PEER: // hippie free love mode... :)
604 break;
605
606 default:
607 ssl_log_error("Invalid peer authentication mode given.");
608 return -1;
609 }
610
611 if (changed) {
612 win_credential_t *new_cred = win_credential(domain->mode);
613 if (!new_cred) {
614 if (store)
615 CertCloseStore(store, 0);
616 return -1;
617 }
618 new_cred->cert_context = CertDuplicateCertificateContext(domain->cred->cert_context);
619 new_cred->trust_store = CertDuplicateStore(domain->cred->trust_store);
620 new_cred->trust_store_name = pn_strdup(domain->cred->trust_store_name);
621 if (win_credential_decref(domain->cred)) {
622 g2.release();
623 win_credential_delete(domain->cred);
624 }
625 domain->cred = new_cred;
626 domain->cred->server_CA_certs = store;
627 }
628
629 domain->verify_mode = mode;
630
631 return 0;
632 }
633
634 int pn_ssl_domain_set_ciphers(pn_ssl_domain_t *domain, const char *ciphers)
635 {
636 return PN_ERR;
637 }
638
639 int pn_ssl_domain_set_protocols(pn_ssl_domain_t *domain, const char *protocols)
640 {
641 return PN_ERR;
642 }
643
644 const pn_io_layer_t ssl_layer = {
645 process_input_ssl,
646 process_output_ssl,
647 NULL,
648 NULL,
649 buffered_output
650 };
651
652 const pn_io_layer_t ssl_input_closed_layer = {
653 process_input_done,
654 process_output_ssl,
655 NULL,
656 NULL,
657 buffered_output
658 };
659
660 const pn_io_layer_t ssl_output_closed_layer = {
661 process_input_ssl,
662 process_output_done,
663 NULL,
664 NULL,
665 buffered_output
666 };
667
668 const pn_io_layer_t ssl_closed_layer = {
669 process_input_done,
670 process_output_done,
671 NULL,
672 NULL,
673 buffered_output
674 };
675
676 static pn_ssl_domain_t *default_client_domain = 0;
677 static pn_ssl_domain_t *default_server_domain = 0;
678
679 int pn_ssl_init(pn_ssl_t *ssl0, pn_ssl_domain_t *domain, const char *session_id)
680 {
681 pn_transport_t *transport = get_transport_internal(ssl0);
682 pni_ssl_t *ssl = transport->ssl;
683 if (!ssl) return -1;
684 if (ssl->state != CREATED) return -1;
685
686 if (!domain) {
687 if (transport->server) {
688 if (!default_server_domain) {
689 default_server_domain = pn_ssl_domain(PN_SSL_MODE_SERVER);
690 }
691 domain = default_server_domain;
692 }
693 else {
694 if (!default_client_domain) {
695 default_client_domain = pn_ssl_domain(PN_SSL_MODE_CLIENT);
696 pn_ssl_domain_set_peer_authentication(default_client_domain, PN_SSL_VERIFY_PEER_NAME, NULL);
697 }
698 domain = default_client_domain;
699 }
700 }
701
702 csguard g(&domain->cslock);
703 csguard g2(&domain->cred->cslock);
704 if (session_id && domain->mode == PN_SSL_MODE_CLIENT)
705 ssl->session_id = pn_strdup(session_id);
706
707 // If SSL doesn't specifically allow skipping encryption, require SSL
708 // TODO: This is a probably a stop-gap until allow_unsecured is removed
709 if (!domain->allow_unsecured) transport->encryption_required = true;
710
711 ssl->cred = domain->cred;
712 pn_incref(domain->cred);
713
714 SECURITY_STATUS status = SEC_E_OK;
715 ssl->cred_handle = win_credential_cred_handle(ssl->cred, ssl->session_id, &status);
716 if (status != SEC_E_OK) {
717 ssl_log_error_status(status, "Credentials handle failure");
718 return -1;
719 }
720
721 ssl->state = (domain->mode == PN_SSL_MODE_CLIENT) ? CLIENT_HELLO : NEGOTIATING;
722 ssl->verify_mode = domain->verify_mode;
723 ssl->mode = domain->mode;
724 return 0;
725 }
726
727
728 int pn_ssl_domain_allow_unsecured_client(pn_ssl_domain_t *domain)
729 {
730 if (!domain) return -1;
731 if (domain->mode != PN_SSL_MODE_SERVER) {
732 ssl_log_error("Cannot permit unsecured clients - not a server.");
733 return -1;
734 }
735 domain->allow_unsecured = true;
736 return 0;
737 }
738
739
740 // TODO: This is just an untested guess
741 int pn_ssl_get_ssf(pn_ssl_t *ssl0)
742 {
743 SecPkgContext_ConnectionInfo info;
744
745 pni_ssl_t *ssl = get_ssl_internal(ssl0);
746 if (ssl &&
747 ssl->state == RUNNING &&
748 SecIsValidHandle(&ssl->ctxt_handle) &&
749 QueryContextAttributes(&ssl->ctxt_handle, SECPKG_ATTR_CONNECTION_INFO, &info) == SEC_E_OK) {
750 return info.dwCipherStrength;
751 }
752 return 0;
753 }
754
755 bool pn_ssl_get_cipher_name(pn_ssl_t *ssl0, char *buffer, size_t size )
756 {
757 pni_ssl_t *ssl = get_ssl_internal(ssl0);
758 *buffer = '\0';
759 if (ssl->state != RUNNING || !SecIsValidHandle(&ssl->ctxt_handle))
760 return false;
761 SecPkgContext_ConnectionInfo info;
762 if (QueryContextAttributes(&ssl->ctxt_handle, SECPKG_ATTR_CONNECTION_INFO, &info) == SEC_E_OK) {
763 // TODO: come up with string for all permutations?
764 snprintf( buffer, size, "%x_%x:%x_%x:%x_%x",
765 info.aiExch, info.dwExchStrength,
766 info.aiCipher, info.dwCipherStrength,
767 info.aiHash, info.dwHashStrength);
768 return true;
769 }
770 return false;
771 }
772
773 bool pn_ssl_get_protocol_name(pn_ssl_t *ssl0, char *buffer, size_t size )
774 {
775 pni_ssl_t *ssl = get_ssl_internal(ssl0);
776 *buffer = '\0';
777 if (ssl->state != RUNNING || !SecIsValidHandle(&ssl->ctxt_handle))
778 return false;
779 SecPkgContext_ConnectionInfo info;
780 if (QueryContextAttributes(&ssl->ctxt_handle, SECPKG_ATTR_CONNECTION_INFO, &info) == SEC_E_OK) {
781 if (info.dwProtocol & (SP_PROT_TLS1_CLIENT | SP_PROT_TLS1_SERVER))
782 snprintf(buffer, size, "%s", "TLSv1");
783 // TLSV1.1 and TLSV1.2 are supported as of XP-SP3, but not defined until VS2010
784 else if ((info.dwProtocol & 0x300))
785 snprintf(buffer, size, "%s", "TLSv1.1");
786 else if ((info.dwProtocol & 0xC00))
787 snprintf(buffer, size, "%s", "TLSv1.2");
788 else {
789 ssl_log_error("unexpected protocol %x", info.dwProtocol);
790 return false;
791 }
792 return true;
793 }
794 return false;
795 }
796
797
798 void pn_ssl_free( pn_transport_t *transport)
799 {
800 pni_ssl_t *ssl = transport->ssl;
801 if (!ssl) return;
802 ssl_log( transport, PN_LEVEL_DEBUG, "SSL socket freed." );
803 // clean up Windows per TLS session data before releasing the domain count
804 csguard g(&ssl->cred->cslock);
805 if (SecIsValidHandle(&ssl->ctxt_handle))
806 DeleteSecurityContext(&ssl->ctxt_handle);
807 if (ssl->cred) {
808 if (ssl->mode == PN_SSL_MODE_CLIENT && ssl->session_id == NULL) {
809 // Responsible for unshared handle
810 if (SecIsValidHandle(&ssl->cred_handle))
811 FreeCredentialsHandle(&ssl->cred_handle);
812 }
813 if (win_credential_decref(ssl->cred)) {
814 g.release();
815 win_credential_delete(ssl->cred);
816 }
817 }
818
819 g.release();
820
821 if (ssl->session_id) free((void *)ssl->session_id);
822 if (ssl->peer_hostname) free((void *)ssl->peer_hostname);
823 if (ssl->sc_inbuf) free((void *)ssl->sc_inbuf);
824 if (ssl->sc_outbuf) free((void *)ssl->sc_outbuf);
825 if (ssl->inbuf2) pn_buffer_free(ssl->inbuf2);
826 if (ssl->subject) free(ssl->subject);
827
828 free(ssl);
829 }
830
831 pn_ssl_t *pn_ssl(pn_transport_t *transport)
832 {
833 if (!transport) return NULL;
834 if (transport->ssl) return (pn_ssl_t *)transport;
835
836 pni_ssl_t *ssl = (pni_ssl_t *) calloc(1, sizeof(pni_ssl_t));
837 if (!ssl) return NULL;
838 ssl->sc_out_size = ssl->sc_in_size = SSL_BUF_SIZE;
839
840 ssl->sc_outbuf = (char *)malloc(ssl->sc_out_size);
841 if (!ssl->sc_outbuf) {
842 free(ssl);
843 return NULL;
844 }
845 ssl->sc_inbuf = (char *)malloc(ssl->sc_in_size);
846 if (!ssl->sc_inbuf) {
847 free(ssl->sc_outbuf);
848 free(ssl);
849 return NULL;
850 }
851
852 ssl->inbuf2 = pn_buffer(0);
853 if (!ssl->inbuf2) {
854 free(ssl->sc_inbuf);
855 free(ssl->sc_outbuf);
856 free(ssl);
857 return NULL;
858 }
859
860 transport->ssl = ssl;
861
862 // Set up hostname from any bound connection
863 if (transport->connection) {
864 if (pn_string_size(transport->connection->hostname)) {
865 pn_ssl_set_peer_hostname((pn_ssl_t *) transport, pn_string_get(transport->connection->hostname));
866 }
867 }
868
869 SecInvalidateHandle(&ssl->cred_handle);
870 SecInvalidateHandle(&ssl->ctxt_handle);
871 ssl->state = CREATED;
872 ssl->decrypting = true;
873
874 return (pn_ssl_t *)transport;
875 }
876
877
878 pn_ssl_resume_status_t pn_ssl_resume_status( pn_ssl_t *ssl )
879 {
880 // TODO
881 return PN_SSL_RESUME_UNKNOWN;
882 }
883
884
885 int pn_ssl_set_peer_hostname( pn_ssl_t *ssl0, const char *hostname )
886 {
887 pni_ssl_t *ssl = get_ssl_internal(ssl0);
888 if (!ssl) return -1;
889
890 if (ssl->peer_hostname) free((void *)ssl->peer_hostname);
891 ssl->peer_hostname = NULL;
892 if (hostname) {
893 ssl->peer_hostname = pn_strdup(hostname);
894 if (!ssl->peer_hostname) return -2;
895 }
896 return 0;
897 }
898
899 int pn_ssl_get_peer_hostname( pn_ssl_t *ssl0, char *hostname, size_t *bufsize )
900 {
901 pni_ssl_t *ssl = get_ssl_internal(ssl0);
902 if (!ssl) return -1;
903 if (!ssl->peer_hostname) {
904 *bufsize = 0;
905 if (hostname) *hostname = '\0';
906 return 0;
907 }
908 unsigned len = strlen(ssl->peer_hostname);
909 if (hostname) {
910 if (len >= *bufsize) return -1;
911 strcpy( hostname, ssl->peer_hostname );
912 }
913 *bufsize = len;
914 return 0;
915 }
916
917 const char* pn_ssl_get_remote_subject(pn_ssl_t *ssl0)
918 {
919 // RFC 2253 compliant, but differs from openssl's subject string with space separators and
920 // ordering of multicomponent RDNs. Made to work as similarly as possible with choice of flags.
921 pni_ssl_t *ssl = get_ssl_internal(ssl0);
922 if (!ssl || !SecIsValidHandle(&ssl->ctxt_handle))
923 return NULL;
924 if (!ssl->subject) {
925 SECURITY_STATUS status;
926 PCCERT_CONTEXT peer_cc = 0;
927 status = QueryContextAttributes(&ssl->ctxt_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &peer_cc);
928 if (status != SEC_E_OK) {
929 ssl_log_error_status(status, "can't obtain remote certificate subject");
930 return NULL;
931 }
932 DWORD flags = CERT_X500_NAME_STR | CERT_NAME_STR_REVERSE_FLAG;
933 DWORD strlen = CertNameToStr(peer_cc->dwCertEncodingType, &peer_cc->pCertInfo->Subject,
934 flags, NULL, 0);
935 if (strlen > 0) {
936 ssl->subject = (char*) malloc(strlen);
937 if (ssl->subject) {
938 DWORD len = CertNameToStr(peer_cc->dwCertEncodingType, &peer_cc->pCertInfo->Subject,
939 flags, ssl->subject, strlen);
940 if (len != strlen) {
941 free(ssl->subject);
942 ssl->subject = NULL;
943 ssl_log_error("pn_ssl_get_remote_subject failure in CertNameToStr");
944 }
945 }
946 }
947 CertFreeCertificateContext(peer_cc);
948 }
949 return ssl->subject;
950 }
951
952
953 /** SChannel specific: */
954
955 const char *tls_version_check(pni_ssl_t *ssl)
956 {
957 SecPkgContext_ConnectionInfo info;
958 QueryContextAttributes(&ssl->ctxt_handle, SECPKG_ATTR_CONNECTION_INFO, &info);
959 // Ascending bit patterns denote newer SSL/TLS protocol versions.
960 // SP_PROT_TLS1_0_SERVER is not defined until VS2010.
961 return (info.dwProtocol < SP_PROT_TLS1_SERVER) ?
962 "peer does not support TLS 1.0 security" : NULL;
963 }
964
965 static void ssl_encrypt(pn_transport_t *transport, char *app_data, size_t count)
966 {
967 pni_ssl_t *ssl = transport->ssl;
968
969 // Get SChannel to encrypt exactly one Record.
970 SecBuffer buffs[4];
971 buffs[0].cbBuffer = ssl->sc_sizes.cbHeader;
972 buffs[0].BufferType = SECBUFFER_STREAM_HEADER;
973 buffs[0].pvBuffer = ssl->sc_outbuf;
974 buffs[1].cbBuffer = count;
975 buffs[1].BufferType = SECBUFFER_DATA;
976 buffs[1].pvBuffer = app_data;
977 buffs[2].cbBuffer = ssl->sc_sizes.cbTrailer;
978 buffs[2].BufferType = SECBUFFER_STREAM_TRAILER;
979 buffs[2].pvBuffer = &app_data[count];
980 buffs[3].cbBuffer = 0;
981 buffs[3].BufferType = SECBUFFER_EMPTY;
982 buffs[3].pvBuffer = 0;
983 SecBufferDesc buff_desc;
984 buff_desc.ulVersion = SECBUFFER_VERSION;
985 buff_desc.cBuffers = 4;
986 buff_desc.pBuffers = buffs;
987 SECURITY_STATUS status = EncryptMessage(&ssl->ctxt_handle, 0, &buff_desc, 0);
988 assert(status == SEC_E_OK);
989
990 // EncryptMessage encrypts the data in place. The header and trailer
991 // areas were reserved previously and must now be included in the updated
992 // count of bytes to write to the peer.
993 ssl->sc_out_count = buffs[0].cbBuffer + buffs[1].cbBuffer + buffs[2].cbBuffer;
994 ssl->network_outp = ssl->sc_outbuf;
995 ssl->network_out_pending = ssl->sc_out_count;
996 ssl_log(transport, PN_LEVEL_TRACE, "ssl_encrypt %d network bytes", ssl->network_out_pending);
997 }
998
999 // Returns true if decryption succeeded (even for empty content)
1000 static bool ssl_decrypt(pn_transport_t *transport)
1001 {
1002 pni_ssl_t *ssl = transport->ssl;
1003 // Get SChannel to decrypt input. May have an incomplete Record,
1004 // exactly one, or more than one. Check also for session ending,
1005 // session renegotiation.
1006
1007 SecBuffer recv_buffs[4];
1008 recv_buffs[0].cbBuffer = ssl->sc_in_count;
1009 recv_buffs[0].BufferType = SECBUFFER_DATA;
1010 recv_buffs[0].pvBuffer = ssl->sc_inbuf;
1011 recv_buffs[1].BufferType = SECBUFFER_EMPTY;
1012 recv_buffs[2].BufferType = SECBUFFER_EMPTY;
1013 recv_buffs[3].BufferType = SECBUFFER_EMPTY;
1014 SecBufferDesc buff_desc;
1015 buff_desc.ulVersion = SECBUFFER_VERSION;
1016 buff_desc.cBuffers = 4;
1017 buff_desc.pBuffers = recv_buffs;
1018 SECURITY_STATUS status = DecryptMessage(&ssl->ctxt_handle, &buff_desc, 0, NULL);
1019
1020 if (status == SEC_E_INCOMPLETE_MESSAGE) {
1021 // Less than a full Record, come back later with more network data
1022 ssl->sc_in_incomplete = true;
1023 return false;
1024 }
1025
1026 ssl->decrypting = false;
1027
1028 if (status != SEC_E_OK) {
1029 rewind_sc_inbuf(ssl);
1030 switch (status) {
1031 case SEC_I_CONTEXT_EXPIRED:
1032 // TLS shutdown alert record. Ignore all subsequent input.
1033 ssl->state = SHUTTING_DOWN;
1034 ssl->sc_input_shutdown = true;
1035 return false;
1036
1037 case SEC_I_RENEGOTIATE:
1038 ssl_log_error("unexpected TLS renegotiation");
1039 // TODO. Fall through for now.
1040 default:
1041 ssl_failed(transport, 0);
1042 return false;
1043 }
1044 }
1045
1046 ssl->decrypting = false;
1047 // have a decrypted Record and possible (still-encrypted) data of
1048 // one (or more) later Recordss. Adjust pointers accordingly.
1049 for (int i = 0; i < 4; i++) {
1050 switch (recv_buffs[i].BufferType) {
1051 case SECBUFFER_DATA:
1052 ssl->in_data = (char *) recv_buffs[i].pvBuffer;
1053 ssl->in_data_size = ssl->in_data_count = recv_buffs[i].cbBuffer;
1054 break;
1055 case SECBUFFER_EXTRA:
1056 ssl->inbuf_extra = (char *)recv_buffs[i].pvBuffer;
1057 ssl->extra_count = recv_buffs[i].cbBuffer;
1058 break;
1059 default:
1060 // SECBUFFER_STREAM_HEADER:
1061 // SECBUFFER_STREAM_TRAILER:
1062 break;
1063 }
1064 }
1065 return true;
1066 }
1067
1068 static void client_handshake_init(pn_transport_t *transport)
1069 {
1070 pni_ssl_t *ssl = transport->ssl;
1071 // Tell SChannel to create the first handshake token (ClientHello)
1072 // and place it in sc_outbuf
1073 SEC_CHAR *host = (SEC_CHAR *)(ssl->peer_hostname);
1074 ULONG ctxt_requested = ISC_REQ_STREAM | ISC_REQ_USE_SUPPLIED_CREDS | ISC_REQ_EXTENDED_ERROR;
1075 ULONG ctxt_attrs;
1076
1077 SecBuffer send_buffs[2];
1078 send_buffs[0].cbBuffer = ssl->sc_out_size;
1079 send_buffs[0].BufferType = SECBUFFER_TOKEN;
1080 send_buffs[0].pvBuffer = ssl->sc_outbuf;
1081 send_buffs[1].cbBuffer = 0;
1082 send_buffs[1].BufferType = SECBUFFER_EMPTY;
1083 send_buffs[1].pvBuffer = 0;
1084 SecBufferDesc send_buff_desc;
1085 send_buff_desc.ulVersion = SECBUFFER_VERSION;
1086 send_buff_desc.cBuffers = 2;
1087 send_buff_desc.pBuffers = send_buffs;
1088 csguard g(&ssl->cred->cslock);
1089 SECURITY_STATUS status = InitializeSecurityContext(&ssl->cred_handle,
1090 NULL, host, ctxt_requested, 0, 0, NULL, 0,
1091 &ssl->ctxt_handle, &send_buff_desc,
1092 &ctxt_attrs, NULL);
1093
1094 if (status == SEC_I_CONTINUE_NEEDED) {
1095 ssl->sc_out_count = send_buffs[0].cbBuffer;
1096 ssl->network_out_pending = ssl->sc_out_count;
1097 // the token is the whole quantity to send
1098 ssl->network_outp = ssl->sc_outbuf;
1099 ssl_log(transport, PN_LEVEL_TRACE, "Sending client hello %d bytes", ssl->network_out_pending);
1100 } else {
1101 ssl_log_error_status(status, "InitializeSecurityContext failed");
1102 ssl_failed(transport, 0);
1103 }
1104 }
1105
1106 static void client_handshake( pn_transport_t* transport) {
1107 pni_ssl_t *ssl = transport->ssl;
1108 // Feed SChannel ongoing responses from the server until the handshake is complete.
1109 SEC_CHAR *host = (SEC_CHAR *)(ssl->peer_hostname);
1110 ULONG ctxt_requested = ISC_REQ_STREAM | ISC_REQ_USE_SUPPLIED_CREDS;
1111 ULONG ctxt_attrs;
1112 size_t max = 0;
1113
1114 // token_buffs describe the buffer that's coming in. It should have
1115 // a token from the SSL server, or empty if sending final shutdown alert.
1116 bool shutdown = ssl->state == SHUTTING_DOWN;
1117 SecBuffer token_buffs[2];
1118 token_buffs[0].cbBuffer = shutdown ? 0 : ssl->sc_in_count;
1119 token_buffs[0].BufferType = SECBUFFER_TOKEN;
1120 token_buffs[0].pvBuffer = shutdown ? 0 : ssl->sc_inbuf;
1121 token_buffs[1].cbBuffer = 0;
1122 token_buffs[1].BufferType = SECBUFFER_EMPTY;
1123 token_buffs[1].pvBuffer = 0;
1124 SecBufferDesc token_buff_desc;
1125 token_buff_desc.ulVersion = SECBUFFER_VERSION;
1126 token_buff_desc.cBuffers = 2;
1127 token_buff_desc.pBuffers = token_buffs;
1128
1129 // send_buffs will hold information to forward to the peer.
1130 SecBuffer send_buffs[2];
1131 send_buffs[0].cbBuffer = ssl->sc_out_size;
1132 send_buffs[0].BufferType = SECBUFFER_TOKEN;
1133 send_buffs[0].pvBuffer = ssl->sc_outbuf;
1134 send_buffs[1].cbBuffer = 0;
1135 send_buffs[1].BufferType = SECBUFFER_EMPTY;
1136 send_buffs[1].pvBuffer = 0;
1137 SecBufferDesc send_buff_desc;
1138 send_buff_desc.ulVersion = SECBUFFER_VERSION;
1139 send_buff_desc.cBuffers = 2;
1140 send_buff_desc.pBuffers = send_buffs;
1141
1142 SECURITY_STATUS status;
1143 {
1144 csguard g(&ssl->cred->cslock);
1145 status = InitializeSecurityContext(&ssl->cred_handle,
1146 &ssl->ctxt_handle, host, ctxt_requested, 0, 0,
1147 &token_buff_desc, 0, NULL, &send_buff_desc,
1148 &ctxt_attrs, NULL);
1149 }
1150
1151 switch (status) {
1152 case SEC_E_INCOMPLETE_MESSAGE:
1153 // Not enough - get more data from the server then try again.
1154 // Leave input buffers untouched.
1155 ssl_log(transport, PN_LEVEL_TRACE, "client handshake: incomplete record");
1156 ssl->sc_in_incomplete = true;
1157 return;
1158
1159 case SEC_I_CONTINUE_NEEDED:
1160 // Successful handshake step, requiring data to be sent to peer.
1161 ssl->sc_out_count = send_buffs[0].cbBuffer;
1162 // the token is the whole quantity to send
1163 ssl->network_out_pending = ssl->sc_out_count;
1164 ssl->network_outp = ssl->sc_outbuf;
1165 ssl_log(transport, PN_LEVEL_DEBUG, "client handshake token %d bytes", ssl->network_out_pending);
1166 break;
1167
1168 case SEC_E_OK:
1169 // Handshake complete.
1170 if (shutdown) {
1171 if (send_buffs[0].cbBuffer > 0) {
1172 ssl->sc_out_count = send_buffs[0].cbBuffer;
1173 // the token is the whole quantity to send
1174 ssl->network_out_pending = ssl->sc_out_count;
1175 ssl->network_outp = ssl->sc_outbuf;
1176 ssl_log(transport, PN_LEVEL_DEBUG, "client shutdown token %d bytes", ssl->network_out_pending);
1177 } else {
1178 ssl->state = SSL_CLOSED;
1179 }
1180 // we didn't touch sc_inbuf, no need to reset
1181 return;
1182 }
1183 if (send_buffs[0].cbBuffer != 0) {
1184 ssl_failed(transport, "unexpected final server token");
1185 break;
1186 }
1187 if (const char *err = tls_version_check(ssl)) {
1188 ssl_failed(transport, err);
1189 break;
1190 }
1191 if (ssl->verify_mode == PN_SSL_VERIFY_PEER || ssl->verify_mode == PN_SSL_VERIFY_PEER_NAME) {
1192 bool tracing = PN_SHOULD_LOG(&transport->logger, PN_SUBSYSTEM_SSL, PN_LEVEL_TRACE);
1193 HRESULT ec = verify_peer(ssl, ssl->cred->trust_store, ssl->peer_hostname, tracing);
1194 if (ec) {
1195 if (ssl->peer_hostname)
1196 ssl_log_error_status(ec, "certificate verification failed for host %s", ssl->peer_hostname);
1197 else
1198 ssl_log_error_status(ec, "certificate verification failed");
1199 ssl_failed(transport, "TLS certificate verification error");
1200 break;
1201 }
1202 }
1203
1204 if (token_buffs[1].BufferType == SECBUFFER_EXTRA && token_buffs[1].cbBuffer > 0) {
1205 // This seems to work but not documented, plus logic differs from decrypt message
1206 // since the pvBuffer value is not set. Grrr.
1207 ssl->extra_count = token_buffs[1].cbBuffer;
1208 ssl->inbuf_extra = ssl->sc_inbuf + (ssl->sc_in_count - ssl->extra_count);
1209 }
1210
1211 QueryContextAttributes(&ssl->ctxt_handle,
1212 SECPKG_ATTR_STREAM_SIZES, &ssl->sc_sizes);
1213 max = ssl->sc_sizes.cbMaximumMessage + ssl->sc_sizes.cbHeader + ssl->sc_sizes.cbTrailer;
1214 if (max > ssl->sc_out_size) {
1215 ssl_log_error("Buffer size mismatch have %d, need %d", (int) ssl->sc_out_size, (int) max);
1216 ssl->state = SHUTTING_DOWN;
1217 ssl->app_input_closed = ssl->app_output_closed = PN_ERR;
1218 start_ssl_shutdown(transport);
1219 pn_do_error(transport, "amqp:connection:framing-error", "SSL Failure: buffer size");
1220 break;
1221 }
1222
1223 ssl->state = RUNNING;
1224 ssl->max_data_size = max - ssl->sc_sizes.cbHeader - ssl->sc_sizes.cbTrailer;
1225 ssl_log(transport, PN_LEVEL_DEBUG, "client handshake successful %d max record size", max);
1226 break;
1227
1228 case SEC_I_CONTEXT_EXPIRED:
1229 // ended before we got going
1230 default:
1231 ssl_log(transport, PN_LEVEL_ERROR, "client handshake failed %d", (int) status);
1232 ssl_failed(transport, 0);
1233 break;
1234 }
1235
1236 if (token_buffs[1].BufferType == SECBUFFER_EXTRA && token_buffs[1].cbBuffer > 0 &&
1237 !ssl->ssl_closed) {
1238 // remaining data after the consumed TLS record(s)
1239 ssl->extra_count = token_buffs[1].cbBuffer;
1240 ssl->inbuf_extra = ssl->sc_inbuf + (ssl->sc_in_count - ssl->extra_count);
1241 }
1242
1243 ssl->decrypting = false;
1244 rewind_sc_inbuf(ssl);
1245 }
1246
1247
1248 static void server_handshake(pn_transport_t* transport)
1249 {
1250 pni_ssl_t *ssl = transport->ssl;
1251 if (!ssl->protocol_detected) {
1252 // SChannel fails less aggressively than openssl on client hello, causing hangs
1253 // waiting for more bytes. Help out here.
1254 pni_protocol_type_t type = pni_sniff_header(ssl->sc_inbuf, ssl->sc_in_count);
1255 if (type == PNI_PROTOCOL_INSUFFICIENT) {
1256 ssl_log(transport, PN_LEVEL_DEBUG, "server handshake: incomplete record");
1257 ssl->sc_in_incomplete = true;
1258 return;
1259 } else {
1260 ssl->protocol_detected = true;
1261 if (type != PNI_PROTOCOL_SSL) {
1262 ssl_failed(transport, "bad client hello");
1263 ssl->decrypting = false;
1264 rewind_sc_inbuf(ssl);
1265 return;
1266 }
1267 }
1268 }
1269
1270 // Feed SChannel ongoing handshake records from the client until the handshake is complete.
1271 ULONG ctxt_requested = ASC_REQ_STREAM | ASC_REQ_EXTENDED_ERROR;
1272 if (ssl->verify_mode == PN_SSL_VERIFY_PEER || ssl->verify_mode == PN_SSL_VERIFY_PEER_NAME)
1273 ctxt_requested |= ASC_REQ_MUTUAL_AUTH;
1274 ULONG ctxt_attrs;
1275 size_t max = 0;
1276
1277 // token_buffs describe the buffer that's coming in. It should have
1278 // a token from the SSL client except if shutting down or renegotiating.
1279 bool shutdown = ssl->state == SHUTTING_DOWN;
1280 SecBuffer token_buffs[2];
1281 token_buffs[0].cbBuffer = shutdown ? 0 : ssl->sc_in_count;
1282 token_buffs[0].BufferType = SECBUFFER_TOKEN;
1283 token_buffs[0].pvBuffer = shutdown ? 0 : ssl->sc_inbuf;
1284 token_buffs[1].cbBuffer = 0;
1285 token_buffs[1].BufferType = SECBUFFER_EMPTY;
1286 token_buffs[1].pvBuffer = 0;
1287 SecBufferDesc token_buff_desc;
1288 token_buff_desc.ulVersion = SECBUFFER_VERSION;
1289 token_buff_desc.cBuffers = 2;
1290 token_buff_desc.pBuffers = token_buffs;
1291
1292 // send_buffs will hold information to forward to the peer.
1293 SecBuffer send_buffs[2];
1294 send_buffs[0].cbBuffer = ssl->sc_out_size;
1295 send_buffs[0].BufferType = SECBUFFER_TOKEN;
1296 send_buffs[0].pvBuffer = ssl->sc_outbuf;
1297 send_buffs[1].cbBuffer = 0;
1298 send_buffs[1].BufferType = SECBUFFER_EMPTY;
1299 send_buffs[1].pvBuffer = 0;
1300 SecBufferDesc send_buff_desc;
1301 send_buff_desc.ulVersion = SECBUFFER_VERSION;
1302 send_buff_desc.cBuffers = 2;
1303 send_buff_desc.pBuffers = send_buffs;
1304 PCtxtHandle ctxt_handle_ptr = (SecIsValidHandle(&ssl->ctxt_handle)) ? &ssl->ctxt_handle : 0;
1305
1306 SECURITY_STATUS status;
1307 {
1308 csguard g(&ssl->cred->cslock);
1309 status = AcceptSecurityContext(&ssl->cred_handle, ctxt_handle_ptr,
1310 &token_buff_desc, ctxt_requested, 0, &ssl->ctxt_handle,
1311 &send_buff_desc, &ctxt_attrs, NULL);
1312 }
1313 bool outbound_token = false;
1314 switch(status) {
1315 case SEC_E_INCOMPLETE_MESSAGE:
1316 // Not enough - get more data from the client then try again.
1317 // Leave input buffers untouched.
1318 ssl_log(transport, PN_LEVEL_DEBUG, "server handshake: incomplete record");
1319 ssl->sc_in_incomplete = true;
1320 return;
1321
1322 case SEC_I_CONTINUE_NEEDED:
1323 outbound_token = true;
1324 break;
1325
1326 case SEC_E_OK:
1327 // Handshake complete.
1328 if (shutdown) {
1329 if (send_buffs[0].cbBuffer > 0) {
1330 ssl->sc_out_count = send_buffs[0].cbBuffer;
1331 // the token is the whole quantity to send
1332 ssl->network_out_pending = ssl->sc_out_count;
1333 ssl->network_outp = ssl->sc_outbuf;
1334 ssl_log(transport, PN_LEVEL_DEBUG, "server shutdown token %d bytes", ssl->network_out_pending);
1335 } else {
1336 ssl->state = SSL_CLOSED;
1337 }
1338 // we didn't touch sc_inbuf, no need to reset
1339 return;
1340 }
1341 if (const char *err = tls_version_check(ssl)) {
1342 ssl_failed(transport, err);
1343 break;
1344 }
1345 // Handshake complete.
1346
1347 if (ssl->verify_mode == PN_SSL_VERIFY_PEER || ssl->verify_mode == PN_SSL_VERIFY_PEER_NAME) {
1348 bool tracing = PN_SHOULD_LOG(&transport->logger, PN_SUBSYSTEM_SSL, PN_LEVEL_TRACE);
1349 HRESULT ec = verify_peer(ssl, ssl->cred->trust_store, NULL, tracing);
1350 if (ec) {
1351 ssl_log_error_status(ec, "certificate verification failed");
1352 ssl_failed(transport, "certificate verification error");
1353 break;
1354 }
1355 }
1356
1357 QueryContextAttributes(&ssl->ctxt_handle,
1358 SECPKG_ATTR_STREAM_SIZES, &ssl->sc_sizes);
1359 max = ssl->sc_sizes.cbMaximumMessage + ssl->sc_sizes.cbHeader + ssl->sc_sizes.cbTrailer;
1360 if (max > ssl->sc_out_size) {
1361 ssl_log_error("Buffer size mismatch have %d, need %d", (int) ssl->sc_out_size, (int) max);
1362 ssl->state = SHUTTING_DOWN;
1363 ssl->app_input_closed = ssl->app_output_closed = PN_ERR;
1364 start_ssl_shutdown(transport);
1365 pn_do_error(transport, "amqp:connection:framing-error", "SSL Failure: buffer size");
1366 break;
1367 }
1368
1369 if (send_buffs[0].cbBuffer != 0)
1370 outbound_token = true;
1371
1372 ssl->state = RUNNING;
1373 ssl->max_data_size = max - ssl->sc_sizes.cbHeader - ssl->sc_sizes.cbTrailer;
1374 ssl_log(transport, PN_LEVEL_DEBUG, "server handshake successful %d max record size", max);
1375 break;
1376
1377 case SEC_E_ALGORITHM_MISMATCH:
1378 ssl_log(transport, PN_LEVEL_WARNING, "server handshake failed: no common algorithm");
1379 ssl_failed(transport, "server handshake failed: no common algorithm");
1380 break;
1381
1382 case SEC_I_CONTEXT_EXPIRED:
1383 // ended before we got going
1384 default:
1385 ssl_log(transport, PN_LEVEL_ERROR, "server handshake failed %d", (int) status);
1386 ssl_failed(transport, 0);
1387 break;
1388 }
1389
1390 if (outbound_token) {
1391 // Successful handshake step, requiring data to be sent to peer.
1392 assert(ssl->network_out_pending == 0);
1393 ssl->sc_out_count = send_buffs[0].cbBuffer;
1394 // the token is the whole quantity to send
1395 ssl->network_out_pending = ssl->sc_out_count;
1396 ssl->network_outp = ssl->sc_outbuf;
1397 ssl_log(transport, PN_LEVEL_DEBUG, "server handshake token %d bytes", ssl->network_out_pending);
1398 }
1399
1400 if (token_buffs[1].BufferType == SECBUFFER_EXTRA && token_buffs[1].cbBuffer > 0 &&
1401 !ssl->ssl_closed) {
1402 // remaining data after the consumed TLS record(s)
1403 ssl->extra_count = token_buffs[1].cbBuffer;
1404 ssl->inbuf_extra = ssl->sc_inbuf + (ssl->sc_in_count - ssl->extra_count);
1405 }
1406
1407 ssl->decrypting = false;
1408 rewind_sc_inbuf(ssl);
1409 }
1410
1411 static void ssl_handshake(pn_transport_t* transport) {
1412 if (transport->ssl->mode == PN_SSL_MODE_CLIENT)
1413 client_handshake(transport);
1414 else {
1415 server_handshake(transport);
1416 }
1417 }
1418
1419 static bool grow_inbuf2(pn_transport_t *transport, size_t minimum_size) {
1420 pni_ssl_t *ssl = transport->ssl;
1421 size_t old_capacity = pn_buffer_capacity(ssl->inbuf2);
1422 size_t new_capacity = old_capacity ? old_capacity * 2 : 1024;
1423
1424 while (new_capacity < minimum_size)
1425 new_capacity *= 2;
1426
1427 uint32_t max_frame = pn_transport_get_max_frame(transport);
1428 if (max_frame != 0) {
1429 if (old_capacity >= max_frame) {
1430 // already big enough
1431 ssl_log(transport, PN_LEVEL_ERROR, "Application expecting %d bytes (> negotiated maximum frame)", new_capacity);
1432 ssl_failed(transport, "TLS: transport maximum frame size error");
1433 return false;
1434 }
1435 }
1436
1437 size_t extra_bytes = new_capacity - pn_buffer_size(ssl->inbuf2);
1438 int err = pn_buffer_ensure(ssl->inbuf2, extra_bytes);
1439 if (err) {
1440 ssl_log(transport, PN_LEVEL_ERROR, "TLS memory allocation failed for %d bytes", max_frame);
1441 ssl_failed(transport, "TLS memory allocation failed");
1442 return false;
1443 }
1444 return true;
1445 }
1446
1447
1448 // Peer initiated a session end by sending us a shutdown alert (and we should politely
1449 // reciprocate), or else we are initiating the session end (and will not bother to wait
1450 // for the peer shutdown alert). Stop processing input immediately, and stop processing
1451 // output once this is sent.
1452
1453 static void start_ssl_shutdown(pn_transport_t *transport)
1454 {
1455 pni_ssl_t *ssl = transport->ssl;
1456 assert(ssl->network_out_pending == 0);
1457 if (ssl->queued_shutdown)
1458 return;
1459 ssl->queued_shutdown = true;
1460 ssl_log(transport, PN_LEVEL_INFO, "Shutting down SSL connection...");
1461
1462 DWORD shutdown = SCHANNEL_SHUTDOWN;
1463 SecBuffer shutBuff;
1464 shutBuff.cbBuffer = sizeof(DWORD);
1465 shutBuff.BufferType = SECBUFFER_TOKEN;
1466 shutBuff.pvBuffer = &shutdown;
1467 SecBufferDesc desc;
1468 desc.ulVersion = SECBUFFER_VERSION;
1469 desc.cBuffers = 1;
1470 desc.pBuffers = &shutBuff;
1471 ApplyControlToken(&ssl->ctxt_handle, &desc);
1472
1473 // Next handshake will generate the shutdown alert token
1474 ssl_handshake(transport);
1475 }
1476
1477 static void rewind_sc_inbuf(pni_ssl_t *ssl)
1478 {
1479 // Decrypted bytes have been drained or double buffered. Prepare for the next SSL Record.
1480 assert(ssl->in_data_count == 0);
1481 if (ssl->decrypting)
1482 return;
1483 ssl->decrypting = true;
1484 if (ssl->inbuf_extra) {
1485 // A previous read picked up more than one Record. Move it to the beginning.
1486 memmove(ssl->sc_inbuf, ssl->inbuf_extra, ssl->extra_count);
1487 ssl->sc_in_count = ssl->extra_count;
1488 ssl->inbuf_extra = 0;
1489 ssl->extra_count = 0;
1490 } else {
1491 ssl->sc_in_count = 0;
1492 }
1493 }
1494
1495 static void app_inbytes_add(pn_transport_t *transport)
1496 {
1497 pni_ssl_t *ssl = transport->ssl;
1498 if (!ssl->app_inbytes.start) {
1499 ssl->app_inbytes.start = ssl->in_data;
1500 ssl->app_inbytes.size = ssl->in_data_count;
1501 return;
1502 }
1503
1504 if (ssl->double_buffered) {
1505 if (pn_buffer_available(ssl->inbuf2) == 0) {
1506 if (!grow_inbuf2(transport, 1024))
1507 // could not add room
1508 return;
1509 }
1510 size_t count = _pni_min(ssl->in_data_count, pn_buffer_available(ssl->inbuf2));
1511 pn_buffer_append(ssl->inbuf2, ssl->in_data, count);
1512 ssl->in_data += count;
1513 ssl->in_data_count -= count;
1514 ssl->app_inbytes = pn_buffer_bytes(ssl->inbuf2);
1515 } else {
1516 assert(ssl->app_inbytes.size == 0);
1517 ssl->app_inbytes.start = ssl->in_data;
1518 ssl->app_inbytes.size = ssl->in_data_count;
1519 }
1520 }
1521
1522
1523 static void app_inbytes_progress(pn_transport_t *transport, size_t minimum)
1524 {
1525 pni_ssl_t *ssl = transport->ssl;
1526 // Make more decrypted data available, if possible. Otherwise, move
1527 // unread bytes to front of inbuf2 to make room for next bulk decryption.
1528 // SSL may have chopped up data that app layer expects to be
1529 // contiguous. Start, continue or stop double buffering here.
1530 if (ssl->double_buffered) {
1531 if (ssl->app_inbytes.size == 0) {
1532 // no straggler bytes, optimistically stop for now
1533 ssl->double_buffered = false;
1534 pn_buffer_clear(ssl->inbuf2);
1535 ssl->app_inbytes.start = ssl->in_data;
1536 ssl->app_inbytes.size = ssl->in_data_count;
1537 } else {
1538 pn_bytes_t ib2 = pn_buffer_bytes(ssl->inbuf2);
1539 assert(ssl->app_inbytes.size <= ib2.size);
1540 size_t consumed = ib2.size - ssl->app_inbytes.size;
1541 if (consumed > 0) {
1542 memmove((void *)ib2.start, ib2.start + consumed, ssl->app_inbytes.size);
1543 pn_buffer_trim(ssl->inbuf2, 0, consumed);
1544 }
1545 if (!pn_buffer_available(ssl->inbuf2)) {
1546 if (!grow_inbuf2(transport, minimum))
1547 // could not add room
1548 return;
1549 }
1550 size_t count = _pni_min(ssl->in_data_count, pn_buffer_available(ssl->inbuf2));
1551 pn_buffer_append(ssl->inbuf2, ssl->in_data, count);
1552 ssl->in_data += count;
1553 ssl->in_data_count -= count;
1554 ssl->app_inbytes = pn_buffer_bytes(ssl->inbuf2);
1555 }
1556 } else {
1557 if (ssl->app_inbytes.size) {
1558 // start double buffering the left over bytes
1559 ssl->double_buffered = true;
1560 pn_buffer_clear(ssl->inbuf2);
1561 if (!pn_buffer_available(ssl->inbuf2)) {
1562 if (!grow_inbuf2(transport, minimum))
1563 // could not add room
1564 return;
1565 }
1566 size_t count = _pni_min(ssl->in_data_count, pn_buffer_available(ssl->inbuf2));
1567 pn_buffer_append(ssl->inbuf2, ssl->in_data, count);
1568 ssl->in_data += count;
1569 ssl->in_data_count -= count;
1570 ssl->app_inbytes = pn_buffer_bytes(ssl->inbuf2);
1571 } else {
1572 // already pointing at all available bytes until next decrypt
1573 }
1574 }
1575 if (ssl->in_data_count == 0)
1576 rewind_sc_inbuf(ssl);
1577 }
1578
1579
1580 static void app_inbytes_advance(pn_transport_t *transport, size_t consumed)
1581 {
1582 pni_ssl_t *ssl = transport->ssl;
1583 if (consumed == 0) {
1584 // more contiguous bytes required
1585 app_inbytes_progress(transport, ssl->app_inbytes.size + 1);
1586 return;
1587 }
1588 assert(consumed <= ssl->app_inbytes.size);
1589 ssl->app_inbytes.start += consumed;
1590 ssl->app_inbytes.size -= consumed;
1591 if (!ssl->double_buffered) {
1592 ssl->in_data += consumed;
1593 ssl->in_data_count -= consumed;
1594 }
1595 if (ssl->app_inbytes.size == 0)
1596 app_inbytes_progress(transport, 0);
1597 }
1598
1599 static void read_closed(pn_transport_t *transport, unsigned int layer, ssize_t error)
1600 {
1601 pni_ssl_t *ssl = transport->ssl;
1602 if (ssl->app_input_closed)
1603 return;
1604 if (ssl->state == RUNNING && !error) {
1605 // Signal end of stream
1606 ssl->app_input_closed = transport->io_layers[layer+1]->process_input(transport, layer+1, ssl->app_inbytes.start, 0);
1607 }
1608 if (!ssl->app_input_closed)
1609 ssl->app_input_closed = error ? error : PN_ERR;
1610
1611 if (ssl->app_output_closed) {
1612 // both sides of app closed, and no more app output pending:
1613 ssl->state = SHUTTING_DOWN;
1614 if (ssl->network_out_pending == 0 && !ssl->queued_shutdown) {
1615 start_ssl_shutdown(transport);
1616 }
1617 }
1618 }
1619
1620
1621 // Read up to "available" bytes from the network, decrypt it and pass plaintext to application.
1622
1623 static ssize_t process_input_ssl(pn_transport_t *transport, unsigned int layer, const char *input_data, size_t available)
1624 {
1625 pni_ssl_t *ssl = transport->ssl;
1626 ssl_log( transport, PN_LEVEL_TRACE, "process_input_ssl( data size=%d )",available );
1627 ssize_t consumed = 0;
1628 ssize_t forwarded = 0;
1629 bool new_app_input;
1630
1631 if (available == 0) {
1632 // No more inbound network data
1633 read_closed(transport, layer, 0);
1634 return 0;
1635 }
1636
1637 do {
1638 if (ssl->sc_input_shutdown) {
1639 // TLS protocol shutdown detected on input, so we are done.
1640 read_closed(transport, layer, 0);
1641 return PN_EOS;
1642 }
1643
1644 // sc_inbuf should be ready for new or additional network encrypted bytes.
1645 // i.e. no straggling decrypted bytes pending.
1646 assert(ssl->in_data_count == 0 && ssl->decrypting);
1647 new_app_input = false;
1648 size_t count;
1649
1650 if (ssl->state != RUNNING) {
1651 count = _pni_min(ssl->sc_in_size - ssl->sc_in_count, available);
1652 } else {
1653 // look for TLS record boundaries
1654 if (ssl->sc_in_count < 5) {
1655 ssl->sc_in_incomplete = true;
1656 size_t hc = _pni_min(available, 5 - ssl->sc_in_count);
1657 memmove(ssl->sc_inbuf + ssl->sc_in_count, input_data, hc);
1658 ssl->sc_in_count += hc;
1659 input_data += hc;
1660 available -= hc;
1661 consumed += hc;
1662 if (ssl->sc_in_count < 5 || available == 0)
1663 break;
1664 }
1665
1666 // Top up sc_inbuf from network input_data hoping for a complete TLS Record
1667 // We try to guess the length as an optimization, but let SChannel
1668 // ultimately decide if there is spoofing going on.
1669 unsigned char low = (unsigned char) ssl->sc_inbuf[4];
1670 unsigned char high = (unsigned char) ssl->sc_inbuf[3];
1671 size_t rec_len = high * 256 + low + 5;
1672 if (rec_len < 5 || rec_len == ssl->sc_in_count || rec_len > ssl->sc_in_size)
1673 rec_len = ssl->sc_in_size;
1674
1675 count = _pni_min(rec_len - ssl->sc_in_count, available);
1676 }
1677
1678 if (count > 0) {
1679 memmove(ssl->sc_inbuf + ssl->sc_in_count, input_data, count);
1680 ssl->sc_in_count += count;
1681 input_data += count;
1682 available -= count;
1683 consumed += count;
1684 ssl->sc_in_incomplete = false;
1685 }
1686
1687 // Try to decrypt another TLS Record.
1688
1689 if (ssl->sc_in_count > 0 && ssl->state <= SHUTTING_DOWN) {
1690 if (ssl->state == NEGOTIATING) {
1691 ssl_handshake(transport);
1692 } else {
1693 if (ssl_decrypt(transport)) {
1694 // Ignore TLS Record with 0 length data (does not mean EOS)
1695 if (ssl->in_data_size > 0) {
1696 new_app_input = true;
1697 app_inbytes_add(transport);
1698 } else {
1699 assert(ssl->decrypting == false);
1700 rewind_sc_inbuf(ssl);
1701 }
1702 }
1703 ssl_log(transport, PN_LEVEL_TRACE, "Next decryption, %d left over", available);
1704 }
1705 }
1706
1707 if (ssl->state == SHUTTING_DOWN) {
1708 if (ssl->network_out_pending == 0 && !ssl->queued_shutdown) {
1709 start_ssl_shutdown(transport);
1710 }
1711 } else if (ssl->state == SSL_CLOSED) {
1712 return PN_EOS;
1713 }
1714
1715 // Consume or discard the decrypted bytes
1716 if (new_app_input && (ssl->state == RUNNING || ssl->state == SHUTTING_DOWN)) {
1717 // present app_inbytes to io_next only if it has new content
1718 while (ssl->app_inbytes.size > 0) {
1719 if (!ssl->app_input_closed) {
1720 ssize_t count = transport->io_layers[layer+1]->process_input(transport, layer+1, ssl->app_inbytes.start, ssl->app_inbytes.size);
1721 if (count > 0) {
1722 forwarded += count;
1723 // advance() can increase app_inbytes.size if double buffered
1724 app_inbytes_advance(transport, count);
1725 ssl_log(transport, PN_LEVEL_TRACE, "Application consumed %d bytes from peer", (int) count);
1726 } else if (count == 0) {
1727 size_t old_size = ssl->app_inbytes.size;
1728 app_inbytes_advance(transport, 0);
1729 if (ssl->app_inbytes.size == old_size) {
1730 break; // no additional contiguous decrypted data available, get more network data
1731 }
1732 } else {
1733 // count < 0
1734 ssl_log(transport, PN_LEVEL_WARNING, "Application layer closed its input, error=%d (discarding %d bytes)",
1735 (int) count, (int)ssl->app_inbytes.size);
1736 app_inbytes_advance(transport, ssl->app_inbytes.size); // discard
1737 read_closed(transport, layer, count);
1738 }
1739 } else {
1740 ssl_log(transport, PN_LEVEL_WARNING, "Input closed discard %d bytes",
1741 (int)ssl->app_inbytes.size);
1742 app_inbytes_advance(transport, ssl->app_inbytes.size); // discard
1743 }
1744 }
1745 }
1746 } while (available || (ssl->sc_in_count && !ssl->sc_in_incomplete));
1747
1748 if (ssl->state >= SHUTTING_DOWN) {
1749 if (ssl->app_input_closed || ssl->sc_input_shutdown) {
1750 // Next layer doesn't want more bytes, or it can't process without more data than it has seen so far
1751 // but the ssl stream has ended
1752 consumed = ssl->app_input_closed ? ssl->app_input_closed : PN_EOS;
1753 if (transport->io_layers[layer]==&ssl_output_closed_layer) {
1754 transport->io_layers[layer] = &ssl_closed_layer;
1755 } else {
1756 transport->io_layers[layer] = &ssl_input_closed_layer;
1757 }
1758 }
1759 }
1760 ssl_log(transport, PN_LEVEL_TRACE, "process_input_ssl() returning %d, forwarded %d", (int) consumed, (int) forwarded);
1761 return consumed;
1762 }
1763
1764 static ssize_t process_output_ssl( pn_transport_t *transport, unsigned int layer, char *buffer, size_t max_len)
1765 {
1766 pni_ssl_t *ssl = transport->ssl;
1767 if (!ssl) return PN_EOS;
1768 ssl_log( transport, PN_LEVEL_TRACE, "process_output_ssl( max_len=%d )",max_len );
1769
1770 ssize_t written = 0;
1771 ssize_t total_app_bytes = 0;
1772 bool work_pending;
1773
1774 if (ssl->state == CLIENT_HELLO) {
1775 // output buffers eclusively for internal handshake use until negotiation complete
1776 client_handshake_init(transport);
1777 if (ssl->state == SSL_CLOSED)
1778 return PN_EOS;
1779 ssl->state = NEGOTIATING;
1780 }
1781
1782 do {
1783 work_pending = false;
1784
1785 if (ssl->network_out_pending > 0) {
1786 size_t wcount = _pni_min(ssl->network_out_pending, max_len);
1787 memmove(buffer, ssl->network_outp, wcount);
1788 ssl->network_outp += wcount;
1789 ssl->network_out_pending -= wcount;
1790 buffer += wcount;
1791 max_len -= wcount;
1792 written += wcount;
1793 }
1794
1795 if (ssl->network_out_pending == 0 && ssl->state == RUNNING && !ssl->app_output_closed) {
1796 // refill the buffer with app data and encrypt it
1797
1798 char *app_data = ssl->sc_outbuf + ssl->sc_sizes.cbHeader;
1799 char *app_outp = app_data;
1800 size_t remaining = ssl->max_data_size;
1801 ssize_t app_bytes;
1802 do {
1803 app_bytes = transport->io_layers[layer+1]->process_output(transport, layer+1, app_outp, remaining);
1804 if (app_bytes > 0) {
1805 app_outp += app_bytes;
1806 remaining -= app_bytes;
1807 ssl_log( transport, PN_LEVEL_TRACE, "Gathered %d bytes from app to send to peer", app_bytes );
1808 } else {
1809 if (app_bytes < 0) {
1810 ssl_log(transport, PN_LEVEL_WARNING, "Application layer closed its output, error=%d (%d bytes pending send)",
1811 (int) app_bytes, (int) ssl->network_out_pending);
1812 ssl->app_output_closed = app_bytes;
1813 if (ssl->app_input_closed)
1814 ssl->state = SHUTTING_DOWN;
1815 } else if (total_app_bytes == 0 && ssl->app_input_closed) {
1816 // We've drained all the App layer can provide
1817 ssl_log(transport, PN_LEVEL_WARNING, "Application layer blocked on input, closing");
1818 ssl->state = SHUTTING_DOWN;
1819 ssl->app_output_closed = PN_ERR;
1820 }
1821 }
1822 } while (app_bytes > 0);
1823 if (app_outp > app_data) {
1824 work_pending = (max_len > 0);
1825 ssl_encrypt(transport, app_data, app_outp - app_data);
1826 }
1827 }
1828
1829 if (ssl->network_out_pending == 0) {
1830 if (ssl->state == SHUTTING_DOWN) {
1831 if (!ssl->queued_shutdown) {
1832 start_ssl_shutdown(transport);
1833 work_pending = true;
1834 } else {
1835 ssl->state = SSL_CLOSED;
1836 }
1837 }
1838 else if (ssl->state == NEGOTIATING && ssl->app_input_closed) {
1839 ssl->app_output_closed = PN_EOS;
1840 ssl->state = SSL_CLOSED;
1841 }
1842 }
1843 } while (work_pending);
1844
1845 if (written == 0 && ssl->state == SSL_CLOSED) {
1846 written = ssl->app_output_closed ? ssl->app_output_closed : PN_EOS;
1847 if (transport->io_layers[layer]==&ssl_input_closed_layer) {
1848 transport->io_layers[layer] = &ssl_closed_layer;
1849 } else {
1850 transport->io_layers[layer] = &ssl_output_closed_layer;
1851 }
1852 }
1853 ssl_log(transport, PN_LEVEL_TRACE, "process_output_ssl() returning %d", (int) written);
1854 return written;
1855 }
1856
1857
1858 static ssize_t process_input_done(pn_transport_t *transport, unsigned int layer, const char *input_data, size_t len)
1859 {
1860 return PN_EOS;
1861 }
1862
1863 static ssize_t process_output_done(pn_transport_t *transport, unsigned int layer, char *input_data, size_t len)
1864 {
1865 return PN_EOS;
1866 }
1867
1868 // return # output bytes sitting in this layer
1869 static size_t buffered_output(pn_transport_t *transport)
1870 {
1871 size_t count = 0;
1872 pni_ssl_t *ssl = transport->ssl;
1873 if (ssl) {
1874 count += ssl->network_out_pending;
1875 if (count == 0 && ssl->state == SHUTTING_DOWN && ssl->queued_shutdown)
1876 count++;
1877 }
1878 return count;
1879 }
1880
1881 static HCERTSTORE open_cert_db(const char *store_name, const char *passwd, int *error) {
1882 *error = 0;
1883 DWORD sys_store_type = 0;
1884 HCERTSTORE cert_store = 0;
1885
1886 if (store_name) {
1887 if (strncmp(store_name, "ss:", 3) == 0) {
1888 store_name += 3;
1889 sys_store_type = CERT_SYSTEM_STORE_CURRENT_USER;
1890 }
1891 else if (strncmp(store_name, "lmss:", 5) == 0) {
1892 store_name += 5;
1893 sys_store_type = CERT_SYSTEM_STORE_LOCAL_MACHINE;
1894 }
1895 }
1896
1897 if (sys_store_type) {
1898 // Opening a system store, names are not case sensitive.
1899 // Map confusing GUI name to actual registry store name.
1900 if (!pn_strcasecmp(store_name, "personal")) store_name= "my";
1901 cert_store = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, NULL,
1902 CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG |
1903 sys_store_type, store_name);
1904 if (!cert_store) {
1905 ssl_log_error_status(GetLastError(), "Failed to open system certificate store %s", store_name);
1906 *error = -3;
1907 return NULL;
1908 }
1909 } else {
1910 // PKCS#12 file
1911 HANDLE cert_file = CreateFile(store_name, GENERIC_READ, 0, NULL, OPEN_EXISTING,
1912 FILE_ATTRIBUTE_NORMAL, NULL);
1913 if (INVALID_HANDLE_VALUE == cert_file) {
1914 HRESULT status = GetLastError();
1915 ssl_log_error_status(status, "Failed to open the file holding the private key: %s", store_name);
1916 *error = -4;
1917 return NULL;
1918 }
1919 DWORD nread = 0L;
1920 const DWORD file_size = GetFileSize(cert_file, NULL);
1921 char *buf = NULL;
1922 if (INVALID_FILE_SIZE != file_size)
1923 buf = (char *) malloc(file_size);
1924 if (!buf || !ReadFile(cert_file, buf, file_size, &nread, NULL)
1925 || file_size != nread) {
1926 HRESULT status = GetLastError();
1927 CloseHandle(cert_file);
1928 free(buf);
1929 ssl_log_error_status(status, "Reading the private key from file failed %s", store_name);
1930 *error = -5;
1931 return NULL;
1932 }
1933 CloseHandle(cert_file);
1934
1935 CRYPT_DATA_BLOB blob;
1936 blob.cbData = nread;
1937 blob.pbData = (BYTE *) buf;
1938
1939 wchar_t *pwUCS2 = NULL;
1940 int pwlen = 0;
1941 if (passwd) {
1942 // convert passwd to null terminated wchar_t (Windows UCS2)
1943 pwlen = strlen(passwd);
1944 pwUCS2 = (wchar_t *) calloc(pwlen + 1, sizeof(wchar_t));
1945 int nwc = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, passwd, pwlen, &pwUCS2[0], pwlen);
1946 if (!nwc) {
1947 ssl_log_error_status(GetLastError(), "Error converting password from UTF8");
1948 free(buf);
1949 free(pwUCS2);
1950 *error = -6;
1951 return NULL;
1952 }
1953 }
1954
1955 cert_store = PFXImportCertStore(&blob, pwUCS2, 0);
1956 if (pwUCS2) {
1957 SecureZeroMemory(pwUCS2, pwlen * sizeof(wchar_t));
1958 free(pwUCS2);
1959 }
1960 if (cert_store == NULL) {
1961 ssl_log_error_status(GetLastError(), "Failed to import the file based certificate store");
1962 free(buf);
1963 *error = -7;
1964 return NULL;
1965 }
1966
1967 free(buf);
1968 }
1969
1970 return cert_store;
1971 }
1972
1973 static bool store_contains(HCERTSTORE store, PCCERT_CONTEXT cert)
1974 {
1975 DWORD find_type = CERT_FIND_EXISTING; // Require exact match
1976 PCCERT_CONTEXT tcert = CertFindCertificateInStore(store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1977 0, find_type, cert, 0);
1978 if (tcert) {
1979 CertFreeCertificateContext(tcert);
1980 return true;
1981 }
1982 return false;
1983 }
1984
1985 /* Match the DNS name pattern from the peer certificate against our configured peer
1986 hostname */
1987 static bool match_dns_pattern(const char *hostname, const char *pattern, int plen)
1988 {
1989 int slen = (int) strlen(hostname);
1990 if (memchr( pattern, '*', plen ) == NULL)
1991 return (plen == slen &&
1992 pn_strncasecmp( pattern, hostname, plen ) == 0);
1993
1994 /* dns wildcarded pattern - RFC2818 */
1995 char plabel[64]; /* max label length < 63 - RFC1034 */
1996 char slabel[64];
1997
1998 while (plen > 0 && slen > 0) {
1999 const char *cptr;
2000 int len;
2001
2002 cptr = (const char *) memchr( pattern, '.', plen );
2003 len = (cptr) ? cptr - pattern : plen;
2004 if (len > (int) sizeof(plabel) - 1) return false;
2005 memcpy( plabel, pattern, len );
2006 plabel[len] = 0;
2007 if (cptr) ++len; // skip matching '.'
2008 pattern += len;
2009 plen -= len;
2010
2011 cptr = (const char *) memchr( hostname, '.', slen );
2012 len = (cptr) ? cptr - hostname : slen;
2013 if (len > (int) sizeof(slabel) - 1) return false;
2014 memcpy( slabel, hostname, len );
2015 slabel[len] = 0;
2016 if (cptr) ++len; // skip matching '.'
2017 hostname += len;
2018 slen -= len;
2019
2020 char *star = strchr( plabel, '*' );
2021 if (!star) {
2022 if (pn_strcasecmp( plabel, slabel )) return false;
2023 } else {
2024 *star = '\0';
2025 char *prefix = plabel;
2026 int prefix_len = strlen(prefix);
2027 char *suffix = star + 1;
2028 int suffix_len = strlen(suffix);
2029 if (prefix_len && pn_strncasecmp( prefix, slabel, prefix_len )) return false;
2030 if (suffix_len && pn_strncasecmp( suffix,
2031 slabel + (strlen(slabel) - suffix_len),
2032 suffix_len )) return false;
2033 }
2034 }
2035
2036 return plen == slen;
2037 }
2038
2039 // Caller must free the returned buffer
2040 static char* wide_to_utf8(LPWSTR wstring)
2041 {
2042 int len = WideCharToMultiByte(CP_UTF8, 0, wstring, -1, 0, 0, 0, 0);
2043 if (!len) {
2044 ssl_log_error_status(GetLastError(), "converting UCS2 to UTF8");
2045 return NULL;
2046 }
2047 char *p = (char *) malloc(len);
2048 if (!p) return NULL;
2049 if (WideCharToMultiByte(CP_UTF8, 0, wstring, -1, p, len, 0, 0))
2050 return p;
2051 ssl_log_error_status(GetLastError(), "converting UCS2 to UTF8");
2052 free (p);
2053 return NULL;
2054 }
2055
2056 static bool server_name_matches(const char *server_name, CERT_EXTENSION *alt_name_ext, PCCERT_CONTEXT cert)
2057 {
2058 // As for openssl.c: alt names first, then CN
2059 bool matched = false;
2060
2061 if (alt_name_ext) {
2062 CERT_ALT_NAME_INFO* alt_name_info = NULL;
2063 DWORD size = 0;
2064 if(!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, szOID_SUBJECT_ALT_NAME2,
2065 alt_name_ext->Value.pbData, alt_name_ext->Value.cbData,
2066 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG,
2067 0, &alt_name_info, &size)) {
2068 ssl_log_error_status(GetLastError(), "Alternative name match internal error");
2069 return false;
2070 }
2071
2072 int name_ct = alt_name_info->cAltEntry;
2073 for (int i = 0; !matched && i < name_ct; ++i) {
2074 if (alt_name_info->rgAltEntry[i].dwAltNameChoice == CERT_ALT_NAME_DNS_NAME) {
2075 char *alt_name = wide_to_utf8(alt_name_info->rgAltEntry[i].pwszDNSName);
2076 if (alt_name) {
2077 matched = match_dns_pattern(server_name, (const char *) alt_name, strlen(alt_name));
2078 free(alt_name);
2079 }
2080 }
2081 }
2082 LocalFree(alt_name_info);
2083 }
2084
2085 if (!matched) {
2086 PCERT_INFO info = cert->pCertInfo;
2087 DWORD len = CertGetNameString(cert, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME, 0, 0);
2088 char *name = (char *) malloc(len);
2089 if (name) {
2090 int count = CertGetNameString(cert, CERT_NAME_ATTR_TYPE, 0, szOID_COMMON_NAME, name, len);
2091 if (count)
2092 matched = match_dns_pattern(server_name, (const char *) name, strlen(name));
2093 free(name);
2094 }
2095 }
2096 return matched;
2097 }
2098
2099 const char* pn_ssl_get_remote_subject_subfield(pn_ssl_t *ssl0, pn_ssl_cert_subject_subfield field)
2100 {
2101 return NULL;
2102 }
2103
2104 int pn_ssl_get_cert_fingerprint(pn_ssl_t *ssl0,
2105 char *fingerprint,
2106 size_t fingerprint_length,
2107 pn_ssl_hash_alg hash_alg)
2108 {
2109 *fingerprint = '\0';
2110 return -1;
2111 }
2112
2113 static HRESULT verify_peer(pni_ssl_t *ssl, HCERTSTORE root_store, const char *server_name, bool tracing)
2114 {
2115 // Free/release the following before return:
2116 PCCERT_CONTEXT peer_cc = 0;
2117 PCCERT_CONTEXT trust_anchor = 0;
2118 PCCERT_CHAIN_CONTEXT chain_context = 0;
2119 wchar_t *nameUCS2 = 0;
2120
2121 if (server_name && strlen(server_name) > 255) {
2122 ssl_log_error("invalid server name: %s", server_name);
2123 return WSAENAMETOOLONG;
2124 }
2125
2126 // Get peer's certificate.
2127 SECURITY_STATUS status;
2128 status = QueryContextAttributes(&ssl->ctxt_handle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &peer_cc);
2129 if (status != SEC_E_OK) {
2130 ssl_log_error_status(status, "can't obtain remote peer certificate information");
2131 return status;
2132 }
2133
2134 // Build the peer's certificate chain. Multiple chains may be built but we
2135 // care about rgpChain[0], which is the best. Custom root stores are not
2136 // allowed until W8/server 2012: see CERT_CHAIN_ENGINE_CONFIG. For now, we
2137 // manually override to taste.
2138
2139 // Chain verification functions give false reports for CRL if the trust anchor
2140 // is not in the official root store. We ignore CRL completely if it doesn't
2141 // apply to any untrusted certs in the chain, and defer to SChannel's veto
2142 // otherwise. To rely on CRL, the CA must be in both the official system
2143 // trusted root store and the Proton cred->trust_store. To defeat CRL, the
2144 // most distal cert with CRL must be placed in the Proton cred->trust_store.
2145 // Similarly, certificate usage checking is overly strict at times.
2146
2147 CERT_CHAIN_PARA desc;
2148 memset(&desc, 0, sizeof(desc));
2149 desc.cbSize = sizeof(desc);
2150
2151 LPSTR usages[] = { szOID_PKIX_KP_SERVER_AUTH };
2152 DWORD n_usages = sizeof(usages) / sizeof(LPSTR);
2153 desc.RequestedUsage.dwType = USAGE_MATCH_TYPE_OR;
2154 desc.RequestedUsage.Usage.cUsageIdentifier = n_usages;
2155 desc.RequestedUsage.Usage.rgpszUsageIdentifier = usages;
2156
2157 if(!CertGetCertificateChain(0, peer_cc, 0, peer_cc->hCertStore, &desc,
2158 CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT |
2159 CERT_CHAIN_CACHE_END_CERT,
2160 0, &chain_context)){
2161 HRESULT st = GetLastError();
2162 ssl_log_error_status(st, "Basic certificate chain check failed");
2163 CertFreeCertificateContext(peer_cc);
2164 return st;
2165 }
2166 if (chain_context->cChain < 1 || chain_context->rgpChain[0]->cElement < 1) {
2167 ssl_log_error("empty chain with status %x %x", chain_context->TrustStatus.dwErrorStatus,
2168 chain_context->TrustStatus.dwInfoStatus);
2169 return SEC_E_CERT_UNKNOWN;
2170 }
2171
2172 int chain_len = chain_context->rgpChain[0]->cElement;
2173 PCCERT_CONTEXT leaf_cert = chain_context->rgpChain[0]->rgpElement[0]->pCertContext;
2174 PCCERT_CONTEXT trunk_cert = chain_context->rgpChain[0]->rgpElement[chain_len - 1]->pCertContext;
2175 if (tracing)
2176 // See doc for CERT_CHAIN_POLICY_STATUS for bit field error and info status values
2177 ssl_log_error("status for complete chain: error bits %x info bits %x",
2178 chain_context->TrustStatus.dwErrorStatus, chain_context->TrustStatus.dwInfoStatus);
2179
2180 // Supplement with checks against Proton's trusted_ca_db, custom revocation and usage.
2181 HRESULT error = 0;
2182 do {
2183 // Do not return from this do loop. Set error = SEC_E_XXX and break.
2184 bool revocable = false; // unless we see any untrusted certs that could be
2185 for (int i = 0; i < chain_len; i++) {
2186 CERT_CHAIN_ELEMENT *ce = chain_context->rgpChain[0]->rgpElement[i];
2187 PCCERT_CONTEXT cc = ce->pCertContext;
2188 if (cc->pCertInfo->dwVersion != CERT_V3) {
2189 if (tracing)
2190 ssl_log_error("certificate chain element %d is not version 3", i);
2191 error = SEC_E_CERT_WRONG_USAGE; // A fossil
2192 break;
2193 }
2194
2195 if (!trust_anchor && store_contains(root_store, cc))
2196 trust_anchor = CertDuplicateCertificateContext(cc);
2197
2198 int n_ext = cc->pCertInfo->cExtension;
2199 for (int ii = 0; ii < n_ext && !revocable && !trust_anchor; ii++) {
2200 CERT_EXTENSION *p = &cc->pCertInfo->rgExtension[ii];
2201 // rfc 5280 extensions for revocation
2202 if (!strcmp(p->pszObjId, szOID_AUTHORITY_INFO_ACCESS) ||
2203 !strcmp(p->pszObjId, szOID_CRL_DIST_POINTS) ||
2204 !strcmp(p->pszObjId, szOID_FRESHEST_CRL)) {
2205 revocable = true;
2206 }
2207 }
2208
2209 if (tracing) {
2210 char name[512];
2211 const char *is_anchor = (cc == trust_anchor) ? " trust anchor" : "";
2212 if (!CertNameToStr(cc->dwCertEncodingType, &cc->pCertInfo->Subject,
2213 CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG, name, sizeof(name)))
2214 strcpy(name, "[too long]");
2215 ssl_log_error("element %d (name: %s)%s error bits %x info bits %x", i, name, is_anchor,
2216 ce->TrustStatus.dwErrorStatus, ce->TrustStatus.dwInfoStatus);
2217 }
2218 }
2219 if (error)
2220 break;
2221
2222 if (!trust_anchor) {
2223 // We don't trust any of the certs in the chain, see if the last cert
2224 // is issued by a Proton trusted CA.
2225 DWORD flags = CERT_STORE_NO_ISSUER_FLAG || CERT_STORE_SIGNATURE_FLAG ||
2226 CERT_STORE_TIME_VALIDITY_FLAG;
2227 trust_anchor = CertGetIssuerCertificateFromStore(root_store, trunk_cert, 0, &flags);
2228 if (trust_anchor) {
2229 if (tracing) {
2230 if (flags & CERT_STORE_SIGNATURE_FLAG)
2231 ssl_log_error("root certificate signature failure");
2232 if (flags & CERT_STORE_TIME_VALIDITY_FLAG)
2233 ssl_log_error("root certificate time validity failure");
2234 }
2235 if (flags) {
2236 CertFreeCertificateContext(trust_anchor);
2237 trust_anchor = 0;
2238 }
2239 }
2240 }
2241 if (!trust_anchor) {
2242 error = SEC_E_UNTRUSTED_ROOT;
2243 break;
2244 }
2245
2246 bool strict_usage = false;
2247 CERT_EXTENSION *leaf_alt_names = 0;
2248 if (leaf_cert != trust_anchor) {
2249 int n_ext = leaf_cert->pCertInfo->cExtension;
2250 for (int ii = 0; ii < n_ext; ii++) {
2251 CERT_EXTENSION *p = &leaf_cert->pCertInfo->rgExtension[ii];
2252 if (!strcmp(p->pszObjId, szOID_ENHANCED_KEY_USAGE))
2253 strict_usage = true;
2254 if (!strcmp(p->pszObjId, szOID_SUBJECT_ALT_NAME2))
2255 if (p->Value.pbData)
2256 leaf_alt_names = p;
2257 }
2258 }
2259
2260 if (server_name) {
2261 int len = strlen(server_name);
2262 nameUCS2 = (wchar_t *) calloc(len + 1, sizeof(wchar_t));
2263 int nwc = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, server_name, len, &nameUCS2[0], len);
2264 if (!nwc) {
2265 error = GetLastError();
2266 ssl_log_error_status(error, "Error converting server name from UTF8");
2267 break;
2268 }
2269 }
2270
2271 // SSL-specific parameters (ExtraPolicy below)
2272 SSL_EXTRA_CERT_CHAIN_POLICY_PARA ssl_desc;
2273 memset(&ssl_desc, 0, sizeof(ssl_desc));
2274 ssl_desc.cbSize = sizeof(ssl_desc);
2275 ssl_desc.pwszServerName = nameUCS2;
2276 ssl_desc.dwAuthType = nameUCS2 ? AUTHTYPE_SERVER : AUTHTYPE_CLIENT;
2277 ssl_desc.fdwChecks = SECURITY_FLAG_IGNORE_UNKNOWN_CA;
2278 if (server_name)
2279 ssl_desc.fdwChecks |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
2280 if (!revocable)
2281 ssl_desc.fdwChecks |= SECURITY_FLAG_IGNORE_REVOCATION;
2282 if (!strict_usage)
2283 ssl_desc.fdwChecks |= SECURITY_FLAG_IGNORE_WRONG_USAGE;
2284
2285 // General certificate chain parameters
2286 CERT_CHAIN_POLICY_PARA chain_desc;
2287 memset(&chain_desc, 0, sizeof(chain_desc));
2288 chain_desc.cbSize = sizeof(chain_desc);
2289 chain_desc.dwFlags = CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG;
2290 if (!revocable)
2291 chain_desc.dwFlags |= CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
2292 if (!strict_usage)
2293 chain_desc.dwFlags |= CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG;
2294 chain_desc.pvExtraPolicyPara = &ssl_desc;
2295
2296 CERT_CHAIN_POLICY_STATUS chain_status;
2297 memset(&chain_status, 0, sizeof(chain_status));
2298 chain_status.cbSize = sizeof(chain_status);
2299
2300 if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
2301 &chain_desc, &chain_status)) {
2302 error = GetLastError();
2303 // Failure to complete the check, does not (in)validate the cert.
2304 ssl_log_error_status(error, "Supplemental certificate chain check failed");
2305 break;
2306 }
2307
2308 if (chain_status.dwError) {
2309 error = chain_status.dwError;
2310 if (tracing) {
2311 ssl_log_error_status(chain_status.dwError, "Certificate chain verification error");
2312 if (chain_status.lChainIndex == 0 && chain_status.lElementIndex != -1) {
2313 int idx = chain_status.lElementIndex;
2314 CERT_CHAIN_ELEMENT *ce = chain_context->rgpChain[0]->rgpElement[idx];
2315 ssl_log_error(" chain failure at %d error/info: %x %x", idx,
2316 ce->TrustStatus.dwErrorStatus, ce->TrustStatus.dwInfoStatus);
2317 }
2318 }
2319 break;
2320 }
2321
2322 if (server_name && ssl->verify_mode == PN_SSL_VERIFY_PEER_NAME &&
2323 !server_name_matches(server_name, leaf_alt_names, leaf_cert)) {
2324 error = SEC_E_WRONG_PRINCIPAL;
2325 break;
2326 }
2327 else if (ssl->verify_mode == PN_SSL_VERIFY_PEER_NAME && !server_name) {
2328 ssl_log_error("Error: configuration error: PN_SSL_VERIFY_PEER_NAME configured, but no peer hostname set!");
2329 error = SEC_E_WRONG_PRINCIPAL;
2330 break;
2331 }
2332 } while (0);
2333
2334 if (tracing && !error)
2335 ssl_log_error("peer certificate authenticated");
2336
2337 // Lots to clean up.
2338 if (peer_cc)
2339 CertFreeCertificateContext(peer_cc);
2340 if (trust_anchor)
2341 CertFreeCertificateContext(trust_anchor);
2342 if (chain_context)
2343 CertFreeCertificateChain(chain_context);
2344 free(nameUCS2);
2345 return error;
2346 }
2347
2348 }