41 #define NCBI_USE_ERRCODE_X Connect_TLS
44 #if defined(HAVE_LIBMBEDTLS) || defined(NCBI_CXX_TOOLKIT)
55 # ifdef MBEDTLS_PSA_CRYPTO_C
60 # define NCBI_NOTSUPPORTED ENOTSUP
61 # elif defined(ENOSYS)
62 # define NCBI_NOTSUPPORTED ENOSYS
64 # define NCBI_NOTSUPPORTED EINVAL
69 # define mbedtls_x509_crt void
70 # define mbedtls_pk_context void
81 #if defined(HAVE_LIBMBEDTLS) || defined(NCBI_CXX_TOOLKIT)
83 # if defined(MBEDTLS_THREADING_ALT) && defined(NCBI_THREADS)
84 # ifdef MBEDTLS_THREADING_PTHREAD
85 # error "MBEDTLS_THREADING_ALT and MBEDTLS_THREADING_PTHREAD conflict"
87 static void mbtls_user_mutex_init(
MT_LOCK* lock)
91 static void mbtls_user_mutex_deinit(
MT_LOCK* lock)
102 static int mbtls_user_mutex_lock(
MT_LOCK* lock)
107 #ifdef MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE
108 return MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE;
122 static int mbtls_user_mutex_unlock(
MT_LOCK* lock)
127 #ifdef MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE
128 return MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE;
163 const char*
file,
int line,
164 const char* message);
166 static int x_MbedTlsPush (
void*,
const unsigned char*,
size_t);
183 const char*
file,
int line,
187 size_t len = message ? strlen(message) : 0;
188 if (!
len || *message ==
'\n')
190 if (message[
len - 1] ==
'\n')
193 (
"MBEDTLS%d: %.*s", level, (
int)
len, message));
206 status = r_status != eIO_Closed && w_status != eIO_Closed
207 ? r_status > w_status ? r_status : w_status
228 #if MBEDTLS_VERSION_MAJOR >= 3
243 #ifdef MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE
244 case MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE:
246 #ifdef MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE
247 case MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE:
251 #ifdef MBEDTLS_ERR_SSL_UNKNOWN_CIPHER
252 case MBEDTLS_ERR_SSL_UNKNOWN_CIPHER:
255 #ifdef MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED
296 CORE_TRACEF((
"MBEDTLS error %d -> CONNECT MBEDTLS status %s",
339 error ?
"error" :
"errno", x_err));
346 else if (!(
error = errno))
378 "Server-side SSL not yet supported with MBEDTLS");
388 (
"%s credentials in MBEDTLS session",
411 (session, xcred->
cert, xcred->
pkey)) != 0)) {
423 CORE_TRACEF((
"MbedTlsCreate(): Leave(%p)", session));
432 size_t alpn_len = alpn ? strlen(alpn) : 0;
434 size_t sslv_len = sslv ? strlen(sslv) : 0;
436 size_t ciph_len = ciph ? strlen(ciph) : 0;
437 size_t len = alpn_len + sslv_len + ciph_len;
443 memcpy(
str, alpn, alpn_len);
449 memcpy(
str +
len, sslv, sslv_len);
455 memcpy(
str +
len, ciph, ciph_len);
488 CORE_TRACEF((
"MbedTlsOpen(%p): Leave(%d)", session, status));
533 size_t x_written = 0;
542 n_written += (
ssize_t) x_written;
547 return (
int) n_written;
557 size_t* n_done,
int*
error)
566 (
unsigned char*)
buf, n_todo);
567 assert(x_read < 0 || (
size_t) x_read <= n_todo);
579 *n_done = (size_t) x_read;
585 size_t n_todo,
size_t* n_done,
int*
error)
591 (
const unsigned char*)
data, n_todo);
592 assert(x_written < 0 || (
size_t) x_written <= n_todo);
594 if (x_written <= 0) {
604 *n_done = (size_t) x_written;
610 size_t n_todo,
size_t* n_done,
int*
error)
621 size_t x_todo = n_todo > max_size ? max_size : n_todo;
630 if (x_todo != x_done)
660 CORE_TRACEF((
"MbedTlsClose(%p): Leave(%d)", session, status));
671 CORE_TRACEF((
"MbedTlsDelete(%p): Enter", session));
676 CORE_TRACEF((
"MbedTlsDelete(%p): Leave", session));
699 # ifdef MBEDTLS_THREADING_PTHREAD
701 # elif defined(MBEDTLS_THREADING_ALT) && defined(NCBI_THREADS)
706 mbtls_user_mutex_deinit,
707 mbtls_user_mutex_lock,
708 mbtls_user_mutex_unlock);
713 # elif !defined(NCBI_NO_THREADS) && defined(_MT)
715 "MBEDTLS locking uninited: Unknown threading model");
733 #ifdef MBEDTLS_PSA_CRYPTO_C
742 # if defined(MBEDTLS_THREADING_ALT) && defined(NCBI_THREADS)
751 static const char kMbedTls[] =
752 # ifdef HAVE_LIBMBEDTLS
758 #ifdef MBEDTLS_PSA_CRYPTO_C
771 (
"%s version mismatch: %s headers vs. %s runtime",
776 if (!pull || !
push) {
787 #if MBEDTLS_VERSION_NUMBER == 0x03060000
837 #ifdef MBEDTLS_PSA_CRYPTO_C
844 "Platform Security Architecture (PSA) failed to initialize");
899 #if defined(HAVE_LIBMBEDTLS) || defined(NCBI_CXX_TOOLKIT)
910 #if !defined(HAVE_LIBMBEDTLS) && !defined(NCBI_CXX_TOOLKIT)
917 #define ALIGN2(s, a) ((((s) + ((a) - 1)) / (a)) * (a))
918 #define ALIGN(s) ALIGN2(s, sizeof(double))
926 if (xcert && xpkey) {
928 size +=
sizeof(*xcred);
933 if (xcert && xpkey) {
935 ((
char*) cred + 2*
ALIGN(
sizeof(*cred)));
945 #if defined(HAVE_LIBMBEDTLS) || defined(NCBI_CXX_TOOLKIT)
953 memset(xcred, 0,
sizeof(*xcred));
956 switch (cred->
type / 100) {
958 strcpy(who,
"GNUTLS");
961 strcpy(who,
"MBEDTLS");
964 sprintf(who,
"TLS 0x%08X", cred->
type);
968 (
"Deleting unknown certificate credentials (%s/%u)",
969 who, cred->
type % 100));
985 const size_t size = (2*
ALIGN(
sizeof(*ncbi_cred))
986 +
ALIGN(
sizeof(*xcred))
988 +
sizeof(*xcred->
pkey));
995 (
"Cannot allocate NCBI_CRED (%lu bytes)",
996 (
unsigned long)
size));
1001 ((
char*) ncbi_cred + 2*
ALIGN(
sizeof(*ncbi_cred)));
1003 ((
char*) xcred +
ALIGN(
sizeof(*xcred)));
1007 ncbi_cred->
data = xcred;
1014 (
const unsigned char*)
cert, certsz ? certsz
1015 : strlen((
const char*)
cert) + 1);
1019 "mbedTLS cannot parse X.509 certificate");
1025 err > 0 ?
":\n" :
"",
1026 err > 0 ?
tmp :
""));
1029 (
const unsigned char*)
pkey, pkeysz ? pkeysz
1030 : strlen((
const char*)
pkey) + 1, 0, 0
1038 "mbedTLS cannot parse private key");
#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
The selected feature is not available.
Platform Security Architecture cryptography module.
This file contains definitions and functions for the CTR_DRBG pseudorandom generator.
void mbedtls_ctr_drbg_free(mbedtls_ctr_drbg_context *ctx)
This function resets CTR_DRBG context to the state immediately after initial call of mbedtls_ctr_drbg...
void mbedtls_ctr_drbg_init(mbedtls_ctr_drbg_context *ctx)
This function initializes the CTR_DRBG context, and prepares it for mbedtls_ctr_drbg_seed() or mbedtl...
int mbedtls_ctr_drbg_seed(mbedtls_ctr_drbg_context *ctx, int(*f_entropy)(void *, unsigned char *, size_t), void *p_entropy, const unsigned char *custom, size_t len)
This function seeds and sets up the CTR_DRBG entropy source for future reseeds.
int mbedtls_ctr_drbg_random(void *p_rng, unsigned char *output, size_t output_len)
This function uses CTR_DRBG to generate random data.
Functions for controlling and providing debug output from the library.
void mbedtls_debug_set_threshold(int threshold)
Set the threshold error level to handle globally all debug output.
Entropy accumulator implementation.
void mbedtls_entropy_free(mbedtls_entropy_context *ctx)
Free the data in the context.
int mbedtls_entropy_func(void *data, unsigned char *output, size_t len)
Retrieve entropy from the accumulator (Maximum length: MBEDTLS_ENTROPY_BLOCK_SIZE) (Thread-safe if MB...
void mbedtls_entropy_init(mbedtls_entropy_context *ctx)
Initialize the context.
std::ofstream out("events_result.xml")
main entry point for tests
static const char * str(char *buf, int n)
SOCKSSL NcbiSetupMbedTls(void)
Explicitly setup mbedTLS library to support SSL in ncbi_socket.h[pp].
#define DEF_CONN_TLS_LOGLEVEL
struct SNcbiCred * NCBI_CRED
Opaque type for credentials.
#define REG_CONN_TLS_LOGLEVEL
EIO_Status SOCK_Status(SOCK sock, EIO_Event direction)
Return low-level socket I/O status of *last* socket operation.
ESOCK_Side
Sides of socket.
NCBI_CRED NcbiCredMbedTls(void *xcert, void *xpkey)
Convert native mbedTLS certificate credentials' handles into an abstract toolkit handle.
MT_LOCK CORE_GetLOCK(void)
Get the lock handle that is to be used by the core internals.
ELOG_Level
Log severity level.
MT_LOCK MT_LOCK_AddRef(MT_LOCK lk)
Increment internal reference count by 1, then return "lk".
const char * IO_StatusStr(EIO_Status status)
Get the text form of an enum status value.
MT_LOCK MT_LOCK_Delete(MT_LOCK lk)
Decrement internal reference count by 1, and if it reaches 0, then destroy the handle,...
EIO_Event
I/O event (or direction).
#define MT_LOCK_Do(lk, how)
Call "lk->handler(lk->data, how)".
@ eMT_Unlock
unlock critical section
@ eMT_Lock
lock critical section
@ eIO_Timeout
timeout expired before any I/O succeeded
@ eIO_Interrupt
signal arrival prevented any I/O to succeed
@ eIO_NotSupported
operation is not supported or is not available
@ eIO_Success
everything is fine, no error occurred
@ eIO_Unknown
unknown I/O error (likely fatal but can retry)
@ eIO_InvalidArg
bad argument / parameter value(s) supplied
@ eIO_Open
also serves as no-event indicator in SOCK_Poll
int32_t psa_status_t
Function return status.
#define PSA_SUCCESS
The action was completed successfully.
psa_status_t psa_crypto_init(void)
Library initialization.
static const CS_INT unused
#define MBEDTLS_VERSION_STRING
#define MBEDTLS_VERSION_MAJOR
The version number x.y.z is split into three parts.
const string version
version string
const struct ncbi::grid::netcache::search::fields::SIZE size
EIO_Status(* FSSLPush)(SOCK sock, const void *data, size_t size, size_t *done, int logdata)
EIO_Status(* FSSLPull)(SOCK sock, void *buf, size_t size, size_t *done, int logdata)
const char * ConnNetInfo_GetValueInternal(const char *service, const char *param, char *value, size_t value_size, const char *def_value)
static int x_StatusToError(EIO_Status status, SOCK sock, EIO_Event direction)
void NcbiDeleteMbedTlsCertCredentials(NCBI_CRED cred)
static void s_MbedTlsExit(void)
static EIO_Status s_MbedTlsOpen(void *session, int *error, char **desc)
NCBI_CRED NcbiCreateMbedTlsCertCredentials(const void *cert, size_t certsz, const void *pkey, size_t pkeysz)
static char * x_MbedTlsDesc(const mbedtls_ssl_context *session)
static EIO_Status x_MbedTlsWrite(void *session, const void *data, size_t n_todo, size_t *n_done, int *error)
static EIO_Status s_MbedTlsRead(void *session, void *buf, size_t size, size_t *done, int *error)
static int x_MbedTlsPull(void *, unsigned char *, size_t)
static volatile int s_MbedTlsLogLevel
static volatile FSSLPull s_Pull
static EIO_Status s_MbedTlsInit(FSSLPull pull, FSSLPush push)
static mbedtls_ssl_config s_MbedTlsConf
static EIO_Status s_MbedTlsClose(void *session, int how, int *error)
#define NCBI_NOTSUPPORTED
static mbedtls_entropy_context s_MbedTlsEntropy
static EIO_Status x_RetryStatus(SOCK sock, EIO_Event direction)
static const char * s_MbedTlsError(void *session, int error, char *buf, size_t size)
static int x_IfToLog(void)
static void s_MbedTlsDelete(void *session)
static volatile FSSLPush s_Push
static void x_MbedTlsExit(int nopsa)
static EIO_Status x_InitLocking(void)
static EIO_Status x_ErrorToStatus(int error, mbedtls_ssl_context *session, EIO_Event direction)
static EIO_Status s_MbedTlsWrite(void *session, const void *data, size_t size, size_t *done, int *error)
static void x_MbedTlsLogger(void *data, int level, const char *file, int line, const char *message)
static int x_MbedTlsPush(void *, const unsigned char *, size_t)
static mbedtls_ctr_drbg_context s_MbedTlsCtrDrbg
static void * s_MbedTlsCreate(ESOCK_Side side, SNcbiSSLctx *ctx, int *error)
#define CORE_DEBUG_ARG(arg)
#define CORE_LOGF_X(subcode, level, fmt_args)
#define CORE_LOG_ERRNO_EXX(subcode, level, error, descr, message)
#define CORE_LOGF_ERRNO_X(subcode, level, error, fmt_args)
#define CORE_TRACEF(fmt_args)
#define CORE_TRACE(message)
#define CORE_LOG_X(subcode, level, message)
#define mbedtls_version_get_string
#define mbedtls_pk_parse_key
#define mbedtls_ssl_set_hostname
#define psa_generic_status_to_mbedtls
#define mbedtls_x509_crt_init
#define mbedtls_version_check_feature
#define mbedtls_ssl_get_alpn_protocol
#define mbedtls_x509_crt_free
#define mbedtls_x509_crt_parse
#define mbedtls_x509_crt_info
#define mbedtls_ssl_set_hs_own_cert
#define mbedtls_threading_set_alt
#define mbedtls_threading_free_alt
Network sockets abstraction layer to integrate Mbed TLS into a BSD-style sockets API.
#define MBEDTLS_ERR_NET_RECV_FAILED
Reading information from the socket failed.
#define MBEDTLS_ERR_NET_CONN_RESET
Connection was reset by peer.
#define MBEDTLS_ERR_NET_SEND_FAILED
Sending information through the socket failed.
Public Key abstraction layer.
const char * mbedtls_pk_get_name(const mbedtls_pk_context *ctx)
Access the type name.
void mbedtls_pk_init(mbedtls_pk_context *ctx)
Initialize a mbedtls_pk_context (as NONE).
void mbedtls_pk_free(mbedtls_pk_context *ctx)
Free the components of a mbedtls_pk_context.
Error to string translation.
#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED
The requested feature is not supported by the platform.
void mbedtls_strerror(int errnum, char *buffer, size_t buflen)
Translate an Mbed TLS error code into a string representation.
Run-time version information.
#define MBEDTLS_ERR_SSL_NON_FATAL
The alert message received indicates a non-fatal error.
const char * mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context *ssl)
Return the name of the current ciphersuite.
#define MBEDTLS_SSL_VERIFY_NONE
const char * mbedtls_ssl_get_version(const mbedtls_ssl_context *ssl)
Return the current TLS version.
#define MBEDTLS_SSL_IS_CLIENT
void mbedtls_ssl_free(mbedtls_ssl_context *ssl)
Free referenced items in an SSL context and clear memory.
#define MBEDTLS_ERR_SSL_TIMEOUT
The operation timed out.
@ MBEDTLS_SSL_VERSION_TLS1_2
void mbedtls_ssl_conf_rng(mbedtls_ssl_config *conf, int(*f_rng)(void *, unsigned char *, size_t), void *p_rng)
Set the random number generator callback.
int mbedtls_ssl_handshake(mbedtls_ssl_context *ssl)
Perform the SSL handshake.
void mbedtls_ssl_conf_authmode(mbedtls_ssl_config *conf, int authmode)
Set the certificate verification mode Default: NONE on server, REQUIRED on client.
int mbedtls_ssl_get_max_out_record_payload(const mbedtls_ssl_context *ssl)
Return the current maximum outgoing record payload in bytes.
int mbedtls_ssl_write(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len)
Try to write exactly 'len' application data bytes.
#define MBEDTLS_ERR_SSL_BAD_INPUT_DATA
Bad input parameters to function.
#define MBEDTLS_ERR_SSL_WANT_WRITE
Connection requires a write call.
#define MBEDTLS_ERR_SSL_WANT_READ
No data of requested type currently available on underlying transport.
#define MBEDTLS_SSL_IS_SERVER
void mbedtls_ssl_config_free(mbedtls_ssl_config *conf)
Free an SSL configuration context.
void mbedtls_ssl_init(mbedtls_ssl_context *ssl)
Initialize an SSL context Just makes the context ready for mbedtls_ssl_setup() or mbedtls_ssl_free()
void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl, void *p_bio, mbedtls_ssl_send_t *f_send, mbedtls_ssl_recv_t *f_recv, mbedtls_ssl_recv_timeout_t *f_recv_timeout)
Set the underlying BIO callbacks for write, read and read-with-timeout.
int mbedtls_ssl_config_defaults(mbedtls_ssl_config *conf, int endpoint, int transport, int preset)
Load reasonable default SSL configuration values.
int mbedtls_ssl_read(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len)
Read at most 'len' application data bytes.
void mbedtls_ssl_conf_dbg(mbedtls_ssl_config *conf, void(*f_dbg)(void *, int, const char *, int, const char *), void *p_dbg)
Set the debug callback.
#define MBEDTLS_ERR_SSL_CONN_EOF
The connection indicated an EOF.
void mbedtls_ssl_config_init(mbedtls_ssl_config *conf)
Initialize an SSL configuration context Just makes the context ready for mbedtls_ssl_config_defaults(...
static void mbedtls_ssl_conf_max_tls_version(mbedtls_ssl_config *conf, mbedtls_ssl_protocol_version tls_version)
Set the maximum supported version sent from the client side and/or accepted at the server side.
int mbedtls_ssl_close_notify(mbedtls_ssl_context *ssl)
Notify the peer that the connection is being closed.
#define MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY
The peer notified us that the connection is going to be closed.
#define MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE
A fatal alert message was received from our peer.
#define MBEDTLS_SSL_TRANSPORT_STREAM
#define MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE
The requested feature is not available.
#define MBEDTLS_ERR_SSL_INTERNAL_ERROR
Internal error (eg, unexpected failure in lower-level module)
int mbedtls_ssl_setup(mbedtls_ssl_context *ssl, const mbedtls_ssl_config *conf)
Set up an SSL context for use.
#define MBEDTLS_SSL_PRESET_DEFAULT
mbedtls_pk_context * pkey
The CTR_DRBG context structure.
Entropy context structure.
SSL/TLS configuration to be shared between mbedtls_ssl_context structures.
const mbedtls_ssl_config * MBEDTLS_PRIVATE(conf)
Container for an X.509 certificate.
Threading abstraction layer.
#define MBEDTLS_ERR_THREADING_MUTEX_ERROR
Locking / unlocking / free failed with error code.
#define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA
Bad input parameters to function.
voidp calloc(uInt items, uInt size)