1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
|
/*
belle-sip - SIP (RFC3261) library.
Copyright (C) 2013 Belledonne Communications SARL
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "belle_sip_internal.h"
#include "stream_channel.h"
/* Uncomment to get very verbose polarssl logs*/
//#define ENABLE_POLARSSL_LOGS
#include <mbedtls/ssl.h>
#include <mbedtls/error.h>
#include <mbedtls/pem.h>
#include <mbedtls/x509.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/sha1.h>
#include <mbedtls/sha256.h>
#include <mbedtls/sha512.h>
#include <mbedtls/net.h>
#include <mbedtls/debug.h>
#include <mbedtls/compat-1.3.h>
struct belle_sip_certificates_chain {
belle_sip_object_t objet;
x509_crt cert;
};
struct belle_sip_signing_key {
belle_sip_object_t objet;
pk_context key;
};
/**
* Retrieve key or certificate in a string(PEM format)
*/
char *belle_sip_certificates_chain_get_pem(belle_sip_certificates_chain_t *cert) {
char *pem_certificate = NULL;
size_t olen=0;
if (cert == NULL) return NULL;
pem_certificate = (char*)belle_sip_malloc(4096);
pem_write_buffer("-----BEGIN CERTIFICATE-----\n", "-----END CERTIFICATE-----\n", cert->cert.raw.p, cert->cert.raw.len, (unsigned char*)pem_certificate, 4096, &olen );
return pem_certificate;
}
char *belle_sip_signing_key_get_pem(belle_sip_signing_key_t *key) {
char *pem_key;
if (key == NULL) return NULL;
pem_key = (char *)belle_sip_malloc(4096);
pk_write_key_pem( &(key->key), (unsigned char *)pem_key, 4096);
return pem_key;
}
/*************tls********/
// SSL verification callback prototype
// der - raw certificate data, in DER format
// length - length of certificate DER data
// depth - position of certificate in cert chain, ending at 0 = root or top
// flags - verification state for CURRENT certificate only
typedef int (*verify_cb_error_cb_t)(unsigned char* der, int length, int depth, int* flags);
static verify_cb_error_cb_t tls_verify_cb_error_cb = NULL;
static int tls_process_data(belle_sip_channel_t *obj,unsigned int revents);
struct belle_sip_tls_channel{
belle_sip_stream_channel_t base;
ssl_context sslctx;
mbedtls_ssl_config sslconf;
x509_crt root_ca;
struct sockaddr_storage ss;
socklen_t socklen;
int socket_connected;
char *cur_debug_msg;
belle_sip_certificates_chain_t* client_cert_chain;
belle_sip_signing_key_t* client_cert_key;
belle_tls_verify_policy_t *verify_ctx;
};
static void tls_channel_close(belle_sip_tls_channel_t *obj){
belle_sip_socket_t sock = belle_sip_source_get_socket((belle_sip_source_t*)obj);
if (sock!=-1 && belle_sip_channel_get_state((belle_sip_channel_t*)obj)!=BELLE_SIP_CHANNEL_ERROR)
ssl_close_notify(&obj->sslctx);
stream_channel_close((belle_sip_stream_channel_t*)obj);
ssl_session_reset(&obj->sslctx);
obj->socket_connected=0;
}
static void tls_channel_uninit(belle_sip_tls_channel_t *obj){
belle_sip_socket_t sock = belle_sip_source_get_socket((belle_sip_source_t*)obj);
if (sock!=(belle_sip_socket_t)-1)
tls_channel_close(obj);
ssl_free(&obj->sslctx);
mbedtls_ssl_config_free(&obj->sslconf);
x509_crt_free(&obj->root_ca);
if (obj->cur_debug_msg)
belle_sip_free(obj->cur_debug_msg);
belle_sip_object_unref(obj->verify_ctx);
if (obj->client_cert_chain) belle_sip_object_unref(obj->client_cert_chain);
if (obj->client_cert_key) belle_sip_object_unref(obj->client_cert_key);
}
static int tls_channel_send(belle_sip_channel_t *obj, const void *buf, size_t buflen){
belle_sip_tls_channel_t* channel = (belle_sip_tls_channel_t*)obj;
int err = ssl_write(&channel->sslctx,buf,buflen);
if (err<0){
char tmp[256]={0};
if (err==POLARSSL_ERR_NET_WANT_WRITE) return -BELLESIP_EWOULDBLOCK;
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("Channel [%p]: ssl_write() error [%i]: %s",obj,err,tmp);
}
return err;
}
static int tls_channel_recv(belle_sip_channel_t *obj, void *buf, size_t buflen){
belle_sip_tls_channel_t* channel = (belle_sip_tls_channel_t*)obj;
int err = ssl_read(&channel->sslctx,buf,buflen);
if (err==POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY) return 0;
if (err<0){
char tmp[256]={0};
if (err==POLARSSL_ERR_NET_WANT_READ) return -BELLESIP_EWOULDBLOCK;
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("Channel [%p]: ssl_read() error [%i]: %s",obj, err, tmp);
}
return err;
}
static int tls_channel_connect(belle_sip_channel_t *obj, const struct addrinfo *ai){
int err= stream_channel_connect((belle_sip_stream_channel_t*)obj,ai);
if (err==0){
belle_sip_source_set_notify((belle_sip_source_t *)obj, (belle_sip_source_func_t)tls_process_data);
return 0;
}
return -1;
}
BELLE_SIP_DECLARE_CUSTOM_VPTR_BEGIN(belle_sip_tls_channel_t,belle_sip_stream_channel_t)
BELLE_SIP_DECLARE_CUSTOM_VPTR_END
BELLE_SIP_DECLARE_NO_IMPLEMENTED_INTERFACES(belle_sip_tls_channel_t);
BELLE_SIP_INSTANCIATE_CUSTOM_VPTR_BEGIN(belle_sip_tls_channel_t)
{
{
{
BELLE_SIP_VPTR_INIT(belle_sip_tls_channel_t,belle_sip_stream_channel_t,FALSE),
(belle_sip_object_destroy_t)tls_channel_uninit,
NULL,
NULL
},
"TLS",
1, /*is_reliable*/
tls_channel_connect,
tls_channel_send,
tls_channel_recv,
(void (*)(belle_sip_channel_t*))tls_channel_close
}
}
BELLE_SIP_INSTANCIATE_CUSTOM_VPTR_END
static int tls_channel_handshake(belle_sip_tls_channel_t *channel) {
int ret;
while( channel->sslctx.state != SSL_HANDSHAKE_OVER ) {
if ((ret = ssl_handshake_step( &channel->sslctx ))) {
break;
}
if (channel->sslctx.state == SSL_CLIENT_CERTIFICATE && channel->sslctx.client_auth >0) {
BELLE_SIP_INVOKE_LISTENERS_ARG1_ARG2( channel->base.base.listeners
,belle_sip_channel_listener_t
,on_auth_requested
,&channel->base.base
,NULL/*not set yet*/);
if (channel->client_cert_chain && channel->client_cert_key) {
int err;
char tmp[512]={0};
x509_crt_info(tmp,sizeof(tmp)-1,"",&channel->client_cert_chain->cert);
belle_sip_message("Channel [%p] found client certificate:\n%s",channel,tmp);
/* allows public keys other than RSA */
if ((err = mbedtls_ssl_set_hs_own_cert(&channel->sslctx, &channel->client_cert_chain->cert,
&channel->client_cert_key->key))) {
error_strerror(err,tmp,sizeof(tmp)-1);
belle_sip_error("Channel [%p] cannot ssl_set_own_cert [%s]",channel,tmp);
}
}
}
}
return ret;
}
static int tls_process_handshake(belle_sip_channel_t *obj){
belle_sip_tls_channel_t* channel=(belle_sip_tls_channel_t*)obj;
int err=tls_channel_handshake(channel);
if (err==0){
belle_sip_message("Channel [%p]: SSL handshake finished.",obj);
belle_sip_source_set_timeout((belle_sip_source_t*)obj,-1);
belle_sip_channel_set_ready(obj,(struct sockaddr*)&channel->ss,channel->socklen);
}else if (err==POLARSSL_ERR_NET_WANT_READ || err==POLARSSL_ERR_NET_WANT_WRITE){
belle_sip_message("Channel [%p]: SSL handshake in progress...",obj);
}else{
char tmp[128];
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("Channel [%p]: SSL handshake failed : %s",obj,tmp);
return -1;
}
return 0;
}
static int tls_process_data(belle_sip_channel_t *obj,unsigned int revents){
belle_sip_tls_channel_t* channel=(belle_sip_tls_channel_t*)obj;
if (obj->state == BELLE_SIP_CHANNEL_CONNECTING ) {
if (!channel->socket_connected) {
channel->socklen=sizeof(channel->ss);
if (finalize_stream_connection((belle_sip_stream_channel_t*)obj,revents,(struct sockaddr*)&channel->ss,&channel->socklen)) {
goto process_error;
}
belle_sip_message("Channel [%p]: Connected at TCP level, now doing TLS handshake",obj);
channel->socket_connected=1;
belle_sip_source_set_events((belle_sip_source_t*)channel,BELLE_SIP_EVENT_READ|BELLE_SIP_EVENT_ERROR);
belle_sip_source_set_timeout((belle_sip_source_t*)obj,belle_sip_stack_get_transport_timeout(obj->stack));
if (tls_process_handshake(obj)==-1) goto process_error;
}else{
if (revents & BELLE_SIP_EVENT_READ){
if (tls_process_handshake(obj)==-1) goto process_error;
}else if (revents==BELLE_SIP_EVENT_TIMEOUT){
belle_sip_error("channel [%p]: SSL handshake took too much time.",obj);
goto process_error;
}else{
belle_sip_warning("channeEHHCXCCCl [%p]: unexpected event [%i] during TLS handshake.",obj,revents);
}
}
} else if ( obj->state == BELLE_SIP_CHANNEL_READY) {
return belle_sip_channel_process_data(obj,revents);
} else {
belle_sip_warning("Unexpected event [%i], for channel [%p]",revents,channel);
return BELLE_SIP_STOP;
}
return BELLE_SIP_CONTINUE;
process_error:
belle_sip_error("Cannot connect to [%s://%s:%i]",belle_sip_channel_get_transport_name(obj),obj->peer_name,obj->peer_port);
channel_set_state(obj,BELLE_SIP_CHANNEL_ERROR);
return BELLE_SIP_STOP;
}
static int polarssl_read(void * ctx, unsigned char *buf, size_t len ){
belle_sip_stream_channel_t *super=(belle_sip_stream_channel_t *)ctx;
int ret = stream_channel_recv(super,buf,len);
if (ret<0){
ret=-ret;
if (ret==BELLESIP_EWOULDBLOCK || ret==BELLESIP_EINPROGRESS || ret == EINTR )
return POLARSSL_ERR_NET_WANT_READ;
return POLARSSL_ERR_NET_CONN_RESET;
}
return ret;
}
static int polarssl_write(void * ctx, const unsigned char *buf, size_t len ){
belle_sip_stream_channel_t *super=(belle_sip_stream_channel_t *)ctx;
int ret = stream_channel_send(super, buf, len);
if (ret<0){
ret=-ret;
if (ret==BELLESIP_EWOULDBLOCK || ret==BELLESIP_EINPROGRESS || ret == EINTR )
return POLARSSL_ERR_NET_WANT_WRITE;
return POLARSSL_ERR_NET_CONN_RESET;
}
return ret;
}
static int random_generator(void *ctx, unsigned char *ptr, size_t size){
belle_sip_random_bytes(ptr, size);
return 0;
}
static const char *polarssl_certflags_to_string(char *buf, size_t size, int flags){
int i=0;
memset(buf,0,size);
size--;
if (i<size && (flags & BADCERT_EXPIRED))
i+=snprintf(buf+i,size-i,"expired ");
if (i<size && (flags & BADCERT_REVOKED))
i+=snprintf(buf+i,size-i,"revoked ");
if (i<size && (flags & BADCERT_CN_MISMATCH))
i+=snprintf(buf+i,size-i,"CN-mismatch ");
if (i<size && (flags & BADCERT_NOT_TRUSTED))
i+=snprintf(buf+i,size-i,"not-trusted ");
if (i<size && (flags & BADCERT_MISSING))
i+=snprintf(buf+i,size-i,"missing ");
if (i<size && (flags & BADCRL_NOT_TRUSTED))
i+=snprintf(buf+i,size-i,"crl-not-trusted ");
if (i<size && (flags & BADCRL_EXPIRED))
i+=snprintf(buf+i,size-i,"crl-not-expired ");
return buf;
}
// shim the default PolarSSL certificate handling by adding an external callback
// see "verify_cb_error_cb_t" for the function signature
int belle_sip_tls_set_verify_error_cb(void * callback)
{
if (callback) {
tls_verify_cb_error_cb = (verify_cb_error_cb_t)callback;
belle_sip_message("belle_sip_tls_set_verify_error_cb: callback set");
} else {
tls_verify_cb_error_cb = NULL;
belle_sip_message("belle_sip_tls_set_verify_error_cb: callback cleared");
}
return 0;
}
//
// Augment certificate verification with certificates stored outside rootca.pem
// PolarSSL calls the verify_cb with each cert in the chain; flags apply to the
// current certificate until depth is 0;
//
// NOTES:
// 1) rootca.pem *must* have at least one valid certificate, or PolarSSL
// does not attempt to verify any certificates
// 2) callback must return 0; non-zero indicates that the verification process failed
// 3) flags should be saved off and cleared for each certificate where depth>0
// 4) return final verification result in *flags when depth == 0
// 5) callback must disable calls to linphone_core_iterate while running
//
int belle_sip_verify_cb_error_wrapper(x509_crt *cert, int depth, uint32_t *flags){
int rc = 0;
unsigned char *der = NULL;
// do nothing if the callback is not set
if (!tls_verify_cb_error_cb) {
return 0;
}
belle_sip_message("belle_sip_verify_cb_error_wrapper: depth=[%d], flags=[%u]:\n", depth, (unsigned)*flags);
der = belle_sip_malloc(cert->raw.len + 1);
if (der == NULL) {
// leave the flags alone and just return to the library
belle_sip_error("belle_sip_verify_cb_error_wrapper: memory error\n");
return 0;
}
// copy in and NULL terminate again for safety
memcpy(der, cert->raw.p, cert->raw.len);
der[cert->raw.len] = '\0';
rc = tls_verify_cb_error_cb(der, cert->raw.len, depth, (int*) flags);
belle_sip_message("belle_sip_verify_cb_error_wrapper: callback return rc: %d, flags: %u", rc, (unsigned)*flags);
belle_sip_free(der);
return rc;
}
static int belle_sip_ssl_verify(void *data , x509_crt *cert , int depth, uint32_t *flags){
belle_tls_verify_policy_t *verify_ctx=(belle_tls_verify_policy_t*)data;
char tmp[512];
char flags_str[128];
x509_crt_info(tmp,sizeof(tmp),"",cert);
belle_sip_message("Found certificate depth=[%i], flags=[%s]:\n%s",
depth,polarssl_certflags_to_string(flags_str,sizeof(flags_str),*flags),tmp);
if (verify_ctx->exception_flags==BELLE_TLS_VERIFY_ANY_REASON){
*flags=0;
}else if (verify_ctx->exception_flags & BELLE_TLS_VERIFY_CN_MISMATCH){
*flags&=~BADCERT_CN_MISMATCH;
}
return belle_sip_verify_cb_error_wrapper(cert, depth, flags);
}
static int belle_sip_tls_channel_load_root_ca(belle_sip_tls_channel_t *obj, const char *path){
struct stat statbuf;
if (stat(path,&statbuf)==0){
if (statbuf.st_mode & S_IFDIR){
if (x509_crt_parse_path(&obj->root_ca,path)<0){
belle_sip_error("Failed to load root ca from directory %s",path);
return -1;
}
}else{
if (x509_crt_parse_file(&obj->root_ca,path)<0){
belle_sip_error("Failed to load root ca from file %s",path);
return -1;
}
}
return 0;
}
belle_sip_error("Could not load root ca from %s: %s",path,strerror(errno));
return -1;
}
#ifdef ENABLE_POLARSSL_LOGS
/*
* polarssl does a lot of logs, some with newline, some without.
* We need to concatenate logs without new line until a new line is found.
*/
static void ssl_debug_to_belle_sip(void *context, int level, const char* file, int line, const char *str){
belle_sip_tls_channel_t *chan=(belle_sip_tls_channel_t*)context;
int len=strlen(str);
if (len>0 && (str[len-1]=='\n' || str[len-1]=='\r')){
/*eliminate the newline*/
char *tmp=belle_sip_strdup(str);
tmp[len-1]=0;
if (chan->cur_debug_msg){
belle_sip_message("ssl: %s%s",chan->cur_debug_msg,tmp);
belle_sip_free(chan->cur_debug_msg);
chan->cur_debug_msg=NULL;
}else belle_sip_message("ssl: %s",tmp);
belle_sip_free(tmp);
}else{
if (chan->cur_debug_msg){
char *tmp=belle_sip_strdup_printf("%s%s",chan->cur_debug_msg,str);
belle_sip_free(chan->cur_debug_msg);
chan->cur_debug_msg=tmp;
}else chan->cur_debug_msg=belle_sip_strdup(str);
}
}
#endif
belle_sip_channel_t * belle_sip_channel_new_tls(belle_sip_stack_t *stack, belle_tls_verify_policy_t *verify_ctx,const char *bindip, int localport, const char *peer_cname, const char *dest, int port){
belle_sip_tls_channel_t *obj=belle_sip_object_new(belle_sip_tls_channel_t);
belle_sip_stream_channel_t* super=(belle_sip_stream_channel_t*)obj;
belle_sip_stream_channel_init_client(super
,stack
,bindip,localport,peer_cname,dest,port);
mbedtls_ssl_config_init(&obj->sslconf);
mbedtls_ssl_config_defaults(&obj->sslconf, MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT);
#ifdef ENABLE_POLARSSL_LOGS
mbedtls_ssl_conf_dbg(&obj->sslconf, ssl_debug_to_belle_sip, obj);
mbedtls_debug_set_threshold(2);
#endif
mbedtls_ssl_conf_authmode(&obj->sslconf, MBEDTLS_SSL_VERIFY_REQUIRED);
if (verify_ctx->root_ca && belle_sip_tls_channel_load_root_ca(obj, verify_ctx->root_ca) == 0) {
mbedtls_ssl_conf_ca_chain(&obj->sslconf, &obj->root_ca, NULL);
}
mbedtls_ssl_conf_rng(&obj->sslconf, random_generator, NULL);
mbedtls_ssl_conf_verify(&obj->sslconf, belle_sip_ssl_verify, verify_ctx);
mbedtls_ssl_init(&obj->sslctx);
mbedtls_ssl_setup(&obj->sslctx, &obj->sslconf);
mbedtls_ssl_set_bio(&obj->sslctx, obj, polarssl_write, polarssl_read, NULL);
mbedtls_ssl_set_hostname(&obj->sslctx, super->base.peer_cname ? super->base.peer_cname : super->base.peer_name);
obj->verify_ctx = (belle_tls_verify_policy_t *)belle_sip_object_ref(verify_ctx);
return (belle_sip_channel_t *)obj;
}
void belle_sip_tls_channel_set_client_certificates_chain(belle_sip_tls_channel_t *channel, belle_sip_certificates_chain_t* cert_chain) {
SET_OBJECT_PROPERTY(channel,client_cert_chain,cert_chain);
}
void belle_sip_tls_channel_set_client_certificate_key(belle_sip_tls_channel_t *channel, belle_sip_signing_key_t* key){
SET_OBJECT_PROPERTY(channel,client_cert_key,key);
}
/**************************** belle_sip_certificates_chain_t **/
// Duplicates the given buffer with one extra null character
// This ensures the returned buffer is always null terminated
// This is nessesary for some mbedtls functions which now require a null
// terminated buffer to be provided.
static char *extend_buffer(const char *buff, size_t size) {
char *result = belle_sip_malloc(size + 1);
memcpy(result, buff, size);
result[size] = '\0';
return result;
}
static int belle_sip_certificate_fill(belle_sip_certificates_chain_t* certificate,const char* buff, size_t size,belle_sip_certificate_raw_format_t format) {
int err;
unsigned char *extended_buff = (unsigned char *)extend_buffer(buff, size);
err = mbedtls_x509_crt_parse(&certificate->cert, extended_buff, size + 1);
belle_sip_free(extended_buff);
if (err < 0) {
char tmp[128];
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("cannot parse x509 cert because [%s]",tmp);
return -1;
}
return 0;
}
static int belle_sip_certificate_fill_from_file(belle_sip_certificates_chain_t* certificate,const char* path,belle_sip_certificate_raw_format_t format) {
int err;
if ((err=x509_crt_parse_file(&certificate->cert, path)) <0) {
char tmp[128];
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("cannot parse x509 cert because [%s]",tmp);
return -1;
}
return 0;
}
/*belle_sip_certificate */
belle_sip_certificates_chain_t* belle_sip_certificates_chain_parse(const char* buff, size_t size,belle_sip_certificate_raw_format_t format) {
belle_sip_certificates_chain_t* certificate = belle_sip_object_new(belle_sip_certificates_chain_t);
if (belle_sip_certificate_fill(certificate,buff, size,format)) {
belle_sip_object_unref(certificate);
certificate=NULL;
}
return certificate;
}
belle_sip_certificates_chain_t* belle_sip_certificates_chain_parse_file(const char* path, belle_sip_certificate_raw_format_t format) {
belle_sip_certificates_chain_t* certificate = belle_sip_object_new(belle_sip_certificates_chain_t);
if (belle_sip_certificate_fill_from_file(certificate, path, format)) {
belle_sip_object_unref(certificate);
certificate=NULL;
}
return certificate;
}
/*
* Parse all *.pem files in a given dir(non recursively) and return the one matching the given subject
*/
int belle_sip_get_certificate_and_pkey_in_dir(const char *path, const char *subject, belle_sip_certificates_chain_t **certificate, belle_sip_signing_key_t **pkey, belle_sip_certificate_raw_format_t format) {
/* get all *.pem file from given path */
belle_sip_list_t *file_list = belle_sip_parse_directory(path, ".pem");
char *filename = NULL;
file_list = belle_sip_list_pop_front(file_list, (void **)&filename);
while (filename != NULL) {
belle_sip_certificates_chain_t *found_certificate = belle_sip_certificates_chain_parse_file(filename, format);
if (found_certificate != NULL) { /* there is a certificate in this file */
char *subject_CNAME_begin, *subject_CNAME_end;
belle_sip_signing_key_t *found_key;
char name[500];
memset( name, 0, sizeof(name) );
x509_dn_gets( name, sizeof(name), &(found_certificate->cert.subject)); /* this function is available only in polarssl version >=1.3 */
/* parse subject to find the CN=xxx, field. There may be no , at the and but a \0 */
subject_CNAME_begin = strstr(name, "CN=");
if (subject_CNAME_begin!=NULL) {
subject_CNAME_begin+=3;
subject_CNAME_end = strstr(subject_CNAME_begin, ",");
if (subject_CNAME_end != NULL) {
*subject_CNAME_end = '\0';
}
if (strcmp(subject_CNAME_begin, subject)==0) { /* subject CNAME match the one we are looking for*/
/* do we have a key too ? */
found_key = belle_sip_signing_key_parse_file(filename, NULL);
if (found_key!=NULL) {
*certificate = found_certificate;
*pkey = found_key;
belle_sip_free(filename);
belle_sip_list_free_with_data(file_list, belle_sip_free); /* free possible rest of list */
return 0;
}
}
}
}
belle_sip_free(filename);
file_list = belle_sip_list_pop_front(file_list, (void **)&filename);
}
return -1;
}
int belle_sip_generate_self_signed_certificate(const char* path, const char *subject, belle_sip_certificates_chain_t **certificate, belle_sip_signing_key_t **pkey) {
entropy_context entropy;
ctr_drbg_context ctr_drbg;
int ret;
mpi serial;
x509write_cert crt;
FILE *fd;
char file_buffer[8192];
size_t file_buffer_len = 0;
char *name_with_path;
int path_length;
char formatted_subject[512];
/* subject may be a sip URL or linphone-dtls-default-identity, add CN= before it to make a valid name */
memcpy(formatted_subject, "CN=", 3);
memcpy(formatted_subject+3, subject, strlen(subject)+1); /* +1 to get the \0 termination */
/* allocate certificate and key */
*pkey = belle_sip_object_new(belle_sip_signing_key_t);
*certificate = belle_sip_object_new(belle_sip_certificates_chain_t);
entropy_init( &entropy );
mbedtls_ctr_drbg_init(&ctr_drbg);
if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0)) != 0) {
belle_sip_error("Certificate generation can't init ctr_drbg: -%x", -ret);
return -1;
}
/* generate 3072 bits RSA public/private key */
pk_init( &((*pkey)->key) );
if ( (ret = pk_init_ctx( &((*pkey)->key), pk_info_from_type( POLARSSL_PK_RSA ) )) != 0) {
belle_sip_error("Certificate generation can't init pk_ctx: -%x", -ret);
return -1;
}
if ( ( ret = rsa_gen_key( pk_rsa( (*pkey)->key ), ctr_drbg_random, &ctr_drbg, 3072, 65537 ) ) != 0) {
belle_sip_error("Certificate generation can't generate rsa key: -%x", -ret);
return -1;
}
/* if there is no path, don't write a file */
if (path!=NULL) {
pk_write_key_pem( &((*pkey)->key), (unsigned char *)file_buffer, 4096);
file_buffer_len = strlen(file_buffer);
}
/* generate the certificate */
x509write_crt_init( &crt );
x509write_crt_set_md_alg( &crt, POLARSSL_MD_SHA256 );
mpi_init( &serial );
if ( (ret = mpi_read_string( &serial, 10, "1" ) ) != 0 ) {
belle_sip_error("Certificate generation can't read serial mpi: -%x", -ret);
return -1;
}
x509write_crt_set_subject_key( &crt, &((*pkey)->key) );
x509write_crt_set_issuer_key( &crt, &((*pkey)->key) );
if ( (ret = x509write_crt_set_subject_name( &crt, formatted_subject) ) != 0) {
belle_sip_error("Certificate generation can't set subject name: -%x", -ret);
return -1;
}
if ( (ret = x509write_crt_set_issuer_name( &crt, formatted_subject) ) != 0) {
belle_sip_error("Certificate generation can't set issuer name: -%x", -ret);
return -1;
}
if ( (ret = x509write_crt_set_serial( &crt, &serial ) ) != 0) {
belle_sip_error("Certificate generation can't set serial: -%x", -ret);
return -1;
}
mpi_free(&serial);
if ( (ret = x509write_crt_set_validity( &crt, "20010101000000", "20300101000000" ) ) != 0) {
belle_sip_error("Certificate generation can't set validity: -%x", -ret);
return -1;
}
/* store anyway certificate in pem format in a string even if we do not have file to write as we need it to get it in a x509_crt structure */
if ( (ret = x509write_crt_pem( &crt, (unsigned char *)file_buffer+file_buffer_len, 4096, ctr_drbg_random, &ctr_drbg ) ) != 0) {
belle_sip_error("Certificate generation can't write crt pem: -%x", -ret);
return -1;
}
x509write_crt_free(&crt);
// mbedtls 2.0 requires the buffer to contain the terminating NULL byte
if ((ret = mbedtls_x509_crt_parse(&((*certificate)->cert), (unsigned char *)file_buffer, strlen(file_buffer) + 1)) != 0) {
belle_sip_error("Certificate generation can't parse crt pem: -%x", -ret);
return -1;
}
/* write the file if needed */
if (path!=NULL) {
name_with_path = (char *)belle_sip_malloc(strlen(path)+257); /* max filename is 256 bytes in dirent structure, +1 for / */
path_length = strlen(path);
memcpy(name_with_path, path, path_length);
name_with_path[path_length] = '/';
path_length++;
memcpy(name_with_path+path_length, subject, strlen(subject));
memcpy(name_with_path+path_length+strlen(subject), ".pem", 5);
/* check if directory exists and if not, create it */
belle_sip_mkdir(path);
if ( (fd = fopen(name_with_path, "w") ) == NULL) {
belle_sip_error("Certificate generation can't open/create file %s", name_with_path);
free(name_with_path);
belle_sip_object_unref(*pkey);
belle_sip_object_unref(*certificate);
*pkey = NULL;
*certificate = NULL;
return -1;
}
if ( fwrite(file_buffer, 1, strlen(file_buffer), fd) != strlen(file_buffer) ) {
belle_sip_error("Certificate generation can't write into file %s", name_with_path);
fclose(fd);
belle_sip_object_unref(*pkey);
belle_sip_object_unref(*certificate);
*pkey = NULL;
*certificate = NULL;
free(name_with_path);
return -1;
}
fclose(fd);
free(name_with_path);
}
return 0;
}
/* Note : this code is duplicated in mediastreamer2/src/voip/dtls_srtp.c but get directly a x509_crt as input parameter */
char *belle_sip_certificates_chain_get_fingerprint(belle_sip_certificates_chain_t *certificate) {
unsigned char buffer[64]={0}; /* buffer is max length of returned hash, which is 64 in case we use sha-512 */
size_t hash_length = 0;
const char *hash_alg_string=NULL;
char *fingerprint = NULL;
x509_crt *crt;
if (certificate == NULL) return NULL;
crt = &certificate->cert;
/* fingerprint is a hash of the DER formated certificate (found in crt->raw.p) using the same hash function used by certificate signature */
switch (crt->sig_md) {
case POLARSSL_MD_SHA1:
sha1(crt->raw.p, crt->raw.len, buffer);
hash_length = 20;
hash_alg_string="SHA-1";
break;
case POLARSSL_MD_SHA224:
sha256(crt->raw.p, crt->raw.len, buffer, 1); /* last argument is a boolean, indicate to output sha-224 and not sha-256 */
hash_length = 28;
hash_alg_string="SHA-224";
break;
case POLARSSL_MD_SHA256:
sha256(crt->raw.p, crt->raw.len, buffer, 0);
hash_length = 32;
hash_alg_string="SHA-256";
break;
case POLARSSL_MD_SHA384:
sha512(crt->raw.p, crt->raw.len, buffer, 1); /* last argument is a boolean, indicate to output sha-384 and not sha-512 */
hash_length = 48;
hash_alg_string="SHA-384";
break;
case POLARSSL_MD_SHA512:
sha512(crt->raw.p, crt->raw.len, buffer, 1); /* last argument is a boolean, indicate to output sha-384 and not sha-512 */
hash_length = 64;
hash_alg_string="SHA-512";
break;
default:
return NULL;
break;
}
if (hash_length>0) {
int i;
int fingerprint_index = strlen(hash_alg_string);
size_t size=fingerprint_index+3*hash_length+1;
char prefix=' ';
/* fingerprint will be : hash_alg_string+' '+HEX : separated values: length is strlen(hash_alg_string)+3*hash_lenght + 1 for null termination */
fingerprint = belle_sip_malloc0(size);
snprintf(fingerprint, size, "%s", hash_alg_string);
for (i=0; i<hash_length; i++, fingerprint_index+=3) {
snprintf((char*)fingerprint+fingerprint_index, size-fingerprint_index, "%c%02X", prefix,buffer[i]);
prefix=':';
}
*(fingerprint+fingerprint_index) = '\0';
}
return fingerprint;
}
static void belle_sip_certificates_chain_destroy(belle_sip_certificates_chain_t *certificate){
x509_crt_free(&certificate->cert);
}
static void belle_sip_certificates_chain_clone(belle_sip_certificates_chain_t *certificate, const belle_sip_certificates_chain_t *orig){
belle_sip_error("belle_sip_certificate_clone not supported");
}
BELLE_SIP_DECLARE_NO_IMPLEMENTED_INTERFACES(belle_sip_certificates_chain_t);
BELLE_SIP_INSTANCIATE_VPTR(belle_sip_certificates_chain_t,belle_sip_object_t,belle_sip_certificates_chain_destroy,belle_sip_certificates_chain_clone,NULL,TRUE);
belle_sip_signing_key_t* belle_sip_signing_key_parse(const char* buff, size_t size,const char* passwd) {
belle_sip_signing_key_t* signing_key = belle_sip_object_new(belle_sip_signing_key_t);
int err;
unsigned char *extended_buff = (unsigned char *)extend_buffer(buff, size);
pk_init(&signing_key->key);
err = mbedtls_pk_parse_key(&signing_key->key, extended_buff, size + 1,
(const unsigned char *)passwd ,passwd ? strlen(passwd) : 0);
belle_sip_free(extended_buff);
/* make sure cipher is RSA to be consistent with API v1.2 */
if(err==0 && !pk_can_do(&signing_key->key,POLARSSL_PK_RSA))
err=POLARSSL_ERR_PK_TYPE_MISMATCH;
if (err<0) {
char tmp[128];
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("cannot parse public key because [%s]",tmp);
pk_free(&signing_key->key);
belle_sip_object_unref(signing_key);
return NULL;
}
return signing_key;
}
belle_sip_signing_key_t* belle_sip_signing_key_parse_file(const char* path,const char* passwd) {
belle_sip_signing_key_t* signing_key = belle_sip_object_new(belle_sip_signing_key_t);
int err;
pk_init(&signing_key->key);
/* for API v1.3 or greater also parses public keys other than RSA */
err=pk_parse_keyfile(&signing_key->key,path, passwd);
/* make sure cipher is RSA to be consistent with API v1.2 */
if(err==0 && !pk_can_do(&signing_key->key,POLARSSL_PK_RSA))
err=POLARSSL_ERR_PK_TYPE_MISMATCH;
if (err<0) {
char tmp[128];
error_strerror(err,tmp,sizeof(tmp));
belle_sip_error("cannot parse public key because [%s]",tmp);
pk_free(&signing_key->key);
belle_sip_object_unref(signing_key);
return NULL;
}
return signing_key;
}
static void belle_sip_signing_key_destroy(belle_sip_signing_key_t *signing_key){
pk_free(&signing_key->key);
}
static void belle_sip_signing_key_clone(belle_sip_signing_key_t *signing_key, const belle_sip_signing_key_t *orig){
belle_sip_error("belle_sip_signing_key_clone not supported");
}
BELLE_SIP_DECLARE_NO_IMPLEMENTED_INTERFACES(belle_sip_signing_key_t);
BELLE_SIP_INSTANCIATE_VPTR(belle_sip_signing_key_t,belle_sip_object_t,belle_sip_signing_key_destroy,belle_sip_signing_key_clone,NULL,TRUE);
|