1
/* $Id: ssl_sock_ossl.c 4146 2012-05-30 06:35:59Z nanang $ */
3
* Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com)
5
* This program is free software; you can redistribute it and/or modify
6
* it under the terms of the GNU General Public License as published by
7
* the Free Software Foundation; either version 2 of the License, or
8
* (at your option) any later version.
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
* GNU General Public License for more details.
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
#include <pj/ssl_sock.h>
20
#include <pj/activesock.h>
21
#include <pj/compat/socket.h>
22
#include <pj/assert.h>
30
#include <pj/string.h>
34
/* Only build when PJ_HAS_SSL_SOCK is enabled */
35
#if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK!=0
37
#define THIS_FILE "ssl_sock_ossl.c"
39
/* Workaround for ticket #985 */
40
#define DELAYED_CLOSE_TIMEOUT 200
43
#define MAX_CIPHERS 100
46
* Include OpenSSL headers
48
#include <openssl/bio.h>
49
#include <openssl/ssl.h>
50
#include <openssl/err.h>
51
#include <openssl/x509v3.h>
56
# pragma comment( lib, "libeay32MTd")
57
# pragma comment( lib, "ssleay32MTd")
59
# pragma comment( lib, "libeay32MT")
60
# pragma comment( lib, "ssleay32MT")
66
* SSL/TLS state enumeration.
70
SSL_STATE_HANDSHAKING,
75
* Internal timer types.
80
TIMER_HANDSHAKE_TIMEOUT,
85
* Structure of SSL socket read buffer.
87
typedef struct read_data_t
94
* Get the offset of pointer to read-buffer of SSL socket from read-buffer
95
* of active socket. Note that both SSL socket and active socket employ
96
* different but correlated read-buffers (as much as async_cnt for each),
97
* and to make it easier/faster to find corresponding SSL socket's read-buffer
98
* from known active socket's read-buffer, the pointer of corresponding
99
* SSL socket's read-buffer is stored right after the end of active socket's
102
#define OFFSET_OF_READ_DATA_PTR(ssock, asock_rbuf) \
104
((pj_int8_t*)(asock_rbuf) + \
105
ssock->param.read_buffer_size)
108
* Structure of SSL socket write buffer.
110
typedef struct write_data_t {
111
pj_ioqueue_op_key_t key;
112
pj_size_t record_len;
113
pj_ioqueue_op_key_t *app_key;
114
pj_size_t plain_data_len;
124
* Structure of SSL socket write state.
126
typedef struct write_state_t {
131
write_data_t *last_data;
135
* Structure of write data pending.
137
typedef struct write_pending_t {
138
PJ_DECL_LIST_MEMBER(struct write_pending_t);
143
* Secure socket structure definition.
148
pj_ssl_sock_t *parent;
149
pj_ssl_sock_param param;
152
pj_ssl_cert_info local_cert_info;
153
pj_ssl_cert_info remote_cert_info;
156
enum ssl_state ssl_state;
157
pj_ioqueue_op_key_t handshake_op_key;
158
pj_timer_entry timer;
159
pj_status_t verify_status;
161
unsigned long last_err;
164
pj_activesock_t *asock;
166
pj_sockaddr local_addr;
167
pj_sockaddr rem_addr;
170
pj_bool_t read_started;
172
pj_uint32_t read_flags;
174
read_data_t *ssock_rbuf;
176
write_state_t write_state;
177
write_pending_t write_pending;
178
write_pending_t write_pending_empty;
179
pj_lock_t *write_mutex; /* protect write BIO and write_state */
189
* Certificate/credential structure definition.
195
pj_str_t privkey_file;
196
pj_str_t privkey_pass;
200
static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock);
203
*******************************************************************
204
* Static/internal functions.
205
*******************************************************************
209
* Mapping from OpenSSL error codes to pjlib error space.
212
#define PJ_SSL_ERRNO_START (PJ_ERRNO_START_USER + \
213
PJ_ERRNO_SPACE_SIZE*6)
215
#define PJ_SSL_ERRNO_SPACE_SIZE PJ_ERRNO_SPACE_SIZE
217
/* Expected maximum value of reason component in OpenSSL error code */
218
#define MAX_OSSL_ERR_REASON 1200
220
static pj_status_t STATUS_FROM_SSL_ERR(pj_ssl_sock_t *ssock,
225
/* General SSL error, dig more from OpenSSL error queue */
226
if (err == SSL_ERROR_SSL)
227
err = ERR_get_error();
229
/* OpenSSL error range is much wider than PJLIB errno space, so
230
* if it exceeds the space, only the error reason will be kept.
231
* Note that the last native error will be kept as is and can be
232
* retrieved via SSL socket info.
234
status = ERR_GET_LIB(err)*MAX_OSSL_ERR_REASON + ERR_GET_REASON(err);
235
if (status > PJ_SSL_ERRNO_SPACE_SIZE)
236
status = ERR_GET_REASON(err);
238
status += PJ_SSL_ERRNO_START;
239
ssock->last_err = err;
243
static pj_status_t GET_SSL_STATUS(pj_ssl_sock_t *ssock)
245
return STATUS_FROM_SSL_ERR(ssock, ERR_get_error());
250
* Get error string of OpenSSL.
252
static pj_str_t ssl_strerror(pj_status_t status,
253
char *buf, pj_size_t bufsize)
256
unsigned long ssl_err = status;
260
ssl_err -= PJ_SSL_ERRNO_START;
261
l = ssl_err / MAX_OSSL_ERR_REASON;
262
r = ssl_err % MAX_OSSL_ERR_REASON;
263
ssl_err = ERR_PACK(l, 0, r);
266
#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
269
const char *tmp = NULL;
270
tmp = ERR_reason_error_string(ssl_err);
272
pj_ansi_strncpy(buf, tmp, bufsize);
273
errstr = pj_str(buf);
278
#endif /* PJ_HAS_ERROR_STRING */
281
errstr.slen = pj_ansi_snprintf(buf, bufsize,
282
"Unknown OpenSSL error %lu",
289
/* OpenSSL library initialization counter */
290
static int openssl_init_count;
292
/* OpenSSL available ciphers */
293
static unsigned openssl_cipher_num;
294
static struct openssl_ciphers_t {
297
} openssl_ciphers[MAX_CIPHERS];
299
/* OpenSSL application data index */
300
static int sslsock_idx;
303
/* Initialize OpenSSL */
304
static pj_status_t init_openssl(void)
308
if (openssl_init_count)
311
openssl_init_count = 1;
313
/* Register error subsystem */
314
status = pj_register_strerror(PJ_SSL_ERRNO_START,
315
PJ_SSL_ERRNO_SPACE_SIZE,
317
pj_assert(status == PJ_SUCCESS);
319
/* Init OpenSSL lib */
321
SSL_load_error_strings();
322
OpenSSL_add_all_algorithms();
324
/* Init available ciphers */
325
if (openssl_cipher_num == 0) {
326
SSL_METHOD *meth = NULL;
329
STACK_OF(SSL_CIPHER) *sk_cipher;
332
meth = (SSL_METHOD*)SSLv23_server_method();
334
meth = (SSL_METHOD*)TLSv1_server_method();
336
meth = (SSL_METHOD*)SSLv3_server_method();
337
#ifndef OPENSSL_NO_SSL2
339
meth = (SSL_METHOD*)SSLv2_server_method();
343
ctx=SSL_CTX_new(meth);
344
SSL_CTX_set_cipher_list(ctx, "ALL");
347
sk_cipher = SSL_get_ciphers(ssl);
349
n = sk_SSL_CIPHER_num(sk_cipher);
350
if (n > PJ_ARRAY_SIZE(openssl_ciphers))
351
n = PJ_ARRAY_SIZE(openssl_ciphers);
353
for (i = 0; i < n; ++i) {
355
c = sk_SSL_CIPHER_value(sk_cipher,i);
356
openssl_ciphers[i].id = (pj_ssl_cipher)
357
(pj_uint32_t)c->id & 0x00FFFFFF;
358
openssl_ciphers[i].name = SSL_CIPHER_get_name(c);
364
openssl_cipher_num = n;
367
/* Create OpenSSL application data index for SSL socket */
368
sslsock_idx = SSL_get_ex_new_index(0, "SSL socket", NULL, NULL, NULL);
374
/* Shutdown OpenSSL */
375
static void shutdown_openssl(void)
377
PJ_UNUSED_ARG(openssl_init_count);
381
/* SSL password callback. */
382
static int password_cb(char *buf, int num, int rwflag, void *user_data)
384
pj_ssl_cert_t *cert = (pj_ssl_cert_t*) user_data;
386
PJ_UNUSED_ARG(rwflag);
388
if(num < cert->privkey_pass.slen)
391
pj_memcpy(buf, cert->privkey_pass.ptr, cert->privkey_pass.slen);
392
return cert->privkey_pass.slen;
396
/* SSL password callback. */
397
static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
399
pj_ssl_sock_t *ssock;
403
/* Get SSL instance */
404
ossl_ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
405
SSL_get_ex_data_X509_STORE_CTX_idx());
408
/* Get SSL socket instance */
409
ssock = SSL_get_ex_data(ossl_ssl, sslsock_idx);
412
/* Store verification status */
413
err = X509_STORE_CTX_get_error(x509_ctx);
418
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
419
ssock->verify_status |= PJ_SSL_CERT_EISSUER_NOT_FOUND;
422
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
423
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
424
case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
425
case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
426
ssock->verify_status |= PJ_SSL_CERT_EINVALID_FORMAT;
429
case X509_V_ERR_CERT_NOT_YET_VALID:
430
case X509_V_ERR_CERT_HAS_EXPIRED:
431
ssock->verify_status |= PJ_SSL_CERT_EVALIDITY_PERIOD;
434
case X509_V_ERR_UNABLE_TO_GET_CRL:
435
case X509_V_ERR_CRL_NOT_YET_VALID:
436
case X509_V_ERR_CRL_HAS_EXPIRED:
437
case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
438
case X509_V_ERR_CRL_SIGNATURE_FAILURE:
439
case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
440
case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
441
ssock->verify_status |= PJ_SSL_CERT_ECRL_FAILURE;
444
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
445
case X509_V_ERR_CERT_UNTRUSTED:
446
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
447
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
448
ssock->verify_status |= PJ_SSL_CERT_EUNTRUSTED;
451
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
452
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
453
case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
454
case X509_V_ERR_AKID_SKID_MISMATCH:
455
case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
456
case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
457
ssock->verify_status |= PJ_SSL_CERT_EISSUER_MISMATCH;
460
case X509_V_ERR_CERT_REVOKED:
461
ssock->verify_status |= PJ_SSL_CERT_EREVOKED;
464
case X509_V_ERR_INVALID_PURPOSE:
465
case X509_V_ERR_CERT_REJECTED:
466
case X509_V_ERR_INVALID_CA:
467
ssock->verify_status |= PJ_SSL_CERT_EINVALID_PURPOSE;
470
case X509_V_ERR_CERT_CHAIN_TOO_LONG: /* not really used */
471
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
472
ssock->verify_status |= PJ_SSL_CERT_ECHAIN_TOO_LONG;
476
case X509_V_ERR_OUT_OF_MEM:
478
ssock->verify_status |= PJ_SSL_CERT_EUNKNOWN;
482
/* When verification is not requested just return ok here, however
483
* application can still get the verification status.
485
if (PJ_FALSE == ssock->param.verify_peer)
491
/* Setting SSL sock cipher list */
492
static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock);
495
/* Create and initialize new SSL context and instance */
496
static pj_status_t create_ssl(pj_ssl_sock_t *ssock)
498
SSL_METHOD *ssl_method;
508
/* Make sure OpenSSL library has been initialized */
511
/* Determine SSL method to use */
512
switch (ssock->param.proto) {
513
case PJ_SSL_SOCK_PROTO_DEFAULT:
514
case PJ_SSL_SOCK_PROTO_TLS1:
515
ssl_method = (SSL_METHOD*)TLSv1_method();
517
#ifndef OPENSSL_NO_SSL2
518
case PJ_SSL_SOCK_PROTO_SSL2:
519
ssl_method = (SSL_METHOD*)SSLv2_method();
522
case PJ_SSL_SOCK_PROTO_SSL3:
523
ssl_method = (SSL_METHOD*)SSLv3_method();
525
case PJ_SSL_SOCK_PROTO_SSL23:
526
ssl_method = (SSL_METHOD*)SSLv23_method();
528
//case PJ_SSL_SOCK_PROTO_DTLS1:
529
//ssl_method = (SSL_METHOD*)DTLSv1_method();
535
/* Create SSL context */
536
ctx = SSL_CTX_new(ssl_method);
538
return GET_SSL_STATUS(ssock);
541
/* Apply credentials */
543
/* Load CA list if one is specified. */
544
if (cert->CA_file.slen) {
546
rc = SSL_CTX_load_verify_locations(ctx, cert->CA_file.ptr, NULL);
549
status = GET_SSL_STATUS(ssock);
550
PJ_LOG(1,(ssock->pool->obj_name, "Error loading CA list file "
551
"'%s'", cert->CA_file.ptr));
557
/* Set password callback */
558
if (cert->privkey_pass.slen) {
559
SSL_CTX_set_default_passwd_cb(ctx, password_cb);
560
SSL_CTX_set_default_passwd_cb_userdata(ctx, cert);
564
/* Load certificate if one is specified */
565
if (cert->cert_file.slen) {
567
/* Load certificate chain from file into ctx */
568
rc = SSL_CTX_use_certificate_chain_file(ctx, cert->cert_file.ptr);
571
status = GET_SSL_STATUS(ssock);
572
PJ_LOG(1,(ssock->pool->obj_name, "Error loading certificate "
573
"chain file '%s'", cert->cert_file.ptr));
580
/* Load private key if one is specified */
581
if (cert->privkey_file.slen) {
582
/* Adds the first private key found in file to ctx */
583
rc = SSL_CTX_use_PrivateKey_file(ctx, cert->privkey_file.ptr,
587
status = GET_SSL_STATUS(ssock);
588
PJ_LOG(1,(ssock->pool->obj_name, "Error adding private key "
589
"from '%s'", cert->privkey_file.ptr));
596
/* Create SSL instance */
597
ssock->ossl_ctx = ctx;
598
ssock->ossl_ssl = SSL_new(ssock->ossl_ctx);
599
if (ssock->ossl_ssl == NULL) {
600
return GET_SSL_STATUS(ssock);
603
/* Set SSL sock as application data of SSL instance */
604
SSL_set_ex_data(ssock->ossl_ssl, sslsock_idx, ssock);
606
/* SSL verification options */
607
mode = SSL_VERIFY_PEER;
608
if (ssock->is_server && ssock->param.require_client_cert)
609
mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
611
SSL_set_verify(ssock->ossl_ssl, mode, &verify_cb);
613
/* Set cipher list */
614
status = set_cipher_list(ssock);
615
if (status != PJ_SUCCESS)
619
ssock->ossl_rbio = BIO_new(BIO_s_mem());
620
ssock->ossl_wbio = BIO_new(BIO_s_mem());
621
BIO_set_close(ssock->ossl_rbio, BIO_CLOSE);
622
BIO_set_close(ssock->ossl_wbio, BIO_CLOSE);
623
SSL_set_bio(ssock->ossl_ssl, ssock->ossl_rbio, ssock->ossl_wbio);
629
/* Destroy SSL context and instance */
630
static void destroy_ssl(pj_ssl_sock_t *ssock)
632
/* Destroy SSL instance */
633
if (ssock->ossl_ssl) {
634
SSL_shutdown(ssock->ossl_ssl);
635
SSL_free(ssock->ossl_ssl); /* this will also close BIOs */
636
ssock->ossl_ssl = NULL;
639
/* Destroy SSL context */
640
if (ssock->ossl_ctx) {
641
SSL_CTX_free(ssock->ossl_ctx);
642
ssock->ossl_ctx = NULL;
645
/* Potentially shutdown OpenSSL library if this is the last
652
/* Reset SSL socket state */
653
static void reset_ssl_sock_state(pj_ssl_sock_t *ssock)
655
ssock->ssl_state = SSL_STATE_NULL;
660
pj_activesock_close(ssock->asock);
662
ssock->sock = PJ_INVALID_SOCKET;
664
if (ssock->sock != PJ_INVALID_SOCKET) {
665
pj_sock_close(ssock->sock);
666
ssock->sock = PJ_INVALID_SOCKET;
669
/* Upon error, OpenSSL may leave any error description in the thread
670
* error queue, which sometime may cause next call to SSL API returning
671
* false error alarm, e.g: in Linux, SSL_CTX_use_certificate_chain_file()
672
* returning false error after a handshake error (in different SSL_CTX!).
673
* For now, just clear thread error queue here.
679
/* Generate cipher list with user preference order in OpenSSL format */
680
static pj_status_t set_cipher_list(pj_ssl_sock_t *ssock)
683
pj_str_t cipher_list;
684
STACK_OF(SSL_CIPHER) *sk_cipher;
688
if (ssock->param.ciphers_num == 0)
691
pj_strset(&cipher_list, buf, 0);
693
/* Set SSL with ALL available ciphers */
694
SSL_set_cipher_list(ssock->ossl_ssl, "ALL");
696
/* Generate user specified cipher list in OpenSSL format */
697
sk_cipher = SSL_get_ciphers(ssock->ossl_ssl);
698
for (i = 0; i < ssock->param.ciphers_num; ++i) {
699
for (j = 0; j < sk_SSL_CIPHER_num(sk_cipher); ++j) {
701
c = sk_SSL_CIPHER_value(sk_cipher, j);
702
if (ssock->param.ciphers[i] == (pj_ssl_cipher)
703
((pj_uint32_t)c->id & 0x00FFFFFF))
707
c_name = SSL_CIPHER_get_name(c);
709
/* Check buffer size */
710
if (cipher_list.slen + pj_ansi_strlen(c_name) + 2 > sizeof(buf)) {
711
pj_assert(!"Insufficient temporary buffer for cipher");
715
/* Add colon separator */
716
if (cipher_list.slen)
717
pj_strcat2(&cipher_list, ":");
720
pj_strcat2(&cipher_list, c_name);
726
/* Put NULL termination in the generated cipher list */
727
cipher_list.ptr[cipher_list.slen] = '\0';
729
/* Finally, set chosen cipher list */
730
ret = SSL_set_cipher_list(ssock->ossl_ssl, buf);
732
return GET_SSL_STATUS(ssock);
739
/* Parse OpenSSL ASN1_TIME to pj_time_val and GMT info */
740
static pj_bool_t parse_ossl_asn1_time(pj_time_val *tv, pj_bool_t *gmt,
743
unsigned long parts[7] = {0};
750
utc = tm->type == V_ASN1_UTCTIME;
756
*gmt = (*end == 'Z');
759
for (i = 0; i < 7 && p < end; ++i) {
763
/* 4 digits year part for non-UTC time format */
766
/* fraction of seconds */
768
st.slen = end - p + 1;
770
/* other parts always 2 digits length */
775
parts[i] = pj_strtoul(&st);
779
/* encode parts to pj_time_val */
782
pt.year += (pt.year < 50)? 2000:1900;
783
pt.mon = parts[1] - 1;
790
pj_time_encode(&pt, tv);
796
/* Get Common Name field string from a general name string */
797
static void get_cn_from_gen_name(const pj_str_t *gen_name, pj_str_t *cn)
799
pj_str_t CN_sign = {"/CN=", 4};
802
pj_bzero(cn, sizeof(cn));
804
p = pj_strstr(gen_name, &CN_sign);
808
p += 4; /* shift pointer to value part */
809
pj_strset(cn, p, gen_name->slen - (p - gen_name->ptr));
810
q = pj_strchr(cn, '/');
816
/* Get certificate info from OpenSSL X509, in case the certificate info
817
* hal already populated, this function will check if the contents need
818
* to be updated by inspecting the issuer and the serial number.
820
static void get_cert_info(pj_pool_t *pool, pj_ssl_cert_info *ci, X509 *x)
822
pj_bool_t update_needed;
824
pj_uint8_t serial_no[64] = {0}; /* should be >= sizeof(ci->serial_no) */
827
GENERAL_NAMES *names = NULL;
829
pj_assert(pool && ci && x);
832
X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof(buf));
835
p = (pj_uint8_t*) M_ASN1_STRING_data(X509_get_serialNumber(x));
836
len = M_ASN1_STRING_length(X509_get_serialNumber(x));
837
if (len > sizeof(ci->serial_no))
838
len = sizeof(ci->serial_no);
839
pj_memcpy(serial_no + sizeof(ci->serial_no) - len, p, len);
841
/* Check if the contents need to be updated. */
842
update_needed = pj_strcmp2(&ci->issuer.info, buf) ||
843
pj_memcmp(ci->serial_no, serial_no, sizeof(ci->serial_no));
847
/* Update cert info */
849
pj_bzero(ci, sizeof(pj_ssl_cert_info));
852
ci->version = X509_get_version(x) + 1;
855
pj_strdup2(pool, &ci->issuer.info, buf);
856
get_cn_from_gen_name(&ci->issuer.info, &ci->issuer.cn);
859
pj_memcpy(ci->serial_no, serial_no, sizeof(ci->serial_no));
862
pj_strdup2(pool, &ci->subject.info,
863
X509_NAME_oneline(X509_get_subject_name(x),
865
get_cn_from_gen_name(&ci->subject.info, &ci->subject.cn);
868
parse_ossl_asn1_time(&ci->validity.start, &ci->validity.gmt,
869
X509_get_notBefore(x));
870
parse_ossl_asn1_time(&ci->validity.end, &ci->validity.gmt,
871
X509_get_notAfter(x));
873
/* Subject Alternative Name extension */
874
if (ci->version >= 3) {
875
names = (GENERAL_NAMES*) X509_get_ext_d2i(x, NID_subject_alt_name,
881
cnt = sk_GENERAL_NAME_num(names);
882
ci->subj_alt_name.entry = pj_pool_calloc(pool, cnt,
883
sizeof(*ci->subj_alt_name.entry));
885
for (i = 0; i < cnt; ++i) {
886
unsigned char *p = 0;
887
pj_ssl_cert_name_type type = PJ_SSL_CERT_NAME_UNKNOWN;
888
const GENERAL_NAME *name;
890
name = sk_GENERAL_NAME_value(names, i);
892
switch (name->type) {
894
len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
895
type = PJ_SSL_CERT_NAME_RFC822;
898
len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
899
type = PJ_SSL_CERT_NAME_DNS;
902
len = ASN1_STRING_to_UTF8(&p, name->d.ia5);
903
type = PJ_SSL_CERT_NAME_URI;
906
p = ASN1_STRING_data(name->d.ip);
907
len = ASN1_STRING_length(name->d.ip);
908
type = PJ_SSL_CERT_NAME_IP;
914
if (p && len && type != PJ_SSL_CERT_NAME_UNKNOWN) {
915
ci->subj_alt_name.entry[ci->subj_alt_name.cnt].type = type;
916
if (type == PJ_SSL_CERT_NAME_IP) {
917
int af = pj_AF_INET();
918
if (len == sizeof(pj_in6_addr)) af = pj_AF_INET6();
919
pj_inet_ntop2(af, p, buf, sizeof(buf));
921
&ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
925
&ci->subj_alt_name.entry[ci->subj_alt_name.cnt].name,
929
ci->subj_alt_name.cnt++;
936
/* Update local & remote certificates info. This function should be
937
* called after handshake or renegotiation successfully completed.
939
static void update_certs_info(pj_ssl_sock_t *ssock)
943
pj_assert(ssock->ssl_state == SSL_STATE_ESTABLISHED);
945
/* Active local certificate */
946
x = SSL_get_certificate(ssock->ossl_ssl);
948
get_cert_info(ssock->pool, &ssock->local_cert_info, x);
949
/* Don't free local's X509! */
951
pj_bzero(&ssock->local_cert_info, sizeof(pj_ssl_cert_info));
954
/* Active remote certificate */
955
x = SSL_get_peer_certificate(ssock->ossl_ssl);
957
get_cert_info(ssock->pool, &ssock->remote_cert_info, x);
958
/* Free peer's X509 */
961
pj_bzero(&ssock->remote_cert_info, sizeof(pj_ssl_cert_info));
966
/* When handshake completed:
967
* - notify application
968
* - if handshake failed, reset SSL state
969
* - return PJ_FALSE when SSL socket instance is destroyed by application.
971
static pj_bool_t on_handshake_complete(pj_ssl_sock_t *ssock,
974
/* Cancel handshake timer */
975
if (ssock->timer.id == TIMER_HANDSHAKE_TIMEOUT) {
976
pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
977
ssock->timer.id = TIMER_NONE;
980
/* Update certificates info on successful handshake */
981
if (status == PJ_SUCCESS)
982
update_certs_info(ssock);
985
if (ssock->is_server) {
986
if (status != PJ_SUCCESS) {
987
/* Handshake failed in accepting, destroy our self silently. */
989
char errmsg[PJ_ERR_MSG_SIZE];
990
char buf[PJ_INET6_ADDRSTRLEN+10];
992
pj_strerror(status, errmsg, sizeof(errmsg));
993
PJ_LOG(3,(ssock->pool->obj_name, "Handshake failed in accepting "
995
pj_sockaddr_print(&ssock->rem_addr, buf, sizeof(buf), 3),
998
/* Workaround for ticket #985 */
999
#if defined(PJ_WIN32) && PJ_WIN32!=0
1000
if (ssock->param.timer_heap) {
1001
pj_time_val interval = {0, DELAYED_CLOSE_TIMEOUT};
1003
reset_ssl_sock_state(ssock);
1005
ssock->timer.id = TIMER_CLOSE;
1006
pj_time_val_normalize(&interval);
1007
if (pj_timer_heap_schedule(ssock->param.timer_heap,
1008
&ssock->timer, &interval) != 0)
1010
ssock->timer.id = TIMER_NONE;
1011
pj_ssl_sock_close(ssock);
1014
#endif /* PJ_WIN32 */
1016
pj_ssl_sock_close(ssock);
1020
/* Notify application the newly accepted SSL socket */
1021
if (ssock->param.cb.on_accept_complete) {
1023
ret = (*ssock->param.cb.on_accept_complete)
1024
(ssock->parent, ssock, (pj_sockaddr_t*)&ssock->rem_addr,
1025
pj_sockaddr_get_len((pj_sockaddr_t*)&ssock->rem_addr));
1026
if (ret == PJ_FALSE)
1033
/* On failure, reset SSL socket state first, as app may try to
1034
* reconnect in the callback.
1036
if (status != PJ_SUCCESS) {
1037
/* Server disconnected us, possibly due to SSL nego failure */
1038
if (status == PJ_EEOF) {
1040
err = ERR_get_error();
1041
if (err != SSL_ERROR_NONE)
1042
status = STATUS_FROM_SSL_ERR(ssock, err);
1044
reset_ssl_sock_state(ssock);
1046
if (ssock->param.cb.on_connect_complete) {
1048
ret = (*ssock->param.cb.on_connect_complete)(ssock, status);
1049
if (ret == PJ_FALSE)
1057
/* Flush write BIO to network socket. Note that any access to write BIO
1058
* MUST be serialized, so mutex protection must cover any call to OpenSSL
1059
* API (that possibly generate data for write BIO) along with the call to
1060
* this function (flushing all data in write BIO generated by above
1061
* OpenSSL API call).
1063
static pj_status_t flush_write_bio(pj_ssl_sock_t *ssock,
1064
pj_ioqueue_op_key_t *send_key,
1071
write_state_t *write_st = &ssock->write_state;
1072
write_data_t *wdata;
1073
pj_size_t avail_len, needed_len, skipped_len = 0;
1076
/* Check if there is data in write BIO, flush it if any */
1077
if (!BIO_pending(ssock->ossl_wbio))
1080
/* Get data and its length */
1081
len = BIO_get_mem_data(ssock->ossl_wbio, &data);
1085
/* Calculate buffer size needed, and align it to 8 */
1086
needed_len = len + sizeof(write_data_t);
1087
needed_len = ((needed_len + 7) >> 3) << 3;
1089
/* Check buffer availability */
1090
avail_len = write_st->max_len - write_st->len;
1091
if (avail_len < needed_len)
1094
/* More buffer availability check, note that the write data must be in
1095
* a contigue buffer.
1097
if (write_st->len == 0) {
1099
write_st->start = write_st->buf;
1100
wdata = (write_data_t*)write_st->start;
1105
pj_size_t reg1_len, reg2_len;
1107
/* Unused slots may be wrapped/splitted into two regions, so let's
1108
* analyze them if any region can hold the write data.
1110
reg1 = write_st->start + write_st->len;
1111
if (reg1 >= write_st->buf + write_st->max_len)
1112
reg1 -= write_st->max_len;
1113
reg1_len = write_st->max_len - write_st->len;
1114
if (reg1 + reg1_len > write_st->buf + write_st->max_len) {
1115
reg1_len = write_st->buf + write_st->max_len - reg1;
1116
reg2 = write_st->buf;
1117
reg2_len = write_st->start - write_st->buf;
1122
avail_len = PJ_MAX(reg1_len, reg2_len);
1123
if (avail_len < needed_len)
1126
/* Get write data pointer and update buffer length */
1127
if (reg1_len >= needed_len) {
1128
wdata = (write_data_t*)reg1;
1130
wdata = (write_data_t*)reg2;
1131
/* Unused slot in region 1 is skipped as current write data
1134
skipped_len = reg1_len;
1138
/* Copy the data and set its properties into the buffer */
1139
pj_bzero(wdata, sizeof(write_data_t));
1140
wdata->app_key = send_key;
1141
wdata->record_len = needed_len;
1142
wdata->data_len = len;
1143
wdata->plain_data_len = orig_len;
1144
wdata->flags = flags;
1145
pj_memcpy(&wdata->data, data, len);
1148
if (ssock->param.sock_type == pj_SOCK_STREAM()) {
1149
status = pj_activesock_send(ssock->asock, &wdata->key,
1150
wdata->data.content, &len,
1153
status = pj_activesock_sendto(ssock->asock, &wdata->key,
1154
wdata->data.content, &len,
1156
(pj_sockaddr_t*)&ssock->rem_addr,
1160
/* Oh no, EWOULDBLOCK! */
1161
if (status == PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK)) {
1162
/* Just return PJ_SUCCESS here, the pending data will be sent in next
1163
* call of this function since the data is still stored in write BIO.
1168
/* Reset write BIO after flushed */
1169
BIO_reset(ssock->ossl_wbio);
1171
if (status == PJ_EPENDING) {
1172
/* Update write state */
1173
pj_assert(skipped_len==0 || write_st->last_data);
1174
write_st->len += needed_len + skipped_len;
1175
if (write_st->last_data)
1176
write_st->last_data->record_len += skipped_len;
1177
write_st->last_data = wdata;
1184
static void on_timer(pj_timer_heap_t *th, struct pj_timer_entry *te)
1186
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)te->user_data;
1187
int timer_id = te->id;
1189
te->id = TIMER_NONE;
1194
case TIMER_HANDSHAKE_TIMEOUT:
1195
PJ_LOG(1,(ssock->pool->obj_name, "SSL timeout after %d.%ds",
1196
ssock->param.timeout.sec, ssock->param.timeout.msec));
1198
on_handshake_complete(ssock, PJ_ETIMEDOUT);
1201
pj_ssl_sock_close(ssock);
1204
pj_assert(!"Unknown timer");
1210
/* Asynchronouse handshake */
1211
static pj_status_t do_handshake(pj_ssl_sock_t *ssock)
1216
pj_lock_acquire(ssock->write_mutex);
1218
/* Perform SSL handshake */
1219
err = SSL_do_handshake(ssock->ossl_ssl);
1221
/* SSL_do_handshake() may put some pending data into SSL write BIO,
1224
status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
1225
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1226
pj_lock_release(ssock->write_mutex);
1230
pj_lock_release(ssock->write_mutex);
1233
err = SSL_get_error(ssock->ossl_ssl, err);
1234
if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1236
/* Handshake fails */
1237
status = STATUS_FROM_SSL_ERR(ssock, err);
1242
/* Check if handshake has been completed */
1243
if (SSL_is_init_finished(ssock->ossl_ssl)) {
1244
ssock->ssl_state = SSL_STATE_ESTABLISHED;
1253
*******************************************************************
1254
* Active socket callbacks.
1255
*******************************************************************
1258
static pj_bool_t asock_on_data_read (pj_activesock_t *asock,
1262
pj_size_t *remainder)
1264
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1265
pj_activesock_get_user_data(asock);
1268
/* Socket error or closed */
1269
if (data && size > 0) {
1270
/* Consume the whole data */
1271
nwritten = BIO_write(ssock->ossl_rbio, data, size);
1272
if (nwritten < size) {
1273
status = GET_SSL_STATUS(ssock);
1278
/* Check if SSL handshake hasn't finished yet */
1279
if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1280
pj_bool_t ret = PJ_TRUE;
1282
if (status == PJ_SUCCESS)
1283
status = do_handshake(ssock);
1285
/* Not pending is either success or failed */
1286
if (status != PJ_EPENDING)
1287
ret = on_handshake_complete(ssock, status);
1292
/* See if there is any decrypted data for the application */
1293
if (ssock->read_started) {
1295
read_data_t *buf = *(OFFSET_OF_READ_DATA_PTR(ssock, data));
1296
void *data_ = (pj_int8_t*)buf->data + buf->len;
1297
int size_ = ssock->read_size - buf->len;
1299
/* SSL_read() may write some data to BIO write when re-negotiation
1300
* is on progress, so let's protect it with write mutex.
1302
pj_lock_acquire(ssock->write_mutex);
1303
size_ = SSL_read(ssock->ossl_ssl, data_, size_);
1304
pj_lock_release(ssock->write_mutex);
1306
if (size_ > 0 || status != PJ_SUCCESS) {
1307
if (ssock->param.cb.on_data_read) {
1309
pj_size_t remainder_ = 0;
1314
ret = (*ssock->param.cb.on_data_read)(ssock, buf->data,
1318
/* We've been destroyed */
1322
/* Application may have left some data to be consumed
1325
buf->len = remainder_;
1328
/* Active socket signalled connection closed/error, this has
1329
* been signalled to the application along with any remaining
1330
* buffer. So, let's just reset SSL socket now.
1332
if (status != PJ_SUCCESS) {
1333
reset_ssl_sock_state(ssock);
1339
int err = SSL_get_error(ssock->ossl_ssl, size);
1341
/* SSL might just return SSL_ERROR_WANT_READ in
1344
if (err != SSL_ERROR_NONE && err != SSL_ERROR_WANT_READ)
1346
/* Reset SSL socket state, then return PJ_FALSE */
1347
status = STATUS_FROM_SSL_ERR(ssock, err);
1348
reset_ssl_sock_state(ssock);
1352
status = do_handshake(ssock);
1353
if (status == PJ_SUCCESS) {
1354
/* Renegotiation completed */
1356
/* Update certificates */
1357
update_certs_info(ssock);
1359
pj_lock_acquire(ssock->write_mutex);
1360
status = flush_delayed_send(ssock);
1361
pj_lock_release(ssock->write_mutex);
1363
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
1364
PJ_PERROR(1,(ssock->pool->obj_name, status,
1365
"Failed to flush delayed send"));
1368
} else if (status != PJ_EPENDING) {
1369
PJ_PERROR(1,(ssock->pool->obj_name, status,
1370
"Renegotiation failed"));
1382
if (ssock->ssl_state == SSL_STATE_HANDSHAKING)
1383
return on_handshake_complete(ssock, status);
1385
if (ssock->read_started && ssock->param.cb.on_data_read) {
1387
ret = (*ssock->param.cb.on_data_read)(ssock, NULL, 0, status,
1390
/* We've been destroyed */
1395
reset_ssl_sock_state(ssock);
1400
static pj_bool_t asock_on_data_sent (pj_activesock_t *asock,
1401
pj_ioqueue_op_key_t *send_key,
1404
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1405
pj_activesock_get_user_data(asock);
1407
PJ_UNUSED_ARG(send_key);
1408
PJ_UNUSED_ARG(sent);
1410
if (ssock->ssl_state == SSL_STATE_HANDSHAKING) {
1411
/* Initial handshaking */
1414
status = do_handshake(ssock);
1415
/* Not pending is either success or failed */
1416
if (status != PJ_EPENDING)
1417
return on_handshake_complete(ssock, status);
1419
} else if (send_key != &ssock->handshake_op_key) {
1420
/* Some data has been sent, notify application */
1421
write_data_t *wdata = (write_data_t*)send_key;
1422
if (ssock->param.cb.on_data_sent) {
1424
ret = (*ssock->param.cb.on_data_sent)(ssock, wdata->app_key,
1425
wdata->plain_data_len);
1427
/* We've been destroyed */
1432
/* Update write buffer state */
1433
pj_lock_acquire(ssock->write_mutex);
1434
ssock->write_state.start += wdata->record_len;
1435
ssock->write_state.len -= wdata->record_len;
1436
if (ssock->write_state.last_data == wdata) {
1437
pj_assert(ssock->write_state.len == 0);
1438
ssock->write_state.last_data = NULL;
1440
pj_lock_release(ssock->write_mutex);
1443
/* SSL re-negotiation is on-progress, just do nothing */
1450
static pj_bool_t asock_on_accept_complete (pj_activesock_t *asock,
1452
const pj_sockaddr_t *src_addr,
1455
pj_ssl_sock_t *ssock_parent = (pj_ssl_sock_t*)
1456
pj_activesock_get_user_data(asock);
1457
pj_ssl_sock_t *ssock;
1458
pj_activesock_cb asock_cb;
1459
pj_activesock_cfg asock_cfg;
1463
PJ_UNUSED_ARG(src_addr_len);
1465
/* Create new SSL socket instance */
1466
status = pj_ssl_sock_create(ssock_parent->pool, &ssock_parent->param,
1468
if (status != PJ_SUCCESS)
1471
/* Update new SSL socket attributes */
1472
ssock->sock = newsock;
1473
ssock->parent = ssock_parent;
1474
ssock->is_server = PJ_TRUE;
1475
if (ssock_parent->cert) {
1476
status = pj_ssl_sock_set_certificate(ssock, ssock->pool,
1477
ssock_parent->cert);
1478
if (status != PJ_SUCCESS)
1482
/* Apply QoS, if specified */
1483
status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
1484
&ssock->param.qos_params, 1,
1485
ssock->pool->obj_name, NULL);
1486
if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
1489
/* Update local address */
1490
ssock->addr_len = src_addr_len;
1491
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1493
if (status != PJ_SUCCESS) {
1494
/* This fails on few envs, e.g: win IOCP, just tolerate this and
1495
* use parent local address instead.
1497
pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);
1500
/* Set remote address */
1501
pj_sockaddr_cp(&ssock->rem_addr, src_addr);
1503
/* Create SSL context */
1504
status = create_ssl(ssock);
1505
if (status != PJ_SUCCESS)
1508
/* Prepare read buffer */
1509
ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1510
ssock->param.async_cnt,
1512
for (i = 0; i<ssock->param.async_cnt; ++i) {
1513
ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1515
ssock->param.read_buffer_size +
1516
sizeof(read_data_t*));
1519
/* Create active socket */
1520
pj_activesock_cfg_default(&asock_cfg);
1521
asock_cfg.async_cnt = ssock->param.async_cnt;
1522
asock_cfg.concurrency = ssock->param.concurrency;
1523
asock_cfg.whole_data = PJ_TRUE;
1525
pj_bzero(&asock_cb, sizeof(asock_cb));
1526
asock_cb.on_data_read = asock_on_data_read;
1527
asock_cb.on_data_sent = asock_on_data_sent;
1529
status = pj_activesock_create(ssock->pool,
1531
ssock->param.sock_type,
1533
ssock->param.ioqueue,
1538
if (status != PJ_SUCCESS)
1542
status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1543
ssock->param.read_buffer_size,
1545
PJ_IOQUEUE_ALWAYS_ASYNC);
1546
if (status != PJ_SUCCESS)
1549
/* Prepare write/send state */
1550
pj_assert(ssock->write_state.max_len == 0);
1551
ssock->write_state.buf = (char*)
1552
pj_pool_alloc(ssock->pool,
1553
ssock->param.send_buffer_size);
1554
ssock->write_state.max_len = ssock->param.send_buffer_size;
1555
ssock->write_state.start = ssock->write_state.buf;
1556
ssock->write_state.len = 0;
1558
/* Start handshake timer */
1559
if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
1560
ssock->param.timeout.msec != 0))
1562
pj_assert(ssock->timer.id == TIMER_NONE);
1563
ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
1564
status = pj_timer_heap_schedule(ssock->param.timer_heap,
1566
&ssock->param.timeout);
1567
if (status != PJ_SUCCESS)
1568
ssock->timer.id = TIMER_NONE;
1571
/* Start SSL handshake */
1572
ssock->ssl_state = SSL_STATE_HANDSHAKING;
1573
SSL_set_accept_state(ssock->ossl_ssl);
1574
status = do_handshake(ssock);
1577
if (ssock && status != PJ_EPENDING)
1578
on_handshake_complete(ssock, status);
1580
/* Must return PJ_TRUE whatever happened, as active socket must
1581
* continue listening.
1587
static pj_bool_t asock_on_connect_complete (pj_activesock_t *asock,
1590
pj_ssl_sock_t *ssock = (pj_ssl_sock_t*)
1591
pj_activesock_get_user_data(asock);
1594
if (status != PJ_SUCCESS)
1597
/* Update local address */
1598
ssock->addr_len = sizeof(pj_sockaddr);
1599
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
1601
if (status != PJ_SUCCESS)
1604
/* Create SSL context */
1605
status = create_ssl(ssock);
1606
if (status != PJ_SUCCESS)
1609
/* Prepare read buffer */
1610
ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool,
1611
ssock->param.async_cnt,
1613
for (i = 0; i<ssock->param.async_cnt; ++i) {
1614
ssock->asock_rbuf[i] = (void*) pj_pool_alloc(
1616
ssock->param.read_buffer_size +
1617
sizeof(read_data_t*));
1621
status = pj_activesock_start_read2(ssock->asock, ssock->pool,
1622
ssock->param.read_buffer_size,
1624
PJ_IOQUEUE_ALWAYS_ASYNC);
1625
if (status != PJ_SUCCESS)
1628
/* Prepare write/send state */
1629
pj_assert(ssock->write_state.max_len == 0);
1630
ssock->write_state.buf = (char*)
1631
pj_pool_alloc(ssock->pool,
1632
ssock->param.send_buffer_size);
1633
ssock->write_state.max_len = ssock->param.send_buffer_size;
1634
ssock->write_state.start = ssock->write_state.buf;
1635
ssock->write_state.len = 0;
1637
#ifdef SSL_set_tlsext_host_name
1638
/* Set server name to connect */
1639
if (ssock->param.server_name.slen) {
1640
/* Server name is null terminated already */
1641
if (!SSL_set_tlsext_host_name(ssock->ossl_ssl,
1642
ssock->param.server_name.ptr))
1644
char err_str[PJ_ERR_MSG_SIZE];
1646
ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str));
1647
PJ_LOG(3,(ssock->pool->obj_name, "SSL_set_tlsext_host_name() "
1648
"failed: %s", err_str));
1653
/* Start SSL handshake */
1654
ssock->ssl_state = SSL_STATE_HANDSHAKING;
1655
SSL_set_connect_state(ssock->ossl_ssl);
1657
status = do_handshake(ssock);
1658
if (status != PJ_EPENDING)
1664
return on_handshake_complete(ssock, status);
1670
*******************************************************************
1672
*******************************************************************
1675
/* Load credentials from files. */
1676
PJ_DEF(pj_status_t) pj_ssl_cert_load_from_files (pj_pool_t *pool,
1677
const pj_str_t *CA_file,
1678
const pj_str_t *cert_file,
1679
const pj_str_t *privkey_file,
1680
const pj_str_t *privkey_pass,
1681
pj_ssl_cert_t **p_cert)
1683
pj_ssl_cert_t *cert;
1685
PJ_ASSERT_RETURN(pool && CA_file && cert_file && privkey_file, PJ_EINVAL);
1687
cert = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1688
pj_strdup_with_null(pool, &cert->CA_file, CA_file);
1689
pj_strdup_with_null(pool, &cert->cert_file, cert_file);
1690
pj_strdup_with_null(pool, &cert->privkey_file, privkey_file);
1691
pj_strdup_with_null(pool, &cert->privkey_pass, privkey_pass);
1699
/* Set SSL socket credentials. */
1700
PJ_DECL(pj_status_t) pj_ssl_sock_set_certificate(
1701
pj_ssl_sock_t *ssock,
1703
const pj_ssl_cert_t *cert)
1705
pj_ssl_cert_t *cert_;
1707
PJ_ASSERT_RETURN(ssock && pool && cert, PJ_EINVAL);
1709
cert_ = PJ_POOL_ZALLOC_T(pool, pj_ssl_cert_t);
1710
pj_memcpy(cert_, cert, sizeof(cert));
1711
pj_strdup_with_null(pool, &cert_->CA_file, &cert->CA_file);
1712
pj_strdup_with_null(pool, &cert_->cert_file, &cert->cert_file);
1713
pj_strdup_with_null(pool, &cert_->privkey_file, &cert->privkey_file);
1714
pj_strdup_with_null(pool, &cert_->privkey_pass, &cert->privkey_pass);
1716
ssock->cert = cert_;
1722
/* Get available ciphers. */
1723
PJ_DEF(pj_status_t) pj_ssl_cipher_get_availables(pj_ssl_cipher ciphers[],
1724
unsigned *cipher_num)
1728
PJ_ASSERT_RETURN(ciphers && cipher_num, PJ_EINVAL);
1730
if (openssl_cipher_num == 0) {
1735
if (openssl_cipher_num == 0) {
1737
return PJ_ENOTFOUND;
1740
*cipher_num = PJ_MIN(*cipher_num, openssl_cipher_num);
1742
for (i = 0; i < *cipher_num; ++i)
1743
ciphers[i] = openssl_ciphers[i].id;
1749
/* Get cipher name string */
1750
PJ_DEF(const char*) pj_ssl_cipher_name(pj_ssl_cipher cipher)
1754
if (openssl_cipher_num == 0) {
1759
for (i = 0; i < openssl_cipher_num; ++i) {
1760
if (cipher == openssl_ciphers[i].id)
1761
return openssl_ciphers[i].name;
1767
/* Check if the specified cipher is supported by SSL/TLS backend. */
1768
PJ_DEF(pj_bool_t) pj_ssl_cipher_is_supported(pj_ssl_cipher cipher)
1772
if (openssl_cipher_num == 0) {
1777
for (i = 0; i < openssl_cipher_num; ++i) {
1778
if (cipher == openssl_ciphers[i].id)
1787
* Create SSL socket instance.
1789
PJ_DEF(pj_status_t) pj_ssl_sock_create (pj_pool_t *pool,
1790
const pj_ssl_sock_param *param,
1791
pj_ssl_sock_t **p_ssock)
1793
pj_ssl_sock_t *ssock;
1796
PJ_ASSERT_RETURN(pool && param && p_ssock, PJ_EINVAL);
1797
PJ_ASSERT_RETURN(param->sock_type == pj_SOCK_STREAM(), PJ_ENOTSUP);
1799
pool = pj_pool_create(pool->factory, "ssl%p", 512, 512, NULL);
1801
/* Create secure socket */
1802
ssock = PJ_POOL_ZALLOC_T(pool, pj_ssl_sock_t);
1804
ssock->sock = PJ_INVALID_SOCKET;
1805
ssock->ssl_state = SSL_STATE_NULL;
1806
pj_list_init(&ssock->write_pending);
1807
pj_list_init(&ssock->write_pending_empty);
1808
pj_timer_entry_init(&ssock->timer, 0, ssock, &on_timer);
1810
/* Create secure socket mutex */
1811
status = pj_lock_create_recursive_mutex(pool, pool->obj_name,
1812
&ssock->write_mutex);
1813
if (status != PJ_SUCCESS)
1816
/* Init secure socket param */
1817
ssock->param = *param;
1818
ssock->param.read_buffer_size = ((ssock->param.read_buffer_size+7)>>3)<<3;
1819
if (param->ciphers_num > 0) {
1821
ssock->param.ciphers = (pj_ssl_cipher*)
1822
pj_pool_calloc(pool, param->ciphers_num,
1823
sizeof(pj_ssl_cipher));
1824
for (i = 0; i < param->ciphers_num; ++i)
1825
ssock->param.ciphers[i] = param->ciphers[i];
1828
/* Server name must be null-terminated */
1829
pj_strdup_with_null(pool, &ssock->param.server_name,
1830
¶m->server_name);
1840
* Close the secure socket. This will unregister the socket from the
1841
* ioqueue and ultimately close the socket.
1843
PJ_DEF(pj_status_t) pj_ssl_sock_close(pj_ssl_sock_t *ssock)
1847
PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1852
if (ssock->timer.id != TIMER_NONE) {
1853
pj_timer_heap_cancel(ssock->param.timer_heap, &ssock->timer);
1854
ssock->timer.id = TIMER_NONE;
1857
reset_ssl_sock_state(ssock);
1858
pj_lock_destroy(ssock->write_mutex);
1863
pj_pool_release(pool);
1870
* Associate arbitrary data with the secure socket.
1872
PJ_DEF(pj_status_t) pj_ssl_sock_set_user_data(pj_ssl_sock_t *ssock,
1875
PJ_ASSERT_RETURN(ssock, PJ_EINVAL);
1877
ssock->param.user_data = user_data;
1883
* Retrieve the user data previously associated with this secure
1886
PJ_DEF(void*) pj_ssl_sock_get_user_data(pj_ssl_sock_t *ssock)
1888
PJ_ASSERT_RETURN(ssock, NULL);
1890
return ssock->param.user_data;
1895
* Retrieve the local address and port used by specified SSL socket.
1897
PJ_DEF(pj_status_t) pj_ssl_sock_get_info (pj_ssl_sock_t *ssock,
1898
pj_ssl_sock_info *info)
1900
pj_bzero(info, sizeof(*info));
1902
/* Established flag */
1903
info->established = (ssock->ssl_state == SSL_STATE_ESTABLISHED);
1906
info->proto = ssock->param.proto;
1909
pj_sockaddr_cp(&info->local_addr, &ssock->local_addr);
1911
if (info->established) {
1912
const SSL_CIPHER *cipher;
1914
/* Current cipher */
1915
cipher = SSL_get_current_cipher(ssock->ossl_ssl);
1916
info->cipher = (cipher->id & 0x00FFFFFF);
1918
/* Remote address */
1919
pj_sockaddr_cp(&info->remote_addr, &ssock->rem_addr);
1921
/* Certificates info */
1922
info->local_cert_info = &ssock->local_cert_info;
1923
info->remote_cert_info = &ssock->remote_cert_info;
1925
/* Verification status */
1926
info->verify_status = ssock->verify_status;
1929
/* Last known OpenSSL error code */
1930
info->last_native_err = ssock->last_err;
1937
* Starts read operation on this secure socket.
1939
PJ_DEF(pj_status_t) pj_ssl_sock_start_read (pj_ssl_sock_t *ssock,
1947
PJ_ASSERT_RETURN(ssock && pool && buff_size, PJ_EINVAL);
1948
PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
1950
readbuf = (void**) pj_pool_calloc(pool, ssock->param.async_cnt,
1953
for (i=0; i<ssock->param.async_cnt; ++i) {
1954
readbuf[i] = pj_pool_alloc(pool, buff_size);
1957
return pj_ssl_sock_start_read2(ssock, pool, buff_size,
1963
* Same as #pj_ssl_sock_start_read(), except that the application
1964
* supplies the buffers for the read operation so that the acive socket
1965
* does not have to allocate the buffers.
1967
PJ_DEF(pj_status_t) pj_ssl_sock_start_read2 (pj_ssl_sock_t *ssock,
1975
PJ_ASSERT_RETURN(ssock && pool && buff_size && readbuf, PJ_EINVAL);
1976
PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
1978
/* Create SSL socket read buffer */
1979
ssock->ssock_rbuf = (read_data_t*)pj_pool_calloc(pool,
1980
ssock->param.async_cnt,
1981
sizeof(read_data_t));
1983
/* Store SSL socket read buffer pointer in the activesock read buffer */
1984
for (i=0; i<ssock->param.async_cnt; ++i) {
1985
read_data_t **p_ssock_rbuf =
1986
OFFSET_OF_READ_DATA_PTR(ssock, ssock->asock_rbuf[i]);
1988
ssock->ssock_rbuf[i].data = readbuf[i];
1989
ssock->ssock_rbuf[i].len = 0;
1991
*p_ssock_rbuf = &ssock->ssock_rbuf[i];
1994
ssock->read_size = buff_size;
1995
ssock->read_started = PJ_TRUE;
1996
ssock->read_flags = flags;
2003
* Same as pj_ssl_sock_start_read(), except that this function is used
2004
* only for datagram sockets, and it will trigger \a on_data_recvfrom()
2007
PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom (pj_ssl_sock_t *ssock,
2012
PJ_UNUSED_ARG(ssock);
2013
PJ_UNUSED_ARG(pool);
2014
PJ_UNUSED_ARG(buff_size);
2015
PJ_UNUSED_ARG(flags);
2022
* Same as #pj_ssl_sock_start_recvfrom() except that the recvfrom()
2023
* operation takes the buffer from the argument rather than creating
2026
PJ_DEF(pj_status_t) pj_ssl_sock_start_recvfrom2 (pj_ssl_sock_t *ssock,
2032
PJ_UNUSED_ARG(ssock);
2033
PJ_UNUSED_ARG(pool);
2034
PJ_UNUSED_ARG(buff_size);
2035
PJ_UNUSED_ARG(readbuf);
2036
PJ_UNUSED_ARG(flags);
2041
/* Write plain data to SSL and flush write BIO. Note that accessing
2042
* write BIO must be serialized, so a call to this function must be
2043
* protected by write mutex of SSL socket.
2045
static pj_status_t ssl_write(pj_ssl_sock_t *ssock,
2046
pj_ioqueue_op_key_t *send_key,
2054
/* Write the plain data to SSL, after SSL encrypts it, write BIO will
2055
* contain the secured data to be sent via socket. Note that re-
2056
* negotitation may be on progress, so sending data should be delayed
2057
* until re-negotiation is completed.
2059
nwritten = SSL_write(ssock->ossl_ssl, data, size);
2061
if (nwritten == size) {
2062
/* All data written, flush write BIO to network socket */
2063
status = flush_write_bio(ssock, send_key, size, flags);
2064
} else if (nwritten <= 0) {
2065
/* SSL failed to process the data, it may just that re-negotiation
2069
err = SSL_get_error(ssock->ossl_ssl, nwritten);
2070
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_NONE) {
2071
/* Re-negotiation is on progress, flush re-negotiation data */
2072
status = flush_write_bio(ssock, &ssock->handshake_op_key, 0, 0);
2073
if (status == PJ_SUCCESS || status == PJ_EPENDING)
2074
/* Just return PJ_EBUSY when re-negotiation is on progress */
2077
/* Some problem occured */
2078
status = STATUS_FROM_SSL_ERR(ssock, err);
2081
/* nwritten < *size, shouldn't happen, unless write BIO cannot hold
2082
* the whole secured data, perhaps because of insufficient memory.
2090
/* Flush delayed data sending in the write pending list. Note that accessing
2091
* write pending list must be serialized, so a call to this function must be
2092
* protected by write mutex of SSL socket.
2094
static pj_status_t flush_delayed_send(pj_ssl_sock_t *ssock)
2096
while (!pj_list_empty(&ssock->write_pending)) {
2097
write_pending_t *wp;
2100
wp = ssock->write_pending.next;
2102
status = ssl_write(ssock, &wp->data.key, wp->data.data.ptr,
2103
wp->data.plain_data_len, wp->data.flags);
2104
if (status != PJ_SUCCESS)
2108
pj_list_push_back(&ssock->write_pending_empty, wp);
2114
/* Sending is delayed, push back the sending data into pending list. Note that
2115
* accessing write pending list must be serialized, so a call to this function
2116
* must be protected by write mutex of SSL socket.
2118
static pj_status_t delay_send (pj_ssl_sock_t *ssock,
2119
pj_ioqueue_op_key_t *send_key,
2124
write_pending_t *wp;
2126
/* Init write pending instance */
2127
if (!pj_list_empty(&ssock->write_pending_empty)) {
2128
wp = ssock->write_pending_empty.next;
2131
wp = PJ_POOL_ZALLOC_T(ssock->pool, write_pending_t);
2134
wp->data.app_key = send_key;
2135
wp->data.plain_data_len = size;
2136
wp->data.data.ptr = data;
2137
wp->data.flags = flags;
2139
pj_list_push_back(&ssock->write_pending, wp);
2141
/* Must return PJ_EPENDING */
2146
* Send data using the socket.
2148
PJ_DEF(pj_status_t) pj_ssl_sock_send (pj_ssl_sock_t *ssock,
2149
pj_ioqueue_op_key_t *send_key,
2156
PJ_ASSERT_RETURN(ssock && data && size && (*size>0), PJ_EINVAL);
2157
PJ_ASSERT_RETURN(ssock->ssl_state==SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2159
pj_lock_acquire(ssock->write_mutex);
2161
/* Flush delayed send first. Sending data might be delayed when
2162
* re-negotiation is on-progress.
2164
status = flush_delayed_send(ssock);
2165
if (status == PJ_EBUSY) {
2166
/* Re-negotiation is on progress, delay sending */
2167
status = delay_send(ssock, send_key, data, *size, flags);
2169
} else if (status != PJ_SUCCESS) {
2173
/* Write data to SSL */
2174
status = ssl_write(ssock, send_key, data, *size, flags);
2175
if (status == PJ_EBUSY) {
2176
/* Re-negotiation is on progress, delay sending */
2177
status = delay_send(ssock, send_key, data, *size, flags);
2181
pj_lock_release(ssock->write_mutex);
2187
* Send datagram using the socket.
2189
PJ_DEF(pj_status_t) pj_ssl_sock_sendto (pj_ssl_sock_t *ssock,
2190
pj_ioqueue_op_key_t *send_key,
2194
const pj_sockaddr_t *addr,
2197
PJ_UNUSED_ARG(ssock);
2198
PJ_UNUSED_ARG(send_key);
2199
PJ_UNUSED_ARG(data);
2200
PJ_UNUSED_ARG(size);
2201
PJ_UNUSED_ARG(flags);
2202
PJ_UNUSED_ARG(addr);
2203
PJ_UNUSED_ARG(addr_len);
2210
* Starts asynchronous socket accept() operations on this secure socket.
2212
PJ_DEF(pj_status_t) pj_ssl_sock_start_accept (pj_ssl_sock_t *ssock,
2214
const pj_sockaddr_t *localaddr,
2217
pj_activesock_cb asock_cb;
2218
pj_activesock_cfg asock_cfg;
2221
PJ_ASSERT_RETURN(ssock && pool && localaddr && addr_len, PJ_EINVAL);
2224
status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2226
if (status != PJ_SUCCESS)
2229
/* Apply QoS, if specified */
2230
status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2231
&ssock->param.qos_params, 2,
2232
ssock->pool->obj_name, NULL);
2233
if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2237
status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2238
if (status != PJ_SUCCESS)
2241
/* Start listening to the address */
2242
status = pj_sock_listen(ssock->sock, PJ_SOMAXCONN);
2243
if (status != PJ_SUCCESS)
2246
/* Create active socket */
2247
pj_activesock_cfg_default(&asock_cfg);
2248
asock_cfg.async_cnt = ssock->param.async_cnt;
2249
asock_cfg.concurrency = ssock->param.concurrency;
2250
asock_cfg.whole_data = PJ_TRUE;
2252
pj_bzero(&asock_cb, sizeof(asock_cb));
2253
asock_cb.on_accept_complete = asock_on_accept_complete;
2255
status = pj_activesock_create(pool,
2257
ssock->param.sock_type,
2259
ssock->param.ioqueue,
2264
if (status != PJ_SUCCESS)
2267
/* Start accepting */
2268
status = pj_activesock_start_accept(ssock->asock, pool);
2269
if (status != PJ_SUCCESS)
2272
/* Update local address */
2273
ssock->addr_len = addr_len;
2274
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2276
if (status != PJ_SUCCESS)
2277
pj_sockaddr_cp(&ssock->local_addr, localaddr);
2279
ssock->is_server = PJ_TRUE;
2284
reset_ssl_sock_state(ssock);
2290
* Starts asynchronous socket connect() operation.
2292
PJ_DECL(pj_status_t) pj_ssl_sock_start_connect(pj_ssl_sock_t *ssock,
2294
const pj_sockaddr_t *localaddr,
2295
const pj_sockaddr_t *remaddr,
2298
pj_activesock_cb asock_cb;
2299
pj_activesock_cfg asock_cfg;
2302
PJ_ASSERT_RETURN(ssock && pool && localaddr && remaddr && addr_len,
2306
status = pj_sock_socket(ssock->param.sock_af, ssock->param.sock_type, 0,
2308
if (status != PJ_SUCCESS)
2311
/* Apply QoS, if specified */
2312
status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,
2313
&ssock->param.qos_params, 2,
2314
ssock->pool->obj_name, NULL);
2315
if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)
2319
status = pj_sock_bind(ssock->sock, localaddr, addr_len);
2320
if (status != PJ_SUCCESS)
2323
/* Create active socket */
2324
pj_activesock_cfg_default(&asock_cfg);
2325
asock_cfg.async_cnt = ssock->param.async_cnt;
2326
asock_cfg.concurrency = ssock->param.concurrency;
2327
asock_cfg.whole_data = PJ_TRUE;
2329
pj_bzero(&asock_cb, sizeof(asock_cb));
2330
asock_cb.on_connect_complete = asock_on_connect_complete;
2331
asock_cb.on_data_read = asock_on_data_read;
2332
asock_cb.on_data_sent = asock_on_data_sent;
2334
status = pj_activesock_create(pool,
2336
ssock->param.sock_type,
2338
ssock->param.ioqueue,
2343
if (status != PJ_SUCCESS)
2346
/* Save remote address */
2347
pj_sockaddr_cp(&ssock->rem_addr, remaddr);
2350
if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||
2351
ssock->param.timeout.msec != 0))
2353
pj_assert(ssock->timer.id == TIMER_NONE);
2354
ssock->timer.id = TIMER_HANDSHAKE_TIMEOUT;
2355
status = pj_timer_heap_schedule(ssock->param.timer_heap,
2357
&ssock->param.timeout);
2358
if (status != PJ_SUCCESS)
2359
ssock->timer.id = TIMER_NONE;
2362
status = pj_activesock_start_connect(ssock->asock, pool, remaddr,
2365
if (status == PJ_SUCCESS)
2366
asock_on_connect_complete(ssock->asock, PJ_SUCCESS);
2367
else if (status != PJ_EPENDING)
2370
/* Update local address */
2371
ssock->addr_len = addr_len;
2372
status = pj_sock_getsockname(ssock->sock, &ssock->local_addr,
2374
/* Note that we may not get an IP address here. This can
2375
* happen for example on Windows, where getsockname()
2376
* would return 0.0.0.0 if socket has just started the
2377
* async connect. In this case, just leave the local
2378
* address with 0.0.0.0 for now; it will be updated
2379
* once the socket is established.
2382
/* Update SSL state */
2383
ssock->is_server = PJ_FALSE;
2388
reset_ssl_sock_state(ssock);
2393
PJ_DEF(pj_status_t) pj_ssl_sock_renegotiate(pj_ssl_sock_t *ssock)
2398
PJ_ASSERT_RETURN(ssock->ssl_state == SSL_STATE_ESTABLISHED, PJ_EINVALIDOP);
2400
if (SSL_renegotiate_pending(ssock->ossl_ssl))
2403
ret = SSL_renegotiate(ssock->ossl_ssl);
2405
status = GET_SSL_STATUS(ssock);
2407
status = do_handshake(ssock);
2413
#endif /* PJ_HAS_SSL_SOCK */