Debian Codegraph @

Xpjproject/pjlib/src/pj/ssl_sock_gtls.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2018-2018 Teluu Inc. (http://www.teluu.com)
3 * Copyright (C) 2014-2017 Savoir-faire Linux.
4 * (https://www.savoirfairelinux.com)
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21 #include <pj/ssl_sock.h>
22 #include <pj/activesock.h>
23 #include <pj/compat/socket.h>
24 #include <pj/assert.h>
25 #include <pj/errno.h>
26 #include <pj/list.h>
27 #include <pj/lock.h>
28 #include <pj/log.h>
29 #include <pj/math.h>
30 #include <pj/os.h>
31 #include <pj/pool.h>
32 #include <pj/string.h>
33 #include <pj/timer.h>
34 #include <pj/file_io.h>
35
36 #if GNUTLS_VERSION_NUMBER < 0x030306 && !defined(_MSC_VER)
37 # include <dirent.h>
38 #endif
39
40 #include <errno.h>
41
42 /* Only build when PJ_HAS_SSL_SOCK and the implementation is GnuTLS. */
43 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
44 (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_GNUTLS)
45
46 #define SSL_SOCK_IMP_USE_CIRC_BUF
47
48 #include "ssl_sock_imp_common.h"
49 #include "ssl_sock_imp_common.c"
50
51 #define THIS_FILE "ssl_sock_gtls.c"
52
53 /* Maximum ciphers */
54 #define MAX_CIPHERS 100
55
56 /* Standard trust locations */
57 #define TRUST_STORE_FILE1 "/etc/ssl/certs/ca-certificates.crt"
58 #define TRUST_STORE_FILE2 "/etc/ssl/certs/ca-bundle.crt"
59
60 /* Debugging output level for GnuTLS only */
61 #define GNUTLS_LOG_LEVEL 0
62
63 /* GnuTLS includes */
64 #include <gnutls/gnutls.h>
65 #include <gnutls/x509.h>
66 #include <gnutls/abstract.h>
67
68 #ifdef _MSC_VER
69 # pragma comment( lib, "libgnutls")
70 #endif
71
72
73 /* Secure socket structure definition. */
74 typedef struct gnutls_sock_t {
75 pj_ssl_sock_t base;
76
77 gnutls_session_t session;
78 gnutls_certificate_credentials_t xcred;
79
80 int tls_init_count; /* library initialization counter */
81 } gnutls_sock_t;
82
83 /* Last error reported somehow */
84 static int tls_last_error;
85
86
87 /*
88 *******************************************************************
89 * Static/internal functions.
90 *******************************************************************
91 */
92
93 /* Convert from GnuTLS error to pj_status_t. */
94 static pj_status_t tls_status_from_err(pj_ssl_sock_t *ssock, int err)
95 {
96 pj_status_t status;
97
98 switch (err) {
99 case GNUTLS_E_SUCCESS:
100 status = PJ_SUCCESS;
101 break;
102 case GNUTLS_E_MEMORY_ERROR:
103 status = PJ_ENOMEM;
104 break;
105 case GNUTLS_E_LARGE_PACKET:
106 status = PJ_ETOOBIG;
107 break;
108 case GNUTLS_E_NO_CERTIFICATE_FOUND:
109 status = PJ_ENOTFOUND;
110 break;
111 case GNUTLS_E_SESSION_EOF:
112 status = PJ_EEOF;
113 break;
114 case GNUTLS_E_HANDSHAKE_TOO_LARGE:
115 status = PJ_ETOOBIG;
116 break;
117 case GNUTLS_E_EXPIRED:
118 status = PJ_EGONE;
119 break;
120 case GNUTLS_E_TIMEDOUT:
121 status = PJ_ETIMEDOUT;
122 break;
123 case GNUTLS_E_PREMATURE_TERMINATION:
124 status = PJ_ECANCELLED;
125 break;
126 case GNUTLS_E_INTERNAL_ERROR:
127 case GNUTLS_E_UNIMPLEMENTED_FEATURE:
128 status = PJ_EBUG;
129 break;
130 case GNUTLS_E_AGAIN:
131 case GNUTLS_E_INTERRUPTED:
132 case GNUTLS_E_REHANDSHAKE:
133 status = PJ_EPENDING;
134 break;
135 case GNUTLS_E_TOO_MANY_EMPTY_PACKETS:
136 case GNUTLS_E_TOO_MANY_HANDSHAKE_PACKETS:
137 case GNUTLS_E_RECORD_LIMIT_REACHED:
138 status = PJ_ETOOMANY;
139 break;
140 case GNUTLS_E_UNSUPPORTED_VERSION_PACKET:
141 case GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM:
142 case GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE:
143 case GNUTLS_E_X509_UNSUPPORTED_ATTRIBUTE:
144 case GNUTLS_E_X509_UNSUPPORTED_EXTENSION:
145 case GNUTLS_E_X509_UNSUPPORTED_CRITICAL_EXTENSION:
146 status = PJ_ENOTSUP;
147 break;
148 case GNUTLS_E_INVALID_SESSION:
149 case GNUTLS_E_INVALID_REQUEST:
150 case GNUTLS_E_INVALID_PASSWORD:
151 case GNUTLS_E_ILLEGAL_PARAMETER:
152 case GNUTLS_E_RECEIVED_ILLEGAL_EXTENSION:
153 case GNUTLS_E_UNEXPECTED_PACKET:
154 case GNUTLS_E_UNEXPECTED_PACKET_LENGTH:
155 case GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET:
156 case GNUTLS_E_UNWANTED_ALGORITHM:
157 case GNUTLS_E_USER_ERROR:
158 status = PJ_EINVAL;
159 break;
160 default:
161 status = PJ_EUNKNOWN;
162 break;
163 }
164
165 /* Not thread safe */
166 tls_last_error = err;
167 if (ssock)
168 ssock->last_err = err;
169 return status;
170 }
171
172
173 /* Get error string from GnuTLS using tls_last_error */
174 static pj_str_t tls_strerror(pj_status_t status,
175 char *buf, pj_size_t bufsize)
176 {
177 PJ_UNUSED_ARG(status);
178 pj_str_t errstr;
179 const char *tmp = gnutls_strerror(tls_last_error);
180
181 #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
182 if (tmp) {
183 pj_ansi_strxcpy(buf, tmp, bufsize);
184 errstr = pj_str(buf);
185 return errstr;
186 }
187 #endif /* PJ_HAS_ERROR_STRING */
188
189 errstr.ptr = buf;
190 errstr.slen = pj_ansi_snprintf(buf, bufsize, "GnuTLS error %d: %s",
191 tls_last_error, tmp);
192 if (errstr.slen < 1 || errstr.slen >= (int) bufsize)
193 errstr.slen = bufsize - 1;
194
195 return errstr;
196 }
197
198
199 /* GnuTLS way of reporting internal operations. */
200 static void tls_print_logs(int level, const char* msg)
201 {
202 PJ_LOG(3, (THIS_FILE, "GnuTLS [%d]: %s", level, msg));
203 }
204
205
206 /* Initialize GnuTLS. */
207 static int tls_init_count;
208 static void tls_deinit(void);
209
210 static pj_status_t tls_init(void)
211 {
212 pj_status_t status;
213 int ret;
214
215 if (tls_init_count == 1)
216 return PJ_SUCCESS;
217
218 if (tls_init_count == -1) {
219 /* Another thread is initializing. Spin briefly. */
220 int retry;
221 for (retry = 0; retry < 100 && tls_init_count == -1; ++retry)
222 pj_thread_sleep(10);
223 return (tls_init_count == 1) ? PJ_SUCCESS : PJ_EBUSY;
224 }
225
226 tls_init_count = -1;
227
228 /* Register error subsystem */
229 status = pj_register_strerror(PJ_ERRNO_START_USER +
230 PJ_ERRNO_SPACE_SIZE * 6,
231 PJ_ERRNO_SPACE_SIZE,
232 &tls_strerror);
233 pj_assert(status == PJ_SUCCESS);
234
235 /* Init GnuTLS library */
236 ret = gnutls_global_init();
237 if (ret < 0) {
238 tls_init_count = 0;
239 return tls_status_from_err(NULL, ret);
240 }
241
242 gnutls_global_set_log_level(GNUTLS_LOG_LEVEL);
243 gnutls_global_set_log_function(tls_print_logs);
244
245 /* Init available ciphers */
246 if (!ssl_cipher_num) {
247 unsigned int i;
248
249 for (i = 0; i<PJ_ARRAY_SIZE(ssl_ciphers); i++) {
250 unsigned char id[2];
251 const char *suite;
252
253 suite = gnutls_cipher_suite_info(i, (unsigned char *)id,
254 NULL, NULL, NULL, NULL);
255 ssl_ciphers[i].id = 0;
256 /* usually the array size is bigger than the number of available
257 * ciphers anyway, so by checking here we can exit the loop as soon
258 * as either all ciphers have been added or the array is full */
259 if (suite) {
260 ssl_ciphers[i].id = (pj_ssl_cipher)
261 (pj_uint32_t) ((id[0] << 8) | id[1]);
262 ssl_ciphers[i].name = suite;
263 } else
264 break;
265 }
266
267 ssl_cipher_num = i;
268 }
269
270 /* Schedule cleanup at pj_shutdown() */
271 status = pj_atexit(&tls_deinit);
272 if (status != PJ_SUCCESS) {
273 PJ_PERROR(2, ("gtls", status,
274 "Failed to register GnuTLS cleanup"));
275 }
276
277 tls_init_count = 1;
278 return PJ_SUCCESS;
279 }
280
281
282 /* Shutdown GnuTLS */
283 static void tls_deinit(void)
284 {
285 if (tls_init_count == 1) {
286 gnutls_global_deinit();
287 tls_init_count = 0;
288 }
289 }
290
291
292 /* Callback invoked every time a certificate has to be validated. */
293 static int tls_cert_verify_cb(gnutls_session_t session)
294 {
295 pj_ssl_sock_t *ssock;
296 unsigned int status;
297 int ret;
298
299 /* Get SSL socket instance */
300 ssock = (pj_ssl_sock_t *)gnutls_session_get_ptr(session);
301 pj_assert(ssock);
302
303 /* Support only x509 format */
304 ret = gnutls_certificate_type_get(session) != GNUTLS_CRT_X509;
305 if (ret < 0) {
306 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
307 return GNUTLS_E_CERTIFICATE_ERROR;
308 }
309
310 /* Store verification status */
311 ret = gnutls_certificate_verify_peers2(session, &status);
312 if (ret < 0) {
313 ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
314 return GNUTLS_E_CERTIFICATE_ERROR;
315 }
316 /* Always map GnuTLS chain-trust flags into ssock->verify_status so that
317 * upper layers (e.g. sip_transport_tls, which sets verify_peer=PJ_FALSE
318 * and enforces certificate policy itself) can inspect the result.
319 * Aborting the handshake immediately is only done when verify_peer is
320 * set at the SSL-socket level. */
321 if (status & GNUTLS_CERT_INVALID) {
322 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
323 ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND;
324 else if (status & GNUTLS_CERT_EXPIRED ||
325 status & GNUTLS_CERT_NOT_ACTIVATED)
326 ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
327 else if (status & GNUTLS_CERT_SIGNER_NOT_CA ||
328 status & GNUTLS_CERT_INSECURE_ALGORITHM)
329 ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
330 else if (status & GNUTLS_CERT_UNEXPECTED_OWNER ||
331 status & GNUTLS_CERT_MISMATCH)
332 ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
333 else if (status & GNUTLS_CERT_REVOKED)
334 ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
335 else
336 ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
337
338 if (ssock->param.verify_peer)
339 return GNUTLS_E_CERTIFICATE_ERROR;
340 }
341
342 if (ssock->param.verify_peer) {
343 gnutls_x509_crt_t cert;
344 unsigned int cert_list_size;
345 const gnutls_datum_t *cert_list;
346 int ret2;
347
348 ret2 = gnutls_x509_crt_init(&cert);
349 if (ret2 < 0)
350 goto out;
351
352 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
353 if (cert_list == NULL) {
354 ret = GNUTLS_E_NO_CERTIFICATE_FOUND;
355 goto out;
356 }
357
358 /* TODO: verify whole chain perhaps? */
359 ret = gnutls_x509_crt_import(cert, &cert_list[0], GNUTLS_X509_FMT_DER);
360 if (ret < 0)
361 ret = gnutls_x509_crt_import(cert, &cert_list[0],
362 GNUTLS_X509_FMT_PEM);
363 if (ret < 0) {
364 ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
365 goto out;
366 }
367 ret = gnutls_x509_crt_check_hostname(cert,
368 ssock->param.server_name.ptr);
369 if (ret < 0)
370 goto out;
371
372 gnutls_x509_crt_deinit(cert);
373
374 /* notify GnuTLS to continue handshake normally */
375 return GNUTLS_E_SUCCESS;
376
377 out:
378 tls_last_error = ret;
379 ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
380 return GNUTLS_E_CERTIFICATE_ERROR;
381 }
382
383 /* verify_peer is false: allow the handshake to complete. Upper layers
384 * will read ssock->verify_status to enforce their own policy. */
385 return GNUTLS_E_SUCCESS;
386 }
387
388
389 /* gnutls_handshake() and gnutls_record_send() will call this function to
390 * send/write (encrypted) data */
391 static pj_ssize_t tls_data_push(gnutls_transport_ptr_t ptr,
392 const void *data, size_t len)
393 {
394 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)ptr;
395 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
396
397 pj_lock_acquire(ssock->ssl_write_buf_mutex);
398 if (circ_write(&ssock->ssl_write_buf, data, len) != PJ_SUCCESS) {
399 pj_lock_release(ssock->ssl_write_buf_mutex);
400
401 gnutls_transport_set_errno(gssock->session, ENOMEM);
402 return -1;
403 }
404
405 pj_lock_release(ssock->ssl_write_buf_mutex);
406
407 return len;
408 }
409
410
411 /* gnutls_handshake() and gnutls_record_recv() will call this function to
412 * receive/read (encrypted) data */
413 static pj_ssize_t tls_data_pull(gnutls_transport_ptr_t ptr,
414 void *data, pj_size_t len)
415 {
416 pj_ssl_sock_t *ssock = (pj_ssl_sock_t *)ptr;
417 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
418
419 pj_lock_acquire(ssock->ssl_read_buf_mutex);
420
421 if (circ_empty(&ssock->ssl_read_buf)) {
422 pj_lock_release(ssock->ssl_read_buf_mutex);
423
424 /* Data buffers not yet filled */
425 gnutls_transport_set_errno(gssock->session, EAGAIN);
426 return -1;
427 }
428
429 pj_size_t circ_buf_size = circ_size(&ssock->ssl_read_buf);
430 pj_size_t read_size = PJ_MIN(circ_buf_size, len);
431
432 circ_read(&ssock->ssl_read_buf, data, read_size);
433
434 pj_lock_release(ssock->ssl_read_buf_mutex);
435
436 return read_size;
437 }
438
439
440 /* Append a string to the priority string, only once. */
441 static pj_status_t tls_str_append_once(pj_str_t *dst, pj_str_t *src)
442 {
443 if (pj_strstr(dst, src) == NULL) {
444 /* Check buffer size */
445 if (dst->slen + src->slen + 3 > 1024)
446 return PJ_ETOOMANY;
447
448 if (dst->slen > 0 && dst->ptr[dst->slen-1] == ':')
449 pj_strcat2(dst, "+");
450 else
451 pj_strcat2(dst, ":+");
452 pj_strcat(dst, src);
453 }
454 return PJ_SUCCESS;
455 }
456
457
458 /* Generate priority string with user preference order. */
459 static pj_status_t tls_priorities_set(pj_ssl_sock_t *ssock)
460 {
461 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
462 char buf[1024];
463 char priority_buf[256];
464 pj_str_t cipher_list;
465 pj_str_t compression = pj_str("COMP-NULL");
466 pj_str_t server = pj_str(":%SERVER_PRECEDENCE");
467 int i, j, ret;
468 pj_str_t priority;
469 const char *err;
470
471 pj_strset(&cipher_list, buf, 0);
472 pj_strset(&priority, priority_buf, 0);
473
474 if (ssock->param.proto == PJ_SSL_SOCK_PROTO_DEFAULT) {
475 ssock->param.proto = PJ_SSL_SOCK_PROTO_TLS1_2 |
476 PJ_SSL_SOCK_PROTO_TLS1_3;
477 }
478
479 /* For each level, enable only the requested protocol */
480 pj_strcat2(&priority, "NORMAL:-VERS-ALL:");
481 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_3) {
482 pj_strcat2(&priority, "+VERS-TLS1.3:");
483 }
484 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_2) {
485 pj_strcat2(&priority, "+VERS-TLS1.2:");
486 }
487 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1_1) {
488 pj_strcat2(&priority, "+VERS-TLS1.1:");
489 }
490 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_TLS1) {
491 pj_strcat2(&priority, "+VERS-TLS1.0:");
492 }
493 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL3) {
494 pj_strcat2(&priority, "+VERS-SSL3.0:");
495 }
496 if (ssock->param.proto & PJ_SSL_SOCK_PROTO_SSL2) {
497 /* GnuTLS doesn't support SSLv2 */
498 }
499
500 pj_strcat(&cipher_list, &priority);
501 if (ssock->param.ciphers_num > 0) {
502 pj_strcat2(&cipher_list, "-CIPHER-ALL");
503 }
504 for (i = 0; i < (int)ssock->param.ciphers_num; i++) {
505 for (j = 0; ; j++) {
506 pj_ssl_cipher c;
507 const char *suite;
508 unsigned char id[2];
509 gnutls_protocol_t proto;
510 gnutls_kx_algorithm_t kx;
511 gnutls_mac_algorithm_t mac;
512 gnutls_cipher_algorithm_t algo;
513
514 suite = gnutls_cipher_suite_info(j, (unsigned char *)id,
515 &kx, &algo, &mac, &proto);
516 if (!suite)
517 break;
518
519 c = (pj_ssl_cipher) (pj_uint32_t) ((id[0] << 8) | id[1]);
520 if (ssock->param.ciphers[i] == c) {
521 char temp[256];
522 pj_str_t cipher_entry;
523
524 /* Protocol version */
525 /* We shouldn't add protocol support that's not specified
526 * in ssock->param.proto.
527 */
528 /*
529 pj_strset(&cipher_entry, temp, 0);
530 pj_strcat2(&cipher_entry, "VERS-");
531 pj_strcat2(&cipher_entry, gnutls_protocol_get_name(proto));
532 ret = tls_str_append_once(&cipher_list, &cipher_entry);
533 if (ret != PJ_SUCCESS)
534 return ret;
535 */
536
537 /* Cipher */
538 pj_strset(&cipher_entry, temp, 0);
539 pj_strcat2(&cipher_entry, gnutls_cipher_get_name(algo));
540 ret = tls_str_append_once(&cipher_list, &cipher_entry);
541 if (ret != PJ_SUCCESS)
542 return ret;
543
544 /* Mac */
545 pj_strset(&cipher_entry, temp, 0);
546 pj_strcat2(&cipher_entry, gnutls_mac_get_name(mac));
547 ret = tls_str_append_once(&cipher_list, &cipher_entry);
548 if (ret != PJ_SUCCESS)
549 return ret;
550
551 /* Key exchange */
552 pj_strset(&cipher_entry, temp, 0);
553 pj_strcat2(&cipher_entry, gnutls_kx_get_name(kx));
554 ret = tls_str_append_once(&cipher_list, &cipher_entry);
555 if (ret != PJ_SUCCESS)
556 return ret;
557
558 /* Compression is always disabled */
559 /* Signature is level-default */
560 break;
561 }
562 }
563 }
564
565 /* Disable compression, it's a TLS-only extension after all */
566 tls_str_append_once(&cipher_list, &compression);
567
568 /* Server will be the one deciding which crypto to use */
569 if (ssock->is_server) {
570 if (cipher_list.slen + server.slen + 1 > (pj_ssize_t)sizeof(buf))
571 return PJ_ETOOMANY;
572 else
573 pj_strcat(&cipher_list, &server);
574 }
575
576 /* End the string and print it */
577 if (cipher_list.ptr[cipher_list.slen-1] == ':')
578 cipher_list.slen--;
579 cipher_list.ptr[cipher_list.slen] = '\0';
580 PJ_LOG(5, (ssock->pool->obj_name, "Priority string: %s", cipher_list.ptr));
581
582 /* Set our priority string */
583 ret = gnutls_priority_set_direct(gssock->session,
584 cipher_list.ptr, &err);
585 if (ret < 0) {
586 tls_last_error = GNUTLS_E_INVALID_REQUEST;
587 return PJ_EINVAL;
588 }
589
590 return PJ_SUCCESS;
591 }
592
593
594 /* Load root CA file or load the installed ones. */
595 static pj_status_t tls_trust_set(pj_ssl_sock_t *ssock)
596 {
597 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
598 int ntrusts = 0;
599 int err;
600
601 err = gnutls_certificate_set_x509_system_trust(gssock->xcred);
602 if (err > 0)
603 ntrusts += err;
604 err = gnutls_certificate_set_x509_trust_file(gssock->xcred,
605 TRUST_STORE_FILE1,
606 GNUTLS_X509_FMT_PEM);
607 if (err > 0)
608 ntrusts += err;
609
610 err = gnutls_certificate_set_x509_trust_file(gssock->xcred,
611 TRUST_STORE_FILE2,
612 GNUTLS_X509_FMT_PEM);
613 if (err > 0)
614 ntrusts += err;
615
616 if (ntrusts > 0)
617 return PJ_SUCCESS;
618 else if (!ntrusts)
619 return PJ_ENOTFOUND;
620 else
621 return PJ_EINVAL;
622 }
623
624 #if GNUTLS_VERSION_NUMBER < 0x030306
625
626 #ifdef _POSIX_PATH_MAX
627 # define GNUTLS_PATH_MAX _POSIX_PATH_MAX
628 #else
629 # define GNUTLS_PATH_MAX 256
630 #endif
631
632 static int gnutls_certificate_set_x509_trust_dir(
633 gnutls_certificate_credentials_t cred,
634 const char *dirname, unsigned type)
635 {
636 DIR *dirp;
637 struct dirent *d;
638 int ret;
639 int r = 0;
640 char path[GNUTLS_PATH_MAX];
641 #ifndef _WIN32
642 struct dirent e;
643 #endif
644
645 dirp = opendir(dirname);
646 if (dirp != NULL) {
647 do {
648 #ifdef _WIN32
649 d = readdir(dirp);
650 if (d != NULL) {
651 #else
652 ret = readdir_r(dirp, &e, &d);
653 if (ret == 0 && d != NULL
654 #ifdef _DIRENT_HAVE_D_TYPE
655 && (d->d_type == DT_REG || d->d_type == DT_LNK ||
656 d->d_type == DT_UNKNOWN)
657 #endif
658 ) {
659 #endif
660 snprintf(path, sizeof(path), "%s/%s",
661 dirname, d->d_name);
662
663 ret = gnutls_certificate_set_x509_trust_file(cred, path, type);
664 if (ret >= 0)
665 r += ret;
666 }
667 } while (d != NULL);
668 closedir(dirp);
669 }
670
671 return r;
672 }
673
674 #endif
675
676 static pj_ssl_sock_t *ssl_alloc(pj_pool_t *pool)
677 {
678 return (pj_ssl_sock_t *)PJ_POOL_ZALLOC_T(pool, gnutls_sock_t);
679 }
680
681 /* Create and initialize new GnuTLS context and instance */
682 static pj_status_t ssl_create(pj_ssl_sock_t *ssock)
683 {
684 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
685 pj_ssl_cert_t *cert;
686 pj_status_t status;
687 int ret;
688
689 /* Suppress warnings */
690 PJ_UNUSED_ARG(circ_reset);
691 PJ_UNUSED_ARG(circ_read_cancel);
692
693 pj_assert(ssock);
694
695 cert = ssock->cert;
696
697 /* Initialize GnuTLS library (idempotent) */
698 {
699 pj_status_t status = tls_init();
700 if (status != PJ_SUCCESS)
701 return status;
702 }
703
704 /* Start this socket session */
705 ret = gnutls_init(&gssock->session, ssock->is_server ? GNUTLS_SERVER
706 : GNUTLS_CLIENT);
707 if (ret < 0)
708 goto out;
709
710 /* Set the ssock object to be retrieved by transport (send/recv) and by
711 * user data from this session */
712 gnutls_transport_set_ptr(gssock->session,
713 (gnutls_transport_ptr_t) (uintptr_t) ssock);
714 gnutls_session_set_ptr(gssock->session,
715 (gnutls_transport_ptr_t) (uintptr_t) ssock);
716
717 /* Initialize input circular buffer */
718 status = circ_init(ssock->pool->factory, &ssock->ssl_read_buf, 512);
719 if (status != PJ_SUCCESS)
720 return status;
721
722 /* Initialize output circular buffer */
723 status = circ_init(ssock->pool->factory, &ssock->ssl_write_buf, 512);
724 if (status != PJ_SUCCESS)
725 return status;
726
727 /* Set the callback that allows GnuTLS to PUSH and PULL data
728 * TO and FROM the transport layer */
729 gnutls_transport_set_push_function(gssock->session, tls_data_push);
730 gnutls_transport_set_pull_function(gssock->session, tls_data_pull);
731
732 /* Determine which cipher suite to support */
733 status = tls_priorities_set(ssock);
734 if (status != PJ_SUCCESS)
735 return status;
736
737 /* Allocate credentials for handshaking and transmission */
738 ret = gnutls_certificate_allocate_credentials(&gssock->xcred);
739 if (ret < 0)
740 goto out;
741 gnutls_certificate_set_verify_function(gssock->xcred, tls_cert_verify_cb);
742
743 /* Load system trust file(s) */
744 status = tls_trust_set(ssock);
745 if (status != PJ_SUCCESS)
746 return status;
747
748 /* Load user-provided CA, certificate and key if available */
749 if (cert) {
750 /* Load CA if one is specified. */
751 if (cert->CA_file.slen) {
752 ret = gnutls_certificate_set_x509_trust_file(gssock->xcred,
753 cert->CA_file.ptr,
754 GNUTLS_X509_FMT_PEM);
755 if (ret < 0)
756 ret = gnutls_certificate_set_x509_trust_file(
757 gssock->xcred,
758 cert->CA_file.ptr,
759 GNUTLS_X509_FMT_DER);
760 if (ret < 0)
761 goto out;
762 }
763 if (cert->CA_path.slen) {
764 ret = gnutls_certificate_set_x509_trust_dir(gssock->xcred,
765 cert->CA_path.ptr,
766 GNUTLS_X509_FMT_PEM);
767 if (ret < 0)
768 ret = gnutls_certificate_set_x509_trust_dir(
769 gssock->xcred,
770 cert->CA_path.ptr,
771 GNUTLS_X509_FMT_DER);
772 if (ret < 0)
773 goto out;
774 }
775
776 /* Load certificate, key and pass if one is specified */
777 if (cert->cert_file.slen && cert->privkey_file.slen) {
778 const char *prikey_file = cert->privkey_file.ptr;
779 const char *prikey_pass = cert->privkey_pass.slen
780 ? cert->privkey_pass.ptr
781 : NULL;
782 ret = gnutls_certificate_set_x509_key_file2(gssock->xcred,
783 cert->cert_file.ptr,
784 prikey_file,
785 GNUTLS_X509_FMT_PEM,
786 prikey_pass,
787 0);
788 if (ret != GNUTLS_E_SUCCESS)
789 ret = gnutls_certificate_set_x509_key_file2(gssock->xcred,
790 cert->cert_file.ptr,
791 prikey_file,
792 GNUTLS_X509_FMT_DER,
793 prikey_pass,
794 0);
795 if (ret < 0)
796 goto out;
797 }
798
799 if (cert->CA_buf.slen) {
800 gnutls_datum_t ca;
801 ca.data = (unsigned char*)cert->CA_buf.ptr;
802 ca.size = cert->CA_buf.slen;
803 ret = gnutls_certificate_set_x509_trust_mem(gssock->xcred,
804 &ca,
805 GNUTLS_X509_FMT_PEM);
806 if (ret < 0)
807 ret = gnutls_certificate_set_x509_trust_mem(
808 gssock->xcred, &ca, GNUTLS_X509_FMT_DER);
809 if (ret < 0)
810 goto out;
811 }
812
813 if (cert->cert_buf.slen && cert->privkey_buf.slen) {
814 gnutls_datum_t cert_buf;
815 gnutls_datum_t privkey_buf;
816
817 cert_buf.data = (unsigned char*)cert->CA_buf.ptr;
818 cert_buf.size = cert->CA_buf.slen;
819 privkey_buf.data = (unsigned char*)cert->privkey_buf.ptr;
820 privkey_buf.size = cert->privkey_buf.slen;
821
822 const char *prikey_pass = cert->privkey_pass.slen
823 ? cert->privkey_pass.ptr
824 : NULL;
825 ret = gnutls_certificate_set_x509_key_mem2(gssock->xcred,
826 &cert_buf,
827 &privkey_buf,
828 GNUTLS_X509_FMT_PEM,
829 prikey_pass,
830 0);
831 /* Load DER format */
832 /*
833 if (ret != GNUTLS_E_SUCCESS)
834 ret = gnutls_certificate_set_x509_key_mem2(gssock->xcred,
835 &cert_buf,
836 &privkey_buf,
837 GNUTLS_X509_FMT_DER,
838 prikey_pass,
839 0);
840 */
841 if (ret < 0)
842 goto out;
843 }
844 }
845
846 /* Require client certificate if asked */
847 if (ssock->is_server && ssock->param.require_client_cert)
848 gnutls_certificate_server_set_request(gssock->session,
849 GNUTLS_CERT_REQUIRE);
850
851 /* Finally set credentials for this session */
852 ret = gnutls_credentials_set(gssock->session,
853 GNUTLS_CRD_CERTIFICATE, gssock->xcred);
854 if (ret < 0)
855 goto out;
856
857 ret = GNUTLS_E_SUCCESS;
858 out:
859 return tls_status_from_err(ssock, ret);
860 }
861
862
863 /* Destroy GnuTLS credentials and session. */
864 static void ssl_destroy(pj_ssl_sock_t *ssock)
865 {
866 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
867
868 if (gssock->session) {
869 if (ssock->ssl_state == SSL_STATE_ESTABLISHED)
870 gnutls_bye(gssock->session, GNUTLS_SHUT_RDWR);
871 gnutls_deinit(gssock->session);
872 gssock->session = NULL;
873 }
874
875 if (gssock->xcred) {
876 gnutls_certificate_free_credentials(gssock->xcred);
877 gssock->xcred = NULL;
878 }
879
880 /* Note: GnuTLS library stays initialized for the process lifetime.
881 * tls_deinit() is called via pj_atexit() at pj_shutdown(). */
882
883 /* Destroy circular buffers */
884 circ_deinit(&ssock->ssl_read_buf);
885 circ_deinit(&ssock->ssl_write_buf);
886 }
887
888
889 /* Reset socket state. */
890 static void ssl_reset_sock_state(pj_ssl_sock_t *ssock)
891 {
892 pj_lock_acquire(ssock->ssl_write_buf_mutex);
893 ssock->ssl_state = SSL_STATE_NULL;
894 pj_lock_release(ssock->ssl_write_buf_mutex);
895
896 ssl_close_sockets(ssock);
897
898 ssock->last_err = tls_last_error = GNUTLS_E_SUCCESS;
899 }
900
901
902 static void ssl_ciphers_populate(void)
903 {
904 if (!ssl_cipher_num) {
905 pj_status_t status = tls_init();
906 if (status != PJ_SUCCESS) {
907 PJ_PERROR(1, ("gtls", status, "Failed to initialize GnuTLS"));
908 return;
909 }
910 /* GnuTLS stays initialized — no tls_deinit() here */
911 }
912 }
913
914
915 static pj_ssl_cipher ssl_get_cipher(pj_ssl_sock_t *ssock)
916 {
917 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
918 int i;
919 gnutls_cipher_algorithm_t lookup;
920 gnutls_cipher_algorithm_t cipher;
921
922 /* Current cipher */
923 cipher = gnutls_cipher_get(gssock->session);
924 for (i = 0; ; i++) {
925 unsigned char id[2];
926 const char *suite;
927
928 suite = gnutls_cipher_suite_info(i,(unsigned char *)id, NULL,
929 &lookup, NULL, NULL);
930 if (suite) {
931 if (lookup == cipher) {
932 return (pj_uint32_t) ((id[0] << 8) | id[1]);
933 }
934 } else {
935 break;
936 }
937 }
938
939 return PJ_TLS_UNKNOWN_CIPHER;
940 }
941
942
943 /* Get Common Name field string from a general name string */
944 static void tls_cert_get_cn(const pj_str_t *gen_name, pj_str_t *cn)
945 {
946 pj_str_t CN_sign = {"CN=", 3};
947 char *p, *q;
948
949 pj_bzero(cn, sizeof(cn));
950
951 p = pj_strstr(gen_name, &CN_sign);
952 if (!p)
953 return;
954
955 p += 3; /* shift pointer to value part */
956 pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
957 q = pj_strchr(cn, ',');
958 if (q)
959 cn->slen = q - p;
960 }
961
962
963 /* Get certificate info; in case the certificate info is already populated,
964 * this function will check if the contents need updating by inspecting the
965 * issuer and the serial number. */
966 static void tls_cert_get_info(pj_pool_t *pool, pj_ssl_cert_info *ci,
967 gnutls_x509_crt_t cert)
968 {
969 pj_bool_t update_needed;
970 char buf[512] = { 0 };
971 size_t bufsize = sizeof(buf);
972 pj_uint8_t serial_no[64] = { 0 }; /* should be >= sizeof(ci->serial_no) */
973 size_t serialsize = sizeof(serial_no);
974 size_t len = sizeof(buf);
975 int i, ret, seq = 0;
976 pj_ssl_cert_name_type type;
977
978 pj_assert(pool && ci && cert);
979
980 /* Get issuer */
981 gnutls_x509_crt_get_issuer_dn(cert, buf, &bufsize);
982
983 /* Get serial no */
984 gnutls_x509_crt_get_serial(cert, serial_no, &serialsize);
985
986 /* Check if the contents need to be updated */
987 update_needed = pj_strcmp2(&ci->issuer.info, buf) ||
988 pj_memcmp(ci->serial_no, serial_no, serialsize);
989 if (!update_needed)
990 return;
991
992 /* Update cert info */
993
994 pj_bzero(ci, sizeof(pj_ssl_cert_info));
995
996 /* Version */
997 ci->version = gnutls_x509_crt_get_version(cert);
998
999 /* Issuer */
1000 pj_strdup2(pool, &ci->issuer.info, buf);
1001 tls_cert_get_cn(&ci->issuer.info, &ci->issuer.cn);
1002
1003 /* Serial number */
1004 pj_memcpy(ci->serial_no, serial_no, sizeof(ci->serial_no));
1005
1006 /* Subject */
1007 bufsize = sizeof(buf);
1008 gnutls_x509_crt_get_dn(cert, buf, &bufsize);
1009 pj_strdup2(pool, &ci->subject.info, buf);
1010 tls_cert_get_cn(&ci->subject.info, &ci->subject.cn);
1011
1012 /* Validity */
1013 ci->validity.end.sec = (long)gnutls_x509_crt_get_expiration_time(cert);
1014 ci->validity.start.sec = (long)gnutls_x509_crt_get_activation_time(cert);
1015 ci->validity.gmt = 0;
1016
1017 /* Subject Alternative Name extension */
1018 if (ci->version >= 3) {
1019 char out[256] = { 0 };
1020 /* Get the number of all alternate names so that we can allocate
1021 * the correct number of bytes in subj_alt_name */
1022 while (gnutls_x509_crt_get_subject_alt_name(cert, seq, out, &len,
1023 NULL) !=
1024 GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
1025 {
1026 seq++;
1027 }
1028
1029 ci->subj_alt_name.entry = pj_pool_calloc(pool, seq,
1030 sizeof(*ci->subj_alt_name.entry));
1031 if (!ci->subj_alt_name.entry) {
1032 tls_last_error = GNUTLS_E_MEMORY_ERROR;
1033 return;
1034 }
1035
1036 /* Now populate the alternative names */
1037 for (i = 0; i < seq; i++) {
1038 len = sizeof(out) - 1;
1039 ret = gnutls_x509_crt_get_subject_alt_name(cert, i, out,
1040 &len, NULL);
1041
1042 switch (ret) {
1043 case GNUTLS_SAN_IPADDRESS:
1044 type = PJ_SSL_CERT_NAME_IP;
1045 pj_inet_ntop2(len == sizeof(pj_in6_addr) ? pj_AF_INET6()
1046 : pj_AF_INET(),
1047 out, buf, sizeof(buf));
1048 break;
1049 case GNUTLS_SAN_URI:
1050 type = PJ_SSL_CERT_NAME_URI;
1051 break;
1052 case GNUTLS_SAN_RFC822NAME:
1053 type = PJ_SSL_CERT_NAME_RFC822;
1054 break;
1055 case GNUTLS_SAN_DNSNAME:
1056 type = PJ_SSL_CERT_NAME_DNS;
1057 break;
1058 default:
1059 type = PJ_SSL_CERT_NAME_UNKNOWN;
1060 break;
1061 }
1062
1063 if (len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
1064 ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
1065 pj_strdup2(pool,
1066 &ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
1067 type == PJ_SSL_CERT_NAME_IP ? buf : out);
1068 ci->subj_alt_name.cnt++;
1069 }
1070 }
1071 /* TODO: if no DNS alt. names were found, we could check against
1072 * the commonName as per RFC3280. */
1073 }
1074 }
1075
1076 static void tls_cert_get_chain_raw(pj_pool_t *pool, pj_ssl_cert_info *ci,
1077 const gnutls_datum_t *certs,
1078 size_t certs_num)
1079 {
1080 size_t i=0;
1081 ci->raw_chain.cert_raw = pj_pool_calloc(pool, certs_num,
1082 sizeof(*ci->raw_chain.cert_raw));
1083 ci->raw_chain.cnt = certs_num;
1084 for (i=0; i < certs_num; ++i) {
1085 const pj_str_t crt_raw = {(char*)certs[i].data,
1086 (pj_ssize_t)certs[i].size};
1087 pj_strdup(pool, ci->raw_chain.cert_raw+i, &crt_raw);
1088 }
1089 }
1090
1091 /* Update local & remote certificates info. This function should be
1092 * called after handshake or renegotiation successfully completed. */
1093 static void ssl_update_certs_info(pj_ssl_sock_t *ssock)
1094 {
1095 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
1096 gnutls_x509_crt_t cert = NULL;
1097 const gnutls_datum_t *us;
1098 const gnutls_datum_t *certs;
1099 unsigned int certslen = 0;
1100 int ret = GNUTLS_CERT_INVALID;
1101
1102 pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
1103
1104 /* Get active local certificate */
1105 us = gnutls_certificate_get_ours(gssock->session);
1106 if (!us)
1107 goto us_out;
1108
1109 ret = gnutls_x509_crt_init(&cert);
1110 if (ret < 0)
1111 goto us_out;
1112 ret = gnutls_x509_crt_import(cert, us, GNUTLS_X509_FMT_DER);
1113 if (ret < 0)
1114 ret = gnutls_x509_crt_import(cert, us, GNUTLS_X509_FMT_PEM);
1115 if (ret < 0)
1116 goto us_out;
1117
1118 tls_cert_get_info(ssock->pool, &ssock->local_cert_info, cert);
1119 pj_pool_reset(ssock->info_pool);
1120 tls_cert_get_chain_raw(ssock->info_pool, &ssock->local_cert_info, us, 1);
1121
1122 us_out:
1123 tls_last_error = ret;
1124 if (cert)
1125 gnutls_x509_crt_deinit(cert);
1126 else
1127 pj_bzero(&ssock->local_cert_info, sizeof(pj_ssl_cert_info));
1128
1129 cert = NULL;
1130
1131 /* Get active remote certificate */
1132 certs = gnutls_certificate_get_peers(gssock->session, &certslen);
1133 if (certs == NULL || certslen == 0)
1134 goto peer_out;
1135
1136 ret = gnutls_x509_crt_init(&cert);
1137 if (ret < 0)
1138 goto peer_out;
1139
1140 ret = gnutls_x509_crt_import(cert, certs, GNUTLS_X509_FMT_PEM);
1141 if (ret < 0)
1142 ret = gnutls_x509_crt_import(cert, certs, GNUTLS_X509_FMT_DER);
1143 if (ret < 0)
1144 goto peer_out;
1145
1146 tls_cert_get_info(ssock->pool, &ssock->remote_cert_info, cert);
1147 pj_pool_reset(ssock->info_pool);
1148 tls_cert_get_chain_raw(ssock->info_pool, &ssock->remote_cert_info, certs,
1149 certslen);
1150
1151 peer_out:
1152 tls_last_error = ret;
1153 if (cert)
1154 gnutls_x509_crt_deinit(cert);
1155 else
1156 pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info));
1157 }
1158
1159 static void ssl_set_state(pj_ssl_sock_t *ssock, pj_bool_t is_server)
1160 {
1161 PJ_UNUSED_ARG(ssock);
1162 PJ_UNUSED_ARG(is_server);
1163 }
1164
1165 static void ssl_set_peer_name(pj_ssl_sock_t *ssock)
1166 {
1167 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
1168
1169 /* Set server name to connect */
1170 if (ssock->param.server_name.slen &&
1171 get_ip_addr_ver(&ssock->param.server_name) == 0)
1172 {
1173 int ret;
1174 /* Server name is null terminated already */
1175 ret = gnutls_server_name_set(gssock->session, GNUTLS_NAME_DNS,
1176 ssock->param.server_name.ptr,
1177 ssock->param.server_name.slen);
1178 if (ret < 0) {
1179 PJ_LOG(3, (ssock->pool->obj_name,
1180 "gnutls_server_name_set() failed: %s",
1181 gnutls_strerror(ret)));
1182 }
1183 }
1184 }
1185
1186 /* Try to perform an asynchronous handshake */
1187 static pj_status_t ssl_do_handshake(pj_ssl_sock_t *ssock)
1188 {
1189 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
1190 int ret;
1191 pj_status_t status;
1192
1193 /* Perform SSL handshake.
1194 * Hold write_mutex to prevent concurrent session access from
1195 * read and write callbacks (ioqueue may fire them in parallel).
1196 */
1197 pj_lock_acquire(ssock->write_mutex);
1198 ret = gnutls_handshake(gssock->session);
1199 pj_lock_release(ssock->write_mutex);
1200
1201 if (ret == GNUTLS_E_SUCCESS) {
1202 /* System are GO */
1203 ssock->ssl_state = SSL_STATE_ESTABLISHED;
1204 status = PJ_SUCCESS;
1205 } else if (!gnutls_error_is_fatal(ret) ||
1206 ret == GNUTLS_E_GOT_APPLICATION_DATA)
1207 {
1208 /* Non fatal error, retry later (busy or again).
1209 * GNUTLS_E_GOT_APPLICATION_DATA means the peer sent application
1210 * data while we expected handshake records (common during
1211 * renegotiation). The app data sits in GnuTLS's internal record
1212 * buffer and will be returned by the next gnutls_record_recv().
1213 * Treat it as non-fatal so the caller retries after draining the
1214 * buffered application data.
1215 */
1216 status = PJ_EPENDING;
1217 } else {
1218 /* Fatal error invalidates session, no fallback */
1219 PJ_LOG(1, ("tls", "gnutls_handshake() error: %s (%d)",
1220 gnutls_strerror(ret), ret));
1221 status = PJ_EINVAL;
1222 }
1223
1224 tls_last_error = ret;
1225
1226 return status;
1227 }
1228
1229 static pj_status_t ssl_read(pj_ssl_sock_t *ssock, void *data, int *size)
1230 {
1231 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
1232 int decrypted_size;
1233
1234 /* Decrypt received data using GnuTLS (will read our input
1235 * circular buffer).
1236 * Hold write_mutex because gnutls_record_recv() may produce
1237 * handshake data during renegotiation (same as OpenSSL's
1238 * SSL_read approach).
1239 */
1240 pj_lock_acquire(ssock->write_mutex);
1241 decrypted_size = gnutls_record_recv(gssock->session, data, *size);
1242 pj_lock_release(ssock->write_mutex);
1243 *size = 0;
1244 if (decrypted_size > 0) {
1245 *size = decrypted_size;
1246 return PJ_SUCCESS;
1247 } else if (decrypted_size == 0) {
1248 /* Nothing more to read */
1249 return PJ_SUCCESS;
1250 } else if (decrypted_size == GNUTLS_E_REHANDSHAKE) {
1251 return PJ_ETRYAGAIN;
1252 } else if (decrypted_size == GNUTLS_E_AGAIN ||
1253 decrypted_size == GNUTLS_E_INTERRUPTED ||
1254 !gnutls_error_is_fatal(decrypted_size))
1255 {
1256 /* non-fatal error, let's just continue */
1257 return PJ_SUCCESS;
1258 } else {
1259 return PJ_ECANCELLED;
1260 }
1261 }
1262
1263 /*
1264 * Write the plain data to GnuTLS, it will be encrypted by gnutls_record_send()
1265 * and sent via tls_data_push. Note that re-negotitation may be on progress, so
1266 * sending data should be delayed until re-negotiation is completed.
1267 * Caller must hold ssock->write_mutex.
1268 */
1269 static pj_status_t ssl_write(pj_ssl_sock_t *ssock, const void *data,
1270 pj_ssize_t size, int *nwritten)
1271 {
1272 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
1273 int nwritten_;
1274 pj_ssize_t total_written = 0;
1275
1276 /* Ask GnuTLS to encrypt our plaintext now. GnuTLS will use the push
1277 * callback to actually write the encrypted bytes into our output circular
1278 * buffer. GnuTLS may refuse to "send" everything at once, but since we are
1279 * not really sending now, we will just call it again now until it succeeds
1280 * (or fails in a fatal way). */
1281 while (total_written < size) {
1282 /* Try encrypting using GnuTLS */
1283 nwritten_ = gnutls_record_send(gssock->session,
1284 ((char *)data) + total_written,
1285 size - total_written);
1286
1287 if (nwritten_ > 0) {
1288 /* Good, some data was encrypted and written */
1289 total_written += nwritten_;
1290 } else {
1291 /* Normally we would have to retry record_send but our internal
1292 * state has not changed, so we have to ask for more data first.
1293 * We will just try again later, although this should never happen.
1294 */
1295 *nwritten = nwritten_;
1296 return tls_status_from_err(ssock, nwritten_);
1297 }
1298 }
1299
1300 /* All encrypted data is written to the output circular buffer;
1301 * now send it on the socket (or notify problem). */
1302 *nwritten = total_written;
1303 return PJ_SUCCESS;
1304 }
1305
1306 static pj_status_t ssl_renegotiate(pj_ssl_sock_t *ssock)
1307 {
1308 gnutls_sock_t *gssock = (gnutls_sock_t *)ssock;
1309 int status;
1310
1311 if (!ssock->is_server) {
1312 /* GnuTLS does not support client-initiated renegotiation.
1313 * gnutls_rehandshake() is server-only (sends HelloRequest),
1314 * and gnutls_handshake() on an established session fails.
1315 */
1316 return PJ_ENOTSUP;
1317 }
1318
1319 /* Server: send HelloRequest to ask client to renegotiate.
1320 * Hold write_mutex for session access consistency with
1321 * ssl_do_handshake() and ssl_read().
1322 */
1323 pj_lock_acquire(ssock->write_mutex);
1324 status = gnutls_rehandshake(gssock->session);
1325 pj_lock_release(ssock->write_mutex);
1326 if (status == GNUTLS_E_SUCCESS)
1327 return PJ_SUCCESS;
1328
1329 return tls_status_from_err(ssock, status);
1330 }
1331
1332 #endif /* PJ_HAS_SSL_SOCK */