Debian Codegraph @

Xpjproject/pjlib/src/pj/ssl_sock_schannel.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2024 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19 #include <pj/ssl_sock.h>
20 #include <pj/activesock.h>
21 #include <pj/compat/socket.h>
22 #include <pj/assert.h>
23 #include <pj/errno.h>
24 #include <pj/file_access.h>
25 #include <pj/list.h>
26 #include <pj/lock.h>
27 #include <pj/log.h>
28 #include <pj/math.h>
29 #include <pj/os.h>
30 #include <pj/pool.h>
31 #include <pj/string.h>
32 #include <pj/timer.h>
33 #include <pj/unicode.h>
34
35 /* Only build when PJ_HAS_SSL_SOCK is enabled and when the backend is
36 * Schannel.
37 *
38 * Note:
39 * - Older Windows SDK versions are not supported (some APIs deprecated,
40 * also missing newer/safer TLS protocol versions).
41 */
42 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
43 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_SCHANNEL) && \
44 defined(_MSC_VER) && _MSC_VER>=1900
45
46 #define THIS_FILE "ssl_sock_schannel.c"
47
48 /* Sender string in logging */
49 #define SENDER "ssl_schannel"
50
51 /* Subject for self-signed certificate */
52 #define SELF_SIGNED_CERT_SUBJECT "CN=lab.pjsip.org"
53
54 /* Debugging */
55 #define DEBUG_SCHANNEL 0
56
57 #if DEBUG_SCHANNEL
58 # define LOG_DEBUG(sender,title) PJ_LOG(4,(sender,title))
59 # define LOG_DEBUG1(sender,title,p1) PJ_LOG(4,(sender,title,p1))
60 # define LOG_DEBUG2(sender,title,p1,p2) PJ_LOG(4,(sender,title,p1,p2))
61 # define LOG_DEBUG3(sender,title,p1,p2,p3) PJ_LOG(4,(sender,title,p1,p2,p3))
62 # define LOG_DEBUG_ERR(sender,title,sec_status) \
63 log_sec_err(4,sender,title,sec_status)
64 #else
65 # define LOG_DEBUG(sender,title)
66 # define LOG_DEBUG1(sender,title,p1)
67 # define LOG_DEBUG2(sender,title,p1,p2)
68 # define LOG_DEBUG3(sender,title,p1,p2,p3)
69 # define LOG_DEBUG_ERR(sender,title,sec_status)
70 #endif
71
72
73 /* For using SSPI */
74 #define SECURITY_WIN32
75
76 /* For using SCH_CREDENTIALS */
77 #define SCHANNEL_USE_BLACKLISTS
78 #include <Winternl.h>
79 #include <security.h>
80 #include <schannel.h>
81 #include <Bcrypt.h> // for enumerating ciphers
82
83 #pragma comment (lib, "secur32.lib")
84 #pragma comment (lib, "shlwapi.lib")
85 #pragma comment (lib, "Crypt32.lib") // for creating & manipulating certs
86 #pragma comment (lib, "Bcrypt.lib") // for enumerating ciphers
87
88
89 /* SSL sock implementation API */
90 #define SSL_SOCK_IMP_USE_CIRC_BUF
91 #include "ssl_sock_imp_common.h"
92
93 #define MIN_READ_BUF_CAP (1024*8)
94 #define MIN_WRITE_BUF_CAP (1024*8)
95
96
97 /*
98 * Schannel global vars.
99 */
100 static struct sch_ssl_t
101 {
102 pj_caching_pool cp;
103 pj_pool_t *pool;
104 unsigned long init_cnt;
105 PCCERT_CONTEXT self_signed_cert;
106 } sch_ssl;
107
108
109 /*
110 * Secure socket structure definition.
111 */
112 typedef struct sch_ssl_sock_t
113 {
114 pj_ssl_sock_t base;
115
116 CredHandle cred_handle;
117 CtxtHandle ctx_handle;
118 PCCERT_CONTEXT cert_ctx;
119 SecPkgContext_StreamSizes strm_sizes;
120
121 pj_uint8_t *write_buf;
122 pj_size_t write_buf_cap;
123 pj_uint8_t *read_buf;
124 pj_size_t read_buf_cap;
125 circ_buf_t decrypted_buf;
126 } sch_ssl_sock_t;
127
128
129 #include "ssl_sock_imp_common.c"
130
131
132 /* === Helper functions === */
133
134 #define SNAME(ssock) ((ssock)->pool->obj_name)
135 #define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + PJ_ERRNO_SPACE_SIZE*6)
136
137 /* Map SECURITY_STATUS to pj_status_t.
138 *
139 * SECURITY_STATUS/Windows-error 32 bit structure (from winerror.h):
140 *
141 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
142 * +---+-+-+-----------------------+-------------------------------+
143 * |Sev|C|R| Facility | Code |
144 * +---+-+-+-----------------------+-------------------------------+
145 *
146 * For this mapping, we only save one severity bit & 15 bit error code.
147 * The facility value for security/SSPI is 9, which needs to be inserted
148 * when converting back from pj_status_t.
149 *
150 * So in pj_status_t it is stored as:
151 * 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
152 * +---+-+-+-----------------------+-------------------------------+
153 * | PJLIB internal | Code |S|
154 * +---+-+-+-----------------------+-------------------------------+
155 */
156 static pj_status_t sec_err_to_pj(SECURITY_STATUS ss)
157 {
158 DWORD err = ((ss & 0x7FFF) << 1) | ((ss & 0x80000000) >> 31);
159
160 /* Make sure it does not exceed PJ_ERRNO_SPACE_SIZE */
161 if (err >= PJ_ERRNO_SPACE_SIZE) {
162 LOG_DEBUG1(SENDER,"sec_err_to_pj() failed mapping error code %d",
163 err);
164 return PJ_EUNKNOWN;
165 }
166
167 return PJ_SSL_ERRNO_START + err;
168 }
169
170 /* Get SECURITY_STATUS from pj_status_t. */
171 static SECURITY_STATUS sec_err_from_pj(pj_status_t status)
172 {
173 SECURITY_STATUS ss;
174
175 /* Make sure it is within SSL error space */
176 if (status < PJ_SSL_ERRNO_START ||
177 status >= PJ_SSL_ERRNO_START + PJ_ERRNO_SPACE_SIZE)
178 {
179 LOG_DEBUG1(SENDER,"sec_err_from_pj() failed mapping status code %d",
180 status);
181 return ERROR_INVALID_DATA;
182 }
183
184 ss = status - PJ_SSL_ERRNO_START;
185 ss = (ss >> 1) | ((ss & 1) << 31) | 0x00090000;
186 return ss;
187 }
188
189 /* Print Schannel error to log */
190 static void log_sec_err(int log_level, const char* sender,
191 const char* title, SECURITY_STATUS ss)
192 {
193 char *str = NULL;
194 DWORD len;
195 len = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
196 FORMAT_MESSAGE_FROM_SYSTEM |
197 FORMAT_MESSAGE_IGNORE_INSERTS,
198 NULL, ss, 0, (LPSTR)&str, 0, NULL);
199 /* Trim new line chars */
200 if (str) {
201 while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
202 str[--len] = 0;
203 }
204
205 switch (log_level) {
206 case 1:
207 PJ_LOG(1, (sender, "%s: 0x%x-%s", title, ss, (str? str : "")));
208 break;
209 case 2:
210 PJ_LOG(2, (sender, "%s: 0x%x-%s", title, ss, (str? str : "")));
211 break;
212 case 3:
213 PJ_LOG(3, (sender, "%s: 0x%x-%s", title, ss, (str? str : "")));
214 break;
215 case 4:
216 PJ_LOG(4, (sender, "%s: 0x%x-%s", title, ss, (str? str : "")));
217 break;
218 case 5:
219 PJ_LOG(5, (sender, "%s: 0x%x-%s", title, ss, (str? str : "")));
220 break;
221 default:
222 PJ_LOG(6, (sender, "%s: 0x%x-%s", title, ss, (str? str : "")));
223 break;
224 }
225
226 if (str)
227 LocalFree(str);
228 }
229
230 static pj_str_t sch_err_print(pj_status_t e, char *msg, pj_size_t max)
231 {
232 DWORD len;
233 SECURITY_STATUS ss = sec_err_from_pj(e);
234 pj_str_t pjstr = {0};
235
236 len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
237 FORMAT_MESSAGE_IGNORE_INSERTS,
238 NULL, ss, 0, (LPSTR)msg, (DWORD)max, NULL);
239
240 /* Trim new line chars */
241 while (len > 0 && (msg[len-1] == '\r' || msg[len-1] == '\n'))
242 msg[--len] = 0;
243
244 pj_strset(&pjstr, msg, len);
245
246 return pjstr;
247 }
248
249 static void sch_deinit(void)
250 {
251 if (sch_ssl.self_signed_cert)
252 CertFreeCertificateContext(sch_ssl.self_signed_cert);
253
254 if (sch_ssl.pool) {
255 pj_pool_secure_release(&sch_ssl.pool);
256 pj_caching_pool_destroy(&sch_ssl.cp);
257 }
258
259 pj_bzero(&sch_ssl, sizeof(sch_ssl));
260 }
261
262 static void sch_inc()
263 {
264 if (++sch_ssl.init_cnt == 1 && sch_ssl.pool == NULL) {
265 pj_caching_pool_init(&sch_ssl.cp, NULL, 0);
266 sch_ssl.pool = pj_pool_create(&sch_ssl.cp.factory, "sch%p",
267 512, 512, NULL);
268 if (pj_atexit(&sch_deinit) != PJ_SUCCESS) {
269 PJ_LOG(1,(SENDER, "Failed to register atexit() for Schannel."));
270 }
271
272 pj_register_strerror(PJ_SSL_ERRNO_START, PJ_ERRNO_SPACE_SIZE,
273 &sch_err_print);
274 }
275 }
276
277 static void sch_dec()
278 {
279 pj_assert(sch_ssl.init_cnt > 0);
280 --sch_ssl.init_cnt;
281 }
282
283
284 /* === SSL socket implementations === */
285
286 /* Allocate SSL backend struct */
287 static pj_ssl_sock_t *ssl_alloc(pj_pool_t *pool)
288 {
289 sch_ssl_sock_t *sch_ssock = NULL;
290
291 sch_inc();
292
293 sch_ssock = (sch_ssl_sock_t*) PJ_POOL_ZALLOC_T(pool, sch_ssl_sock_t);
294 if (!sch_ssock)
295 return NULL;
296
297 SecInvalidateHandle(&sch_ssock->cred_handle);
298 SecInvalidateHandle(&sch_ssock->ctx_handle);
299
300 return &sch_ssock->base;
301 }
302
303 /* Create and initialize new SSL context and instance */
304 static pj_status_t ssl_create(pj_ssl_sock_t *ssock)
305 {
306 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
307 pj_pool_factory* pf = ssock->pool->factory;
308 pj_pool_t* pool = ssock->pool;
309 pj_ssize_t read_cap, write_cap;
310 pj_status_t status = PJ_SUCCESS;
311
312 /* Ciphers & curves settings should be set via OS/registry */
313 if (ssock->param.ciphers_num || ssock->param.curves_num) {
314 PJ_LOG(3,(SNAME(ssock), "Ciphers and curves settings are ignored, "
315 "they should be set via OS/registry"));
316 }
317
318 read_cap = PJ_MAX(MIN_READ_BUF_CAP, ssock->param.read_buffer_size);
319 write_cap = PJ_MAX(MIN_WRITE_BUF_CAP, ssock->param.send_buffer_size);
320
321 /* Allocate read buffer */
322 sch_ssock->read_buf_cap = read_cap;
323 sch_ssock->read_buf = (pj_uint8_t*)pj_pool_zalloc(pool, read_cap);
324 if (!sch_ssock->read_buf) {
325 status = PJ_ENOMEM;
326 goto on_return;
327 }
328
329 /* Allocate write buffer */
330 sch_ssock->write_buf_cap = write_cap;
331 sch_ssock->write_buf = (pj_uint8_t*)pj_pool_zalloc(pool, write_cap);
332 if (!sch_ssock->write_buf) {
333 status = PJ_ENOMEM;
334 goto on_return;
335 }
336
337 /* Initialize input circular buffer */
338 status = circ_init(pf, &ssock->ssl_read_buf, read_cap);
339 if (status != PJ_SUCCESS)
340 goto on_return;
341
342 /* Initialize output circular buffer */
343 status = circ_init(pf, &ssock->ssl_write_buf, write_cap);
344 if (status != PJ_SUCCESS)
345 goto on_return;
346
347 /* Initialize decrypted circular buffer */
348 status = circ_init(pf, &sch_ssock->decrypted_buf, read_cap);
349 if (status != PJ_SUCCESS)
350 goto on_return;
351
352 on_return:
353 if (status != PJ_SUCCESS) {
354 PJ_PERROR(1, (SENDER, status, "Error allocating SSL"));
355 }
356
357 return status;
358 }
359
360
361 /* Destroy SSL context and instance */
362 static void ssl_destroy(pj_ssl_sock_t* ssock)
363 {
364 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
365
366 /* Destroy circular buffers */
367 circ_deinit(&ssock->ssl_read_buf);
368 circ_deinit(&ssock->ssl_write_buf);
369 circ_deinit(&sch_ssock->decrypted_buf);
370
371 /* Free certificate */
372 if (sch_ssock->cert_ctx) {
373 CertFreeCertificateContext(sch_ssock->cert_ctx);
374 sch_ssock->cert_ctx = NULL;
375 }
376
377 sch_dec();
378 }
379
380 /* Reset SSL socket state */
381 static void ssl_reset_sock_state(pj_ssl_sock_t* ssock)
382 {
383 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
384 SECURITY_STATUS ss;
385 int post_unlock_flush_write_buf = 0;
386
387 LOG_DEBUG(SNAME(ssock), "SSL reset");
388
389 pj_lock_acquire(ssock->write_mutex);
390
391 /* Signal shutdown only when SSL connection has been established */
392 if (ssock->ssl_state == SSL_STATE_ESTABLISHED &&
393 SecIsValidHandle(&sch_ssock->ctx_handle))
394 {
395 DWORD type = SCHANNEL_SHUTDOWN;
396
397 SecBuffer buf_in[1] = { {0} };
398 buf_in[0].BufferType = SECBUFFER_TOKEN;
399 buf_in[0].pvBuffer = &type;
400 buf_in[0].cbBuffer = sizeof(type);
401 SecBufferDesc buf_desc_in = { 0 };
402 buf_desc_in.ulVersion = SECBUFFER_VERSION;
403 buf_desc_in.cBuffers = ARRAYSIZE(buf_in);
404 buf_desc_in.pBuffers = buf_in;
405 ApplyControlToken(&sch_ssock->ctx_handle, &buf_desc_in);
406
407 SecBuffer buf_out[1] = { {0} };
408 buf_out[0].BufferType = SECBUFFER_TOKEN;
409 buf_out[0].pvBuffer = sch_ssock->write_buf;
410 buf_out[0].cbBuffer = (ULONG)sch_ssock->write_buf_cap;
411 SecBufferDesc buf_desc_out = { 0 };
412 buf_desc_out.ulVersion = SECBUFFER_VERSION;
413 buf_desc_out.cBuffers = ARRAYSIZE(buf_out);
414 buf_desc_out.pBuffers = buf_out;
415
416 DWORD flags =
417 ISC_REQ_CONFIDENTIALITY |
418 ISC_REQ_REPLAY_DETECT |
419 ISC_REQ_SEQUENCE_DETECT |
420 ISC_REQ_STREAM;
421 ss = InitializeSecurityContext(&sch_ssock->cred_handle,
422 &sch_ssock->ctx_handle,
423 NULL,
424 flags, 0, 0,
425 &buf_desc_out, 0, NULL,
426 &buf_desc_out,
427 &flags, NULL);
428 if (ss == SEC_E_OK) {
429 /* May need to send TLS shutdown packets */
430 if (buf_out->cbBuffer > 0 && buf_out[0].pvBuffer) {
431 pj_status_t status;
432
433 status = circ_write(&ssock->ssl_write_buf,
434 buf_out[0].pvBuffer,
435 buf_out[0].cbBuffer);
436 if (status != PJ_SUCCESS) {
437 PJ_PERROR(1, (SNAME(ssock), status,
438 "Failed to queue shutdown packets"));
439 } else {
440 post_unlock_flush_write_buf = 1;
441 }
442 }
443 } else {
444 log_sec_err(1, SNAME(ssock), "Error in shutting down SSL", ss);
445 }
446 }
447
448 ssock->ssl_state = SSL_STATE_NULL;
449
450 if (SecIsValidHandle(&sch_ssock->ctx_handle)) {
451 DeleteSecurityContext(&sch_ssock->ctx_handle);
452 SecInvalidateHandle(&sch_ssock->ctx_handle);
453 }
454
455 if (SecIsValidHandle(&sch_ssock->cred_handle)) {
456 FreeCredentialsHandle(&sch_ssock->cred_handle);
457 SecInvalidateHandle(&sch_ssock->cred_handle);
458 }
459 circ_reset(&ssock->ssl_read_buf);
460 if (!post_unlock_flush_write_buf)
461 circ_reset(&ssock->ssl_write_buf);
462 circ_reset(&sch_ssock->decrypted_buf);
463
464 pj_lock_release(ssock->write_mutex);
465
466 if (post_unlock_flush_write_buf) {
467 pj_status_t flush_st;
468 flush_st = flush_ssl_write_buf(ssock, &ssock->shutdown_op_key,
469 0, 0);
470 circ_reset(&ssock->ssl_write_buf);
471 if (flush_st == PJ_EPENDING) {
472 PJ_LOG(5, (SNAME(ssock), "close_notify send pending"));
473 }
474 }
475
476 ssl_close_sockets(ssock);
477 }
478
479 /* Ciphers and certs */
480 static void ssl_ciphers_populate()
481 {
482 PCRYPT_CONTEXT_FUNCTIONS fn = NULL;
483 ULONG size = 0;
484 NTSTATUS s;
485
486 /* Populate once only */
487 if (ssl_cipher_num)
488 return;
489
490 s = BCryptEnumContextFunctions(CRYPT_LOCAL, L"SSL",
491 NCRYPT_SCHANNEL_INTERFACE,
492 &size, &fn);
493 if (s < 0) {
494 PJ_LOG(1,(SENDER, "Error in enumerating ciphers (code=0x%x)", s));
495 return;
496 }
497
498 /* Make sure schannel's pool is created */
499 sch_inc();
500 sch_dec();
501
502 for (ULONG i = 0; i < fn->cFunctions; i++) {
503 char tmp_buf[SZ_ALG_MAX_SIZE] = {0};
504 pj_str_t tmp_st;
505
506 pj_unicode_to_ansi(fn->rgpszFunctions[i], -1,
507 tmp_buf, sizeof(tmp_buf));
508 if (tmp_buf[0] == '\0')
509 continue;
510 pj_strdup2_with_null(sch_ssl.pool, &tmp_st, tmp_buf);
511
512 /* Unfortunately we do not get the ID here.
513 * Let's just set ID to (0x8000000 + i) for now.
514 */
515 ssl_ciphers[ssl_cipher_num].id = 0x8000000 + i;
516 ssl_ciphers[ssl_cipher_num].name = tmp_st.ptr;
517 ++ssl_cipher_num;
518 }
519
520 BCryptFreeBuffer(fn);
521 }
522
523 static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock)
524 {
525 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
526 SecPkgContext_CipherInfo ci;
527 SECURITY_STATUS ss;
528
529 if (!SecIsValidHandle(&sch_ssock->ctx_handle)) {
530 return PJ_TLS_UNKNOWN_CIPHER;
531 }
532
533 ss = QueryContextAttributes(&sch_ssock->ctx_handle,
534 SECPKG_ATTR_CIPHER_INFO,
535 &ci);
536 if (ss == SEC_E_OK) {
537 pj_ssl_cipher c = (pj_ssl_cipher)ci.dwCipherSuite;
538
539 /* Check if this is in the cipher list */
540 if (ssl_cipher_num < PJ_SSL_SOCK_MAX_CIPHERS &&
541 !pj_ssl_cipher_name(c))
542 {
543 char tmp_buf[SZ_ALG_MAX_SIZE+1] = {0};
544 unsigned i;
545
546 pj_unicode_to_ansi(ci.szCipherSuite, -1,
547 tmp_buf, sizeof(tmp_buf));
548 if (tmp_buf[0] == '\0')
549 return c;
550
551 /* If cipher is actually in the list and:
552 * - if ID is 0, update it, or
553 * - if ID does not match, return ID from our list.
554 */
555 for (i = 0; i < ssl_cipher_num; ++i) {
556 if (!pj_ansi_stricmp(ssl_ciphers[i].name, tmp_buf)) {
557 if (ssl_ciphers[i].id == 0)
558 ssl_ciphers[i].id = c;
559 else
560 c = ssl_ciphers[i].id;
561 break;
562 }
563 }
564
565 /* Add to cipher list if not found */
566 if (i == ssl_cipher_num) {
567 pj_str_t tmp_st;
568 pj_strdup2_with_null(sch_ssl.pool, &tmp_st, tmp_buf);
569
570 ssl_ciphers[ssl_cipher_num].id = c;
571 ssl_ciphers[ssl_cipher_num].name = tmp_st.ptr;
572 ++ssl_cipher_num;
573 }
574 }
575 return c;
576 }
577
578 return PJ_TLS_UNKNOWN_CIPHER;
579 }
580
581 static pj_status_t blob_to_str(DWORD enc_type, CERT_NAME_BLOB* blob,
582 DWORD flag, char *buf, unsigned buf_len)
583 {
584 DWORD ret;
585 ret = CertNameToStrA(enc_type, blob, flag, buf, buf_len);
586 if (ret <= 1) {
587 PJ_LOG(3,(SENDER, "Failed to convert cert blob to string"));
588 return PJ_ETOOSMALL;
589 }
590 return PJ_SUCCESS;
591 }
592
593
594 static pj_status_t file_time_to_time_val(const FILETIME* file_time,
595 pj_time_val* time_val)
596 {
597 FILETIME local_file_time;
598 SYSTEMTIME localTime;
599 pj_parsed_time pt;
600
601 if (!FileTimeToLocalFileTime(file_time, &local_file_time))
602 return PJ_RETURN_OS_ERROR(GetLastError());
603
604 if (!FileTimeToSystemTime(&local_file_time, &localTime))
605 return PJ_RETURN_OS_ERROR(GetLastError());
606
607 pj_bzero(&pt, sizeof(pt));
608 pt.year = localTime.wYear;
609 pt.mon = localTime.wMonth - 1;
610 pt.day = localTime.wDay;
611 pt.wday = localTime.wDayOfWeek;
612
613 pt.hour = localTime.wHour;
614 pt.min = localTime.wMinute;
615 pt.sec = localTime.wSecond;
616 pt.msec = localTime.wMilliseconds;
617
618 return pj_time_encode(&pt, time_val);
619 }
620
621
622 static void cert_parse_info(pj_pool_t* pool, pj_ssl_cert_info* ci,
623 const CERT_CONTEXT *cert)
624 {
625 PCERT_INFO cert_info = cert->pCertInfo;
626 char buf[512];
627 pj_uint8_t serial_no[20];
628 unsigned serial_size;
629 pj_bool_t update_needed;
630 pj_status_t status;
631
632 /* Get issuer & serial no first */
633 status = blob_to_str(cert->dwCertEncodingType, &cert_info->Issuer,
634 CERT_SIMPLE_NAME_STR,
635 buf, sizeof(buf));
636
637 serial_size = PJ_MIN(cert_info->SerialNumber.cbData, sizeof(serial_no));
638 pj_memcpy(&serial_no, cert_info->SerialNumber.pbData, serial_size);
639
640 /* Check if the contents need to be updated */
641 update_needed = status == PJ_SUCCESS &&
642 (pj_strcmp2(&ci->issuer.info, buf) ||
643 pj_memcmp(ci->serial_no, serial_no, serial_size));
644 if (!update_needed)
645 return;
646
647 /* Update info */
648
649 pj_bzero(ci, sizeof(pj_ssl_cert_info));
650
651 /* Version */
652 ci->version = cert_info->dwVersion;
653
654 /* Issuer */
655 pj_strdup2(pool, &ci->issuer.info, buf);
656 status = blob_to_str(cert->dwCertEncodingType, &cert_info->Issuer,
657 CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG,
658 buf, sizeof(buf));
659 if (status == PJ_SUCCESS)
660 pj_strdup2(pool, &ci->issuer.cn, buf);
661
662 /* Serial number */
663 pj_memcpy(ci->serial_no, serial_no, serial_size);
664
665 /* Subject */
666 status = blob_to_str(cert->dwCertEncodingType, &cert_info->Subject,
667 CERT_SIMPLE_NAME_STR,
668 buf, sizeof(buf));
669 if (status == PJ_SUCCESS)
670 pj_strdup2(pool, &ci->subject.info, buf);
671
672 status = blob_to_str(cert->dwCertEncodingType, &cert_info->Subject,
673 CERT_X500_NAME_STR | CERT_NAME_STR_NO_PLUS_FLAG,
674 buf, sizeof(buf));
675 if (status == PJ_SUCCESS)
676 pj_strdup2(pool, &ci->subject.cn, buf);
677
678 /* Validity */
679 file_time_to_time_val(&cert_info->NotAfter, &ci->validity.end);
680 file_time_to_time_val(&cert_info->NotBefore, &ci->validity.start);
681 ci->validity.gmt = 0;
682
683 /* Subject Alternative Name extension */
684 while (1) {
685 PCERT_EXTENSION ext = CertFindExtension(szOID_SUBJECT_ALT_NAME2,
686 cert_info->cExtension,
687 cert_info->rgExtension);
688 if (!ext)
689 break;
690
691 CERT_ALT_NAME_INFO* alt_name_info = NULL;
692 DWORD alt_name_info_size = 0;
693 BOOL rv;
694 rv = CryptDecodeObjectEx(cert->dwCertEncodingType,
695 szOID_SUBJECT_ALT_NAME2,
696 ext->Value.pbData,
697 ext->Value.cbData,
698 CRYPT_DECODE_ALLOC_FLAG |
699 CRYPT_DECODE_NOCOPY_FLAG,
700 NULL,
701 &alt_name_info,
702 &alt_name_info_size);
703 if (!rv)
704 break;
705
706 ci->subj_alt_name.entry = pj_pool_calloc(
707 pool, alt_name_info->cAltEntry,
708 sizeof(*ci->subj_alt_name.entry));
709 if (!ci->subj_alt_name.entry) {
710 PJ_LOG(3,(SENDER, "Failed to allocate memory for SubjectAltName"));
711 LocalFree(alt_name_info);
712 break;
713 }
714
715 for (unsigned i = 0; i < alt_name_info->cAltEntry; ++i) {
716 CERT_ALT_NAME_ENTRY *ane = &alt_name_info->rgAltEntry[i];
717 pj_ssl_cert_name_type type;
718 unsigned len = 0;
719
720 switch (ane->dwAltNameChoice) {
721 case CERT_ALT_NAME_DNS_NAME:
722 type = PJ_SSL_CERT_NAME_DNS;
723 len = pj_unicode_to_ansi(ane->pwszDNSName, -1,
724 buf, sizeof(buf)) != NULL;
725 break;
726 case CERT_ALT_NAME_IP_ADDRESS:
727 type = PJ_SSL_CERT_NAME_IP;
728 pj_inet_ntop2(ane->IPAddress.cbData == sizeof(pj_in6_addr)?
729 pj_AF_INET6() : pj_AF_INET(),
730 ane->IPAddress.pbData, buf, sizeof(buf));
731 break;
732 case CERT_ALT_NAME_URL:
733 type = PJ_SSL_CERT_NAME_URI;
734 len = pj_unicode_to_ansi(ane->pwszURL, -1,
735 buf, sizeof(buf)) != NULL;
736 break;
737 case CERT_ALT_NAME_RFC822_NAME:
738 type = PJ_SSL_CERT_NAME_RFC822;
739 len = pj_unicode_to_ansi(ane->pwszRfc822Name, -1,
740 buf, sizeof(buf)) != NULL;
741 break;
742 default:
743 type = PJ_SSL_CERT_NAME_UNKNOWN;
744 break;
745 }
746
747 if (len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
748 ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
749 pj_strdup2(pool,
750 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
751 buf);
752 ci->subj_alt_name.cnt++;
753 }
754 }
755
756 /* Done parsing Subject Alt Name */
757 LocalFree(alt_name_info);
758 break;
759 }
760 }
761
762 static void ssl_update_certs_info(pj_ssl_sock_t *ssock)
763 {
764 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
765 CERT_CONTEXT *cert_ctx = NULL;
766 SECURITY_STATUS ss;
767
768 if (!SecIsValidHandle(&sch_ssock->ctx_handle)) {
769 return;
770 }
771
772 ss = QueryContextAttributes(&sch_ssock->ctx_handle,
773 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
774 &cert_ctx);
775
776 if (ss != SEC_E_OK || !cert_ctx) {
777 if (!ssock->is_server)
778 log_sec_err(1, SNAME(ssock),
779 "Failed to retrieve remote certificate", ss);
780 } else {
781 cert_parse_info(ssock->pool, &ssock->remote_cert_info, cert_ctx);
782 CertFreeCertificateContext(cert_ctx);
783 }
784
785 ss = QueryContextAttributes(&sch_ssock->ctx_handle,
786 SECPKG_ATTR_LOCAL_CERT_CONTEXT,
787 &cert_ctx);
788
789 if (ss != SEC_E_OK || !cert_ctx) {
790 if (ssock->is_server)
791 log_sec_err(3, SNAME(ssock),
792 "Failed to retrieve local certificate", ss);
793 }
794 else {
795 cert_parse_info(ssock->pool, &ssock->local_cert_info, cert_ctx);
796 CertFreeCertificateContext(cert_ctx);
797 }
798 }
799
800 /* SSL session functions */
801 static void ssl_set_state(pj_ssl_sock_t* ssock, pj_bool_t is_server)
802 {
803 /* Nothing to do */
804 PJ_UNUSED_ARG(ssock);
805 PJ_UNUSED_ARG(is_server);
806 }
807
808 static void ssl_set_peer_name(pj_ssl_sock_t* ssock)
809 {
810 /* Nothing to do */
811 PJ_UNUSED_ARG(ssock);
812 }
813
814
815 static PCCERT_CONTEXT create_self_signed_cert()
816 {
817 if (!sch_ssl.self_signed_cert) {
818 CERT_EXTENSIONS cert_ext = { 0 };
819 BYTE cert_name_buffer[64];
820 CERT_NAME_BLOB cert_name;
821 cert_name.pbData = cert_name_buffer;
822 cert_name.cbData = ARRAYSIZE(cert_name_buffer);
823
824 if (!CertStrToNameA(X509_ASN_ENCODING, SELF_SIGNED_CERT_SUBJECT,
825 CERT_X500_NAME_STR, NULL,
826 cert_name.pbData, &cert_name.cbData, NULL))
827 {
828 return NULL;
829 }
830
831 sch_ssl.self_signed_cert = CertCreateSelfSignCertificate(
832 0, &cert_name, 0, NULL,
833 NULL, NULL, NULL,
834 &cert_ext);
835 }
836
837 /* May return NULL on any failure */
838 return CertDuplicateCertificateContext(sch_ssl.self_signed_cert);
839 }
840
841 static PCCERT_CONTEXT find_cert_in_stores(pj_ssl_cert_lookup_type type,
842 const pj_str_t *keyword)
843 {
844 PCCERT_CONTEXT cert = NULL;
845
846 LOG_DEBUG3(SENDER,
847 "Looking up certificate with criteria: type=%d keyword=%.*s",
848 type, (type==PJ_SSL_CERT_LOOKUP_FINGERPRINT? 4:keyword->slen),
849 (type==PJ_SSL_CERT_LOOKUP_FINGERPRINT?"[..]":keyword->ptr));
850
851 /* Find in Current User & Local Machine stores */
852 DWORD flags[2] = { CERT_SYSTEM_STORE_CURRENT_USER,
853 CERT_SYSTEM_STORE_LOCAL_MACHINE };
854
855 for (int i = 0; (!cert && i < PJ_ARRAY_SIZE(flags)); ++i) {
856 HCERTSTORE store = NULL;
857
858 /* Open the store */
859 store = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING,
860 0, flags[i], L"MY");
861 if (!store) {
862 log_sec_err(1, SENDER, "Error opening store", GetLastError());
863 continue;
864 }
865
866 LOG_DEBUG1(SENDER, "Looking up certificate in store: %s",
867 (i==0? "Current User" : "Local Machine"));
868
869 /* Lookup based on type */
870
871 if (type == PJ_SSL_CERT_LOOKUP_SUBJECT) {
872 /* CertFindCertificateInStore requires null-terminated string.
873 * The caller (ssl_sock_imp_common.c) always uses
874 * pj_strdup_with_null(), so keyword->ptr is safe to use
875 * directly here.
876 */
877 cert = CertFindCertificateInStore(
878 store, X509_ASN_ENCODING, 0,
879 CERT_FIND_SUBJECT_STR_A, keyword->ptr, NULL);
880
881 } else if (type == PJ_SSL_CERT_LOOKUP_FINGERPRINT) {
882 CRYPT_HASH_BLOB hash = {0};
883 hash.cbData = (DWORD)keyword->slen;
884 hash.pbData = (BYTE*)keyword->ptr;
885 cert = CertFindCertificateInStore(
886 store, X509_ASN_ENCODING,
887 0, CERT_FIND_SHA1_HASH, &hash, NULL);
888
889 } else if (type == PJ_SSL_CERT_LOOKUP_FRIENDLY_NAME) {
890 WCHAR buf[256];
891 DWORD buf_size;
892
893 if (keyword->slen >= PJ_ARRAY_SIZE(buf)) {
894 PJ_LOG(1,(SENDER,"Cannot lookup certificate, friendly name "
895 "keyword is too long (max=%d)",
896 (int)PJ_ARRAY_SIZE(buf)));
897 } else {
898 cert = NULL;
899 while (1) {
900 cert = CertEnumCertificatesInStore(store, cert);
901 if (!cert)
902 break;
903
904 buf_size = sizeof(buf);
905 if (CertGetCertificateContextProperty(
906 cert, CERT_FRIENDLY_NAME_PROP_ID, buf, &buf_size))
907 {
908 char buf2[256];
909 pj_ssize_t buf2_len;
910
911 /* The output buf is null-terminated */
912 pj_unicode_to_ansi(buf, -1, buf2, sizeof(buf2));
913 buf2_len = pj_ansi_strlen(buf2);
914 if (keyword->slen == buf2_len &&
915 !pj_memcmp(buf2, keyword->ptr, buf2_len))
916 {
917 /* Found it */
918 break;
919 }
920 }
921 }
922 }
923 }
924
925 CertCloseStore(store, 0);
926 }
927
928 if (!cert) {
929 PJ_LOG(1,(SENDER,
930 "Cannot find certificate with criteria: "
931 "type=%d keyword=%.*s", type,
932 (type==PJ_SSL_CERT_LOOKUP_FINGERPRINT? 4:keyword->slen),
933 (type==PJ_SSL_CERT_LOOKUP_FINGERPRINT?"[..]":keyword->ptr)));
934 }
935 return cert;
936 }
937
938
939 /* Initialize credentials */
940 static pj_status_t init_creds(pj_ssl_sock_t* ssock)
941 {
942 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
943 SCH_CREDENTIALS creds = { 0 };
944 unsigned param_cnt = 0;
945 TLS_PARAMETERS param = {0};
946 SECURITY_STATUS ss;
947
948 creds.dwVersion = SCH_CREDENTIALS_VERSION;
949 creds.dwFlags = SCH_USE_STRONG_CRYPTO;
950
951 /* Setup Protocol version */
952 if (ssock->param.proto != PJ_SSL_SOCK_PROTO_DEFAULT &&
953 ssock->param.proto != PJ_SSL_SOCK_PROTO_ALL)
954 {
955 DWORD tmp = 0;
956 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3)
957 tmp |= SP_PROT_TLS1_3;
958 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2)
959 tmp |= SP_PROT_TLS1_2;
960 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1)
961 tmp |= SP_PROT_TLS1_1;
962 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1)
963 tmp |= SP_PROT_TLS1_0;
964 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3)
965 tmp |= SP_PROT_SSL3;
966 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL2)
967 tmp |= SP_PROT_SSL2;
968 if (tmp) {
969 param_cnt = 1;
970 param.grbitDisabledProtocols = ~tmp;
971 LOG_DEBUG1(SNAME(ssock), "grbitDisabledProtocols=0x%x", (~tmp));
972 }
973 }
974
975 /* Setup the TLS certificate */
976 if (ssock->cert &&
977 ssock->cert->criteria.type != PJ_SSL_CERT_LOOKUP_NONE &&
978 !sch_ssock->cert_ctx)
979 {
980 /* Search certificate from stores */
981 sch_ssock->cert_ctx =
982 find_cert_in_stores(ssock->cert->criteria.type,
983 &ssock->cert->criteria.keyword);
984 }
985
986 if (ssock->is_server) {
987 if (!ssock->cert ||
988 ssock->cert->criteria.type == PJ_SSL_CERT_LOOKUP_NONE)
989 {
990 /* No certificate specified, use self-signed cert */
991 sch_ssock->cert_ctx = create_self_signed_cert();
992 PJ_LOG(2,(SNAME(ssock),
993 "Warning: certificate is not specified for "
994 "TLS server, using a self-signed certificate."));
995 }
996 } else {
997 creds.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
998 }
999
1000 if (sch_ssock->cert_ctx) {
1001 creds.cCreds = 1;
1002 creds.paCred = &sch_ssock->cert_ctx;
1003 }
1004
1005 /* Verification */
1006 if (!ssock->is_server) {
1007 if (ssock->param.verify_peer)
1008 creds.dwFlags |= SCH_CRED_AUTO_CRED_VALIDATION |
1009 SCH_CRED_REVOCATION_CHECK_CHAIN;
1010 else
1011 creds.dwFlags |= SCH_CRED_MANUAL_CRED_VALIDATION;
1012 } else {
1013 if (ssock->param.verify_peer)
1014 creds.dwFlags |= SCH_CRED_REVOCATION_CHECK_CHAIN;
1015 }
1016
1017 /* Now init the credentials */
1018 if (param_cnt) {
1019 creds.cTlsParameters = param_cnt;
1020 creds.pTlsParameters = &param;
1021 }
1022
1023 ss = AcquireCredentialsHandle(NULL, UNISP_NAME,
1024 ssock->is_server? SECPKG_CRED_INBOUND :
1025 SECPKG_CRED_OUTBOUND,
1026 NULL, &creds, NULL, NULL,
1027 &sch_ssock->cred_handle, NULL);
1028 if (ss < 0) {
1029 log_sec_err(1, SNAME(ssock),
1030 "Failed in AcquireCredentialsHandle()", ss);
1031
1032 return sec_err_to_pj(ss);
1033 }
1034
1035 return PJ_SUCCESS;
1036 }
1037
1038 /* Initialize credentials using older data type SCHANNEL_CRED */
1039 static pj_status_t init_creds_old(pj_ssl_sock_t* ssock)
1040 {
1041 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
1042 SCHANNEL_CRED creds = { 0 };
1043 SECURITY_STATUS ss;
1044
1045 creds.dwVersion = SCHANNEL_CRED_VERSION;
1046 creds.dwFlags = SCH_USE_STRONG_CRYPTO;
1047
1048 /* Setup Protocol version */
1049 if (ssock->param.proto != PJ_SSL_SOCK_PROTO_DEFAULT &&
1050 ssock->param.proto != PJ_SSL_SOCK_PROTO_ALL)
1051 {
1052 DWORD tmp = 0;
1053 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3)
1054 tmp |= SP_PROT_TLS1_3;
1055 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2)
1056 tmp |= SP_PROT_TLS1_2;
1057 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1)
1058 tmp |= SP_PROT_TLS1_1;
1059 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1)
1060 tmp |= SP_PROT_TLS1_0;
1061 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3)
1062 tmp |= SP_PROT_SSL3;
1063 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL2)
1064 tmp |= SP_PROT_SSL2;
1065 if (tmp) {
1066 creds.grbitEnabledProtocols = tmp;
1067 LOG_DEBUG1(SNAME(ssock), "grbitEnabledProtocols=0x%x", tmp);
1068 }
1069 }
1070
1071 /* Setup the TLS certificate */
1072 if (ssock->cert &&
1073 ssock->cert->criteria.type != PJ_SSL_CERT_LOOKUP_NONE &&
1074 !sch_ssock->cert_ctx)
1075 {
1076 /* Search certificate from stores */
1077 sch_ssock->cert_ctx =
1078 find_cert_in_stores(ssock->cert->criteria.type,
1079 &ssock->cert->criteria.keyword);
1080 }
1081
1082 if (ssock->is_server) {
1083 if (!ssock->cert ||
1084 ssock->cert->criteria.type == PJ_SSL_CERT_LOOKUP_NONE)
1085 {
1086 /* No certificate specified, use self-signed cert */
1087 sch_ssock->cert_ctx = create_self_signed_cert();
1088 PJ_LOG(2,(SNAME(ssock),
1089 "Warning: TLS server does not specify a "
1090 "certificate, use a self-signed certificate"));
1091 }
1092 } else {
1093 creds.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
1094 }
1095
1096 if (sch_ssock->cert_ctx) {
1097 creds.cCreds = 1;
1098 creds.paCred = &sch_ssock->cert_ctx;
1099 }
1100
1101 /* Verification */
1102 if (!ssock->is_server) {
1103 if (ssock->param.verify_peer)
1104 creds.dwFlags |= SCH_CRED_AUTO_CRED_VALIDATION |
1105 SCH_CRED_REVOCATION_CHECK_CHAIN;
1106 else
1107 creds.dwFlags |= SCH_CRED_MANUAL_CRED_VALIDATION;
1108 } else {
1109 if (ssock->param.verify_peer)
1110 creds.dwFlags |= SCH_CRED_REVOCATION_CHECK_CHAIN;
1111 }
1112
1113 ss = AcquireCredentialsHandle(NULL, UNISP_NAME,
1114 ssock->is_server? SECPKG_CRED_INBOUND :
1115 SECPKG_CRED_OUTBOUND,
1116 NULL, &creds, NULL, NULL,
1117 &sch_ssock->cred_handle, NULL);
1118 if (ss < 0) {
1119 log_sec_err(1, SNAME(ssock),
1120 "Failed in AcquireCredentialsHandle()", ss);
1121
1122 return sec_err_to_pj(ss);
1123 }
1124
1125 return PJ_SUCCESS;
1126 }
1127
1128
1129
1130 static void verify_remote_cert(pj_ssl_sock_t* ssock)
1131 {
1132 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
1133 CERT_CONTEXT *cert_ctx = NULL;
1134 CERT_CHAIN_CONTEXT *chain_ctx = NULL;
1135 CERT_CHAIN_PARA chain_para = {0};
1136 DWORD info, err;
1137 SECURITY_STATUS ss;
1138
1139 ss = QueryContextAttributes(&sch_ssock->ctx_handle,
1140 SECPKG_ATTR_REMOTE_CERT_CONTEXT,
1141 &cert_ctx);
1142 if (ss != SEC_E_OK || !cert_ctx) {
1143 if (!ssock->is_server ||
1144 (ssock->is_server && ssock->param.require_client_cert))
1145 {
1146 log_sec_err(1, SNAME(ssock), "Error querying remote cert", ss);
1147 }
1148 goto on_return;
1149 }
1150
1151 chain_para.cbSize = sizeof(chain_para);
1152 if (!CertGetCertificateChain(HCCE_CURRENT_USER,
1153 (PCCERT_CONTEXT)cert_ctx,
1154 NULL, NULL, &chain_para, 0, 0,
1155 &chain_ctx))
1156 {
1157 log_sec_err(1, SNAME(ssock),
1158 "Failed to get remote cert chain for verification",
1159 GetLastError());
1160 goto on_return;
1161 }
1162
1163 info = chain_ctx->TrustStatus.dwInfoStatus;
1164 err = chain_ctx->TrustStatus.dwErrorStatus;
1165
1166 if (err == CERT_TRUST_NO_ERROR) {
1167 ssock->verify_status = PJ_SUCCESS;
1168 return;
1169 }
1170
1171 if (err & CERT_TRUST_IS_NOT_TIME_VALID)
1172 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
1173 if (err & CERT_TRUST_IS_REVOKED)
1174 ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
1175 if (err & CERT_TRUST_IS_NOT_SIGNATURE_VALID)
1176 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
1177 if (err & CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
1178 ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
1179 if (err & CERT_TRUST_IS_UNTRUSTED_ROOT)
1180 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
1181 if (err & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
1182 ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
1183 if (err & CERT_TRUST_IS_CYCLIC)
1184 ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
1185 if (err & CERT_TRUST_INVALID_EXTENSION ||
1186 err & CERT_TRUST_INVALID_POLICY_CONSTRAINTS ||
1187 err & CERT_TRUST_INVALID_BASIC_CONSTRAINTS ||
1188 err & CERT_TRUST_INVALID_NAME_CONSTRAINTS ||
1189 err & CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT ||
1190 err & CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT ||
1191 err & CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT ||
1192 err & CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT)
1193 {
1194 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
1195 }
1196 if (err & CERT_TRUST_IS_OFFLINE_REVOCATION)
1197 ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
1198 if (err & CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY)
1199 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
1200 if (err & CERT_TRUST_IS_EXPLICIT_DISTRUST)
1201 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
1202 if (err & CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT)
1203 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
1204 if (err & CERT_TRUST_HAS_WEAK_SIGNATURE)
1205 ssock->verify_status |= PJ_SSL_CERT_EWEAK_SIGNATURE;
1206
1207 if (err & CERT_TRUST_IS_PARTIAL_CHAIN)
1208 ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
1209 if (err & CERT_TRUST_CTL_IS_NOT_TIME_VALID)
1210 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
1211 if (err & CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID)
1212 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
1213 if (err & CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE)
1214 ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
1215
1216 /* Some unknown error */
1217 if (ssock->verify_status == PJ_SUCCESS)
1218 ssock->verify_status = PJ_SSL_CERT_EUNKNOWN;
1219
1220 on_return:
1221 if (chain_ctx)
1222 CertFreeCertificateChain(chain_ctx);
1223 if (cert_ctx)
1224 CertFreeCertificateContext(cert_ctx);
1225 }
1226
1227
1228 static pj_status_t ssl_do_handshake(pj_ssl_sock_t* ssock)
1229 {
1230 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
1231 pj_bool_t renego_req;
1232 pj_size_t data_in_size = 0;
1233 pj_uint8_t* data_in = NULL;
1234 SECURITY_STATUS ss;
1235 pj_status_t status = PJ_EPENDING;
1236 pj_status_t status2;
1237
1238 pj_lock_acquire(ssock->write_mutex);
1239
1240 /* Create credential handle, if not yet */
1241 if (!SecIsValidHandle(&sch_ssock->cred_handle)) {
1242 status2 = init_creds(ssock);
1243 if (status2 != PJ_SUCCESS) {
1244 /* On error, retry using older version of credential */
1245 status2 = init_creds_old(ssock);
1246 }
1247 if (status2 != PJ_SUCCESS) {
1248 status = status2;
1249 goto on_return;
1250 }
1251 }
1252
1253 /* Is this a renegotiation request? */
1254 renego_req = (ssock->ssl_state == SSL_STATE_ESTABLISHED);
1255
1256 /* Start handshake iteration */
1257
1258 pj_lock_acquire(ssock->ssl_read_buf_mutex);
1259
1260 if (!circ_empty(&ssock->ssl_read_buf) && !renego_req) {
1261 data_in = sch_ssock->read_buf;
1262 data_in_size = PJ_MIN(sch_ssock->read_buf_cap,
1263 circ_size(&ssock->ssl_read_buf));
1264 circ_read(&ssock->ssl_read_buf, data_in, data_in_size);
1265 }
1266
1267 SecBuffer buf_in[2] = { {0} };
1268 buf_in[0].BufferType = SECBUFFER_TOKEN;
1269 buf_in[0].pvBuffer = data_in;
1270 buf_in[0].cbBuffer = (ULONG)data_in_size;
1271 buf_in[1].BufferType = SECBUFFER_EMPTY;
1272 SecBufferDesc buf_desc_in = { 0 };
1273 buf_desc_in.ulVersion = SECBUFFER_VERSION;
1274 buf_desc_in.cBuffers = ARRAYSIZE(buf_in);
1275 buf_desc_in.pBuffers = buf_in;
1276
1277 SecBuffer buf_out[1] = { {0} };
1278 buf_out[0].BufferType = SECBUFFER_TOKEN;
1279 buf_out[0].pvBuffer = sch_ssock->write_buf;
1280 buf_out[0].cbBuffer = (ULONG)sch_ssock->write_buf_cap;
1281 SecBufferDesc buf_desc_out = { 0 };
1282 buf_desc_out.ulVersion = SECBUFFER_VERSION;
1283 buf_desc_out.cBuffers = ARRAYSIZE(buf_out);
1284 buf_desc_out.pBuffers = buf_out;
1285
1286 /* As client */
1287 if (!ssock->is_server) {
1288 DWORD flags =
1289 ISC_REQ_USE_SUPPLIED_CREDS |
1290 ISC_REQ_CONFIDENTIALITY |
1291 ISC_REQ_REPLAY_DETECT |
1292 ISC_REQ_SEQUENCE_DETECT |
1293 ISC_REQ_STREAM;
1294
1295 ss = InitializeSecurityContext(
1296 &sch_ssock->cred_handle,
1297 SecIsValidHandle(&sch_ssock->ctx_handle)?
1298 &sch_ssock->ctx_handle : NULL,
1299 (SEC_CHAR*)ssock->param.server_name.ptr,
1300 flags, 0, 0,
1301 data_in_size? &buf_desc_in : NULL,
1302 0,
1303 SecIsValidHandle(&sch_ssock->ctx_handle)?
1304 NULL : &sch_ssock->ctx_handle,
1305 &buf_desc_out, &flags, NULL);
1306 }
1307
1308 /* As server */
1309 else {
1310 DWORD flags =
1311 ASC_REQ_CONFIDENTIALITY |
1312 ASC_REQ_REPLAY_DETECT |
1313 ASC_REQ_SEQUENCE_DETECT |
1314 ASC_REQ_STREAM;
1315
1316 if (ssock->param.require_client_cert)
1317 flags |= ASC_REQ_MUTUAL_AUTH;
1318
1319 ss = AcceptSecurityContext(
1320 &sch_ssock->cred_handle,
1321 SecIsValidHandle(&sch_ssock->ctx_handle) ?
1322 &sch_ssock->ctx_handle : NULL,
1323 data_in_size ? &buf_desc_in : NULL,
1324 flags, 0,
1325 SecIsValidHandle(&sch_ssock->ctx_handle) ?
1326 NULL : &sch_ssock->ctx_handle,
1327 &buf_desc_out, &flags, NULL);
1328 }
1329
1330 /* Check for any unprocessed input data, put it back to buffer */
1331 if (buf_in[1].BufferType==SECBUFFER_EXTRA && buf_in[1].cbBuffer>0) {
1332 circ_read_cancel(&ssock->ssl_read_buf, buf_in[1].cbBuffer);
1333 }
1334
1335 if (ss == SEC_E_OK && !renego_req) {
1336 SECURITY_STATUS ss2;
1337
1338 /* Handshake completed! */
1339 ssock->ssl_state = SSL_STATE_ESTABLISHED;
1340 status = PJ_SUCCESS;
1341 PJ_LOG(3, (SNAME(ssock), "TLS handshake completed!"));
1342
1343 /* Get stream sizes */
1344 ss2 = QueryContextAttributes(&sch_ssock->ctx_handle,
1345 SECPKG_ATTR_STREAM_SIZES,
1346 &sch_ssock->strm_sizes);
1347 if (ss2 != SEC_E_OK) {
1348 log_sec_err(1, SNAME(ssock), "Failed to query stream sizes", ss2);
1349 ssl_reset_sock_state(ssock);
1350 status = sec_err_to_pj(ss2);
1351 }
1352
1353 /* Adjust maximum message size to our allocated buffer size */
1354 if (sch_ssock->write_buf) {
1355 pj_size_t max_msg = sch_ssock->write_buf_cap -
1356 sch_ssock->strm_sizes.cbHeader -
1357 sch_ssock->strm_sizes.cbTrailer;
1358
1359 sch_ssock->strm_sizes.cbMaximumMessage =
1360 PJ_MIN((ULONG)max_msg,
1361 sch_ssock->strm_sizes.cbMaximumMessage);
1362 }
1363
1364 /* Manually verify remote cert */
1365 if (!ssock->param.verify_peer)
1366 verify_remote_cert(ssock);
1367 }
1368
1369 else if (ss == SEC_I_COMPLETE_NEEDED ||
1370 ss == SEC_I_COMPLETE_AND_CONTINUE)
1371 {
1372 /* Perhaps CompleteAuthToken() is unnecessary for Schannel, but
1373 * the sample code seems to call it.
1374 */
1375 LOG_DEBUG_ERR(SNAME(ssock), "Handshake progress", ss);
1376 ss = CompleteAuthToken(&sch_ssock->ctx_handle, &buf_desc_out);
1377 if (ss != SEC_E_OK) {
1378 log_sec_err(1, SNAME(ssock),
1379 "Handshake error in CompleteAuthToken()", ss);
1380 status = sec_err_to_pj(ss);
1381 }
1382 }
1383
1384 else if (ss == SEC_I_CONTINUE_NEEDED)
1385 {
1386 LOG_DEBUG_ERR(SNAME(ssock), "Handshake progress", ss);
1387 }
1388
1389 else if (ss == SEC_E_INCOMPLETE_MESSAGE)
1390 {
1391 LOG_DEBUG_ERR(SNAME(ssock), "Handshake progress", ss);
1392
1393 /* Put back the incomplete message */
1394 circ_read_cancel(&ssock->ssl_read_buf, data_in_size);
1395 }
1396
1397 else if (!renego_req) {
1398 /* Handshake failed */
1399 log_sec_err(1, SNAME(ssock), "Handshake failed!", ss);
1400 status = sec_err_to_pj(ss);
1401 }
1402
1403 pj_lock_release(ssock->ssl_read_buf_mutex);
1404
1405 if ((ss == SEC_E_OK || ss == SEC_I_CONTINUE_NEEDED) &&
1406 buf_out[0].cbBuffer > 0 && buf_out[0].pvBuffer)
1407 {
1408 /* Queue output data to send */
1409 status2 = circ_write(&ssock->ssl_write_buf, buf_out[0].pvBuffer,
1410 buf_out[0].cbBuffer);
1411 if (status2 != PJ_SUCCESS) {
1412 PJ_PERROR(1,(SNAME(ssock), status2,
1413 "Failed to queue handshake packets"));
1414 status = status2;
1415 }
1416 }
1417
1418 on_return:
1419 pj_lock_release(ssock->write_mutex);
1420
1421 return status;
1422 }
1423
1424 static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock)
1425 {
1426 PJ_LOG(3, (SNAME(ssock), "App requested renegotiation.."));
1427
1428 /* Nothing to do, SSL sock common will invoke ssl_do_handshake() */
1429 return PJ_SUCCESS;
1430 }
1431
1432 static int find_sec_buffer(const SecBuffer* buf, int buf_cnt,
1433 unsigned long sec_type)
1434 {
1435 for (int i = 0; i < buf_cnt; ++i)
1436 if (buf[i].BufferType == sec_type)
1437 return i;
1438 return -1;
1439 }
1440
1441 static pj_status_t ssl_read(pj_ssl_sock_t* ssock, void* data, int* size)
1442 {
1443 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
1444 pj_size_t size_ = 0;
1445 pj_uint8_t* data_ = NULL;
1446 SECURITY_STATUS ss;
1447 pj_status_t status = PJ_SUCCESS;
1448 int i, requested = *size;
1449 pj_size_t need = (pj_size_t)*size;
1450
1451 /* Avoid compile warning of unused debugging var */
1452 PJ_UNUSED_ARG(requested);
1453
1454 pj_lock_acquire(ssock->ssl_read_buf_mutex);
1455
1456 /* Try read from the decrypted buffer */
1457 size_ = circ_size(&sch_ssock->decrypted_buf);
1458 if (need <= size_) {
1459 /* Got all from the decrypted buffer */
1460 circ_read(&sch_ssock->decrypted_buf, data, need);
1461 *size = (int)need;
1462 LOG_DEBUG1(SNAME(ssock),
1463 "Read %d: returned all from decrypted buffer.", requested);
1464 pj_lock_release(ssock->ssl_read_buf_mutex);
1465 return PJ_SUCCESS;
1466 }
1467
1468 /* Get all data of the decrypted buffer, then decrypt more */
1469 LOG_DEBUG2(SNAME(ssock),
1470 "Read %d: %d from decrypted buffer..", requested, size_);
1471 circ_read(&sch_ssock->decrypted_buf, data, size_);
1472 *size = (int)size_;
1473 need -= (int)size_;
1474
1475 /* Decrypt data of network input buffer */
1476 if (!circ_empty(&ssock->ssl_read_buf)) {
1477 data_ = sch_ssock->read_buf;
1478 size_ = PJ_MIN(sch_ssock->read_buf_cap,
1479 circ_size(&ssock->ssl_read_buf));
1480 circ_read(&ssock->ssl_read_buf, data_, size_);
1481 } else {
1482 LOG_DEBUG2(SNAME(ssock), "Read %d: no data to decrypt, returned %d.",
1483 requested, *size);
1484 pj_lock_release(ssock->ssl_read_buf_mutex);
1485 return PJ_SUCCESS;
1486 }
1487
1488 SecBuffer buf[4] = { {0} };
1489 buf[0].BufferType = SECBUFFER_DATA;
1490 buf[0].pvBuffer = data_;
1491 buf[0].cbBuffer = (ULONG)size_;
1492 buf[1].BufferType = SECBUFFER_EMPTY;
1493 buf[2].BufferType = SECBUFFER_EMPTY;
1494 buf[3].BufferType = SECBUFFER_EMPTY;
1495 SecBufferDesc buf_desc = { 0 };
1496 buf_desc.ulVersion = SECBUFFER_VERSION;
1497 buf_desc.cBuffers = ARRAYSIZE(buf);
1498 buf_desc.pBuffers = buf;
1499
1500 ss = DecryptMessage(&sch_ssock->ctx_handle, &buf_desc, 0, NULL);
1501
1502 if (ss == SEC_E_OK) {
1503 /* Check for any unprocessed input data, put it back to buffer */
1504 i = find_sec_buffer(buf, ARRAYSIZE(buf), SECBUFFER_EXTRA);
1505 if (i >= 0) {
1506 circ_read_cancel(&ssock->ssl_read_buf, buf[i].cbBuffer);
1507 }
1508
1509 /* Process any decrypted data */
1510 i = find_sec_buffer(buf, ARRAYSIZE(buf), SECBUFFER_DATA);
1511 if (i >= 0) {
1512 pj_uint8_t *p = buf[i].pvBuffer;
1513 pj_size_t len = buf[i].cbBuffer;
1514 if (need <= len) {
1515 /* All requested fulfilled, may have excess */
1516 pj_memcpy((pj_uint8_t*)data + *size, p, need);
1517 *size += (int)need;
1518 len -= need;
1519 p += need;
1520
1521 /* Store any excess in the decrypted buffer */
1522 if (len)
1523 circ_write(&sch_ssock->decrypted_buf, p, len);
1524
1525 LOG_DEBUG2(SNAME(ssock), "Read %d: after decrypt, excess=%d",
1526 requested, len);
1527 } else {
1528 /* Not enough, just give everything */
1529 pj_memcpy((pj_uint8_t*)data + *size, p, len);
1530 *size += (int)len;
1531 LOG_DEBUG2(SNAME(ssock),"Read %d: after decrypt, only got %d",
1532 requested, len);
1533 }
1534 }
1535 }
1536
1537 else if (ss == SEC_E_INCOMPLETE_MESSAGE)
1538 {
1539 /* Put back the incomplete message */
1540 circ_read_cancel(&ssock->ssl_read_buf, size_);
1541 }
1542
1543 else if (ss == SEC_I_RENEGOTIATE) {
1544 /* Proceed renegotiation (initiated by local or remote) */
1545 PJ_LOG(3, (SNAME(ssock), "Renegotiation on progress"));
1546
1547 /* Check for any token for renegotiation */
1548 i = find_sec_buffer(buf, ARRAYSIZE(buf), SECBUFFER_EXTRA);
1549 if (i >= 0 && buf[i].pvBuffer && buf[i].cbBuffer) {
1550 /* Queue the token as input in the handshake */
1551 circ_write(&ssock->ssl_read_buf, buf[i].pvBuffer,
1552 buf[i].cbBuffer);
1553 }
1554
1555 /* Set SSL state as handshaking & reset handshake status */
1556 ssock->ssl_state = SSL_STATE_HANDSHAKING;
1557 ssock->handshake_status = PJ_EUNKNOWN;
1558 status = PJ_ETRYAGAIN;
1559 }
1560
1561 else if (ss == SEC_I_CONTEXT_EXPIRED)
1562 {
1563 PJ_LOG(3, (SNAME(ssock), "TLS connection closed"));
1564 //status = sec_err_to_pj(ss);
1565 status = PJ_EEOF;
1566 }
1567
1568 else {
1569 log_sec_err(1, SNAME(ssock), "Decrypt error", ss);
1570 status = sec_err_to_pj(ss);
1571 }
1572
1573 pj_lock_release(ssock->ssl_read_buf_mutex);
1574
1575 LOG_DEBUG2(SNAME(ssock), "Read %d: returned=%d.", requested, *size);
1576 return status;
1577 }
1578
1579
1580 /* Caller must hold ssock->write_mutex. */
1581 static pj_status_t ssl_write(pj_ssl_sock_t* ssock, const void* data,
1582 pj_ssize_t size, int* nwritten)
1583 {
1584 sch_ssl_sock_t* sch_ssock = (sch_ssl_sock_t*)ssock;
1585 pj_ssize_t total = 0;
1586 pj_status_t status = PJ_SUCCESS;
1587
1588 pj_lock_acquire(ssock->write_mutex);
1589
1590 while (total < size) {
1591 SECURITY_STATUS ss;
1592 pj_uint8_t *p_header, *p_data, *p_trailer;
1593 pj_ssize_t write_len, out_size;
1594
1595 write_len = PJ_MIN((pj_size_t)(size-total), sch_ssock->strm_sizes.cbMaximumMessage);
1596 p_header = sch_ssock->write_buf;
1597 p_data = p_header + sch_ssock->strm_sizes.cbHeader;
1598 p_trailer = p_data + write_len;
1599
1600 pj_memcpy(p_data, (pj_uint8_t*)data + total, write_len);
1601
1602 SecBuffer buf[4] = { {0} };
1603 buf[0].BufferType = SECBUFFER_STREAM_HEADER;
1604 buf[0].pvBuffer = p_header;
1605 buf[0].cbBuffer = sch_ssock->strm_sizes.cbHeader;
1606 buf[1].BufferType = SECBUFFER_DATA;
1607 buf[1].pvBuffer = p_data;
1608 buf[1].cbBuffer = (ULONG)write_len;
1609 buf[2].BufferType = SECBUFFER_STREAM_TRAILER;
1610 buf[2].pvBuffer = p_trailer;
1611 buf[2].cbBuffer = sch_ssock->strm_sizes.cbTrailer;
1612 buf[3].BufferType = SECBUFFER_EMPTY;
1613
1614 SecBufferDesc buf_desc = { 0 };
1615 buf_desc.ulVersion = SECBUFFER_VERSION;
1616 buf_desc.cBuffers = ARRAYSIZE(buf);
1617 buf_desc.pBuffers = buf;
1618
1619 ss = EncryptMessage(&sch_ssock->ctx_handle, 0, &buf_desc, 0);
1620
1621 if (ss != SEC_E_OK) {
1622 log_sec_err(1, SNAME(ssock), "Encrypt error", ss);
1623 status = sec_err_to_pj(ss);
1624 break;
1625 }
1626
1627 out_size = (pj_ssize_t)buf[0].cbBuffer + buf[1].cbBuffer +
1628 buf[2].cbBuffer;
1629 status = circ_write(&ssock->ssl_write_buf, sch_ssock->write_buf,
1630 out_size);
1631 if (status != PJ_SUCCESS) {
1632 PJ_PERROR(1, (SNAME(ssock), status,
1633 "Failed to queue outgoing packets"));
1634 break;
1635 }
1636
1637 total += write_len;
1638 }
1639
1640 pj_lock_release(ssock->write_mutex);
1641
1642 *nwritten = (int)total;
1643
1644 return status;
1645 }
1646
1647
1648 #endif /* PJ_HAS_SSL_SOCK */