Is there a way to encrypt data with tls using OpenSSL but send and receive data with Linux system calls recv and send, not with OpenSSL. Is it possible for OpenSSL not to access network by itself and for it to cypher a data only?
Assistant
OpenSSL's primary function is to provide secure communication over networks, but it can also be used to encrypt and decrypt data without directly handling network operations. In OpenSSL, the library that's associated with encryption/decryption without network operations is commonly the libcrypto library, whereas the part that deals with actual SSL/TLS protocols, including managing network connections, is the libssl library.
However, you're asking if you can perform TLS encryption/decryption manually—that is, with OpenSSL handling the encryption/decryption of data, and the application itself handling the network operations using raw system calls like send and recv. This is indeed possible using what certain versions of OpenSSL refer to as either "BIOs" (Basic I/O abstraction) or the newer "BIO_s_mem" and "BIO_s_socket" in particular.
The process involves separating the encryption layer from the network I/O operation. Here's how the process works in simplified steps:
Create a memory BIO (BIO_s_mem) for reading/writing encrypted data.
Create a socket BIO (BIO_s_socket) if you want to make OpenSSL aware of your socket, but this is optional.
Perform the TLS handshake by manually reading/writing the handshake data from/to the BIO and socket.
Once the handshake is complete, use the memory BIO to encrypt and decrypt the application data.
Send the encrypted data to the network using send and receive encrypted data from the network using recv.
Feed the encrypted data received from the network into the OpenSSL BIO to decrypt it.
Here is a very simplified example. Keep in mind that error checking and appropriate handling of the handshake process would need to be included in a production example:
c
SSL_CTX *ctx;
SSL *ssl;
BIO *bio;
char buf[4096];
int sockfd; // This should be a connected socket.
// Setup OpenSSL
SSL_library_init();
ctx = SSL_CTX_new(TLS_client_method());
ssl = SSL_new(ctx);
// Create a memory BIO for encryption and decryption
bio = BIO_new(BIO_s_mem());
// Set SSL to work with the BIO
SSL_set_bio(ssl, bio, bio);
// Perform the TLS handshake
SSL_connect(ssl);
// At this point you would need to read/write handshake data manually
// Once the handshake is done, you can use the SSL object to encrypt and
// decrypt data using the memory BIO.
while (/* data to send */) {
// Encrypt data with OpenSSL and write to the BIO
int written = SSL_write(ssl, "data", data_len);
// Read encrypted data from the BIO and send via socket
int read_bio = BIO_read(bio, buf, sizeof(buf));
send(sockfd, buf, read_bio, 0);
// Receive encrypted data from the socket
int read_socket = recv(sockfd, buf, sizeof(buf), 0);
// Write encrypted data into the BIO
BIO_write(bio, buf, read_socket);
// Decrypt data with OpenSSL
int read_ssl = SSL_read(ssl, buf, sizeof(buf));
// Now buf contains decrypted data
}
// Clean-up
SSL_free(ssl);
SSL_CTX_free(ctx);
In this example, remember that this is handling the encryption and decryption steps, but the detailed process of the initial handshake and subsequent continuation of the TLS process is complex and needs specific state management that is normally handled by OpenSSL internally. You'll need to handle the proper reading and writing of data to correctly perform the handshake and manage the encrypted connection.
Using OpenSSL in this way requires a good understanding of both the OpenSSL API and the TLS protocol itself. Errors in implementation can lead to insecure connections, so it's usually recommended to use the built-in networking facilities of OpenSSL unless you have a strong reason not to.
User
No, I asked about a way to use a Linux system calls "send" and "recv" I need epoll to handle connections. Is it possible to make tls encryption with OpenSSL but without it's ""BIO" ?
Assistant
Apologies for the confusion. When using epoll along with OpenSSL for handling multiple connections, you might still need to use OpenSSL BIOs for the encryption and decryption process—but you can manage the actual socket IO, including send and recv, using the system calls directly. The BIOs here would not be responsible for the network IO, but instead for buffering the data that OpenSSL needs to process for SSL/TLS operations.
Let's clarify one important aspect: OpenSSL is designed to use BIOs for buffering and abstracting its IO operations, but you can manually manage the socket IO part using the standard system calls (send, recv, epoll_ctl, etc.) and still utilize OpenSSL for the TLS layer.
Here's a high-level outline of how this could work:
Socket Initialization: You create and configure sockets as usual in Linux, setting them to non-blocking mode and registering them with epoll for multiplexing.
SSL Initialization: Set up OpenSSL SSL_CTX and SSL objects as needed for your application for each connection.
Manual Handshaking: You'll handle the reads and writes manually during the SSL handshake phase. Specifically, you will:
Use SSL_do_handshake() to proceed with the handshake.
Check SSL_get_error() when SSL_do_handshake() returns <= 0 to determine if SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE is indicated.
Based on that, use epoll and regular send/recv system calls to read from and write to the socket.
Data Encryption/Decryption: After the handshake is complete, you perform read and write operations as follows:
For sending data, encrypt it using SSL_write(), and then use the send system call to send the underlying raw data.
For receiving data, obtain encrypted data from the network using the recv system call, and then pass this encrypted data to SSL_read() to decrypt it.
The key point is that during the SSL_read() and SSL_write() calls, OpenSSL may not complete its operations (due to non-blocking IO) and may return SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE. When this happens, your code must wait for the appropriate condition (readable or writable) to be signalled by before retrying the operation.
User
Can you give a good example of it with comments when SSL calls is used? It would be highly appreciated if you could give an exhalent example.
Assistant
Certainly! Below is a simplified example that demonstrates using epoll, along with non-blocking socket system calls, send and recv, to manage the TLS handshake and data transmission with OpenSSL. This example focuses primarily on the interaction between OpenSSL and the system calls while skipping other aspects like error handling, certificate setup, and full connection management for the sake of brevity.
Here's a hypothetical setup:
We assume there is an already created non-blocking socket clientfd that you want to connect via SSL.
An epoll instance epollfd is already set up and clientfd has been added with EPOLLIN | EPOLLOUT events.
c
User
Doesn't SSL_write send data to network? Shortly
Assistant
My apologies for any confusion in the previous response. Let's clarify:
SSL_write is an OpenSSL function that encrypts data and writes it to an SSL/TLS buffer. It does not directly send the encrypted data to the network. Instead, the encrypted data is placed into an internal OpenSSL buffer associated with the SSL object. It is then expected that you, as the programmer, will take care of extracting the encrypted data from this buffer and actually sending it over the network using a system call like write or send.
In essence:
You provide SSL_write with plaintext data that you want to send securely.
SSL_write encrypts this data and stores it in an internal buffer.
You then need to retrieve this encrypted data from the OpenSSL buffer and use send to transmit it over the socket.
The confusion may arise because, typically, when an SSL object is associated with a socket BIO (as is usually the case in simpler examples or default usage), calling SSL_write does indeed result in the encrypted data being written out to the network socket. This is because, under the hood, OpenSSL calls the write functionality of the associated BIO which, in the case of a socket BIO, sends the data out over the network.
But when you are manually controlling the network operations with calls to send and recv in the context of using epoll, you would avoid having SSL_write interact directly with the network. Instead, you would use BIO-related calls to get the encrypted data from the SSL object's buffers, and then use send in your own code to send that data over the network.
This decouples the OpenSSL cryptographic process from the network I/O, allowing you to integrate OpenSSL with systems like epoll that expect you to manage the I/O manually.
User
What prevents SSL_write from sending a data? What will happen if I call SSL_write more then ones, the encrypted data will be overwritten or sent or error will occur?
Assistant
In a default configuration using OpenSSL, SSL_write will indeed send data to the network if the SSL object is set up to use a socket BIO. What prevents SSL_write from sending data to a network socket is creating an SSL object that either is not associated with a BIO at all (which is quite unusual and requires careful manual handling), or is associated with a memory BIO, which does not perform network I/O but instead allows you to manage the encrypted data yourself.
In the context of an SSL object that is not configured to directly send data over the network (e.g., using a memory BIO), the following will happen when you call SSL_write:
SSL_write encrypts the data and writes it into a buffer managed by OpenSSL.
If there is enough space in the buffer, the data is added to the buffer for later retrieval and the function returns the number of bytes successfully written.
If there is not enough space in the buffer, SSL_write will write what it can and return the number of bytes written. You will need to retry sending the remaining data later.
When you call SSL_write more than once:
Subsequent calls to SSL_write will encrypt and append the new data to the end of OpenSSL's internal buffer. The data is not overwritten. The buffer expands as needed to accommodate more data (up to any limits set or memory available on the system).
If SSL_write encounters an error (unrelated to the bio buffer space), such as if the SSL session has been shut down or if a serious error occurs with the encryption process, it will return an error code. The SSL_get_error function can be used to get more information about the reason for the error.
The key thing to understand is that OpenSSL maintains an internal buffer for outgoing data when working with non-blocking I/O. You must handle the situation where SSL_write might return the SSL_ERROR_WANT_WRITE result, indicating that although the data is now encrypted and sitting in the buffer, it has not yet been successfully written out to the network, and you need to wait for the socket to be writable again.
To avoid having the SSL_write function directly cause data to be sent out over the network, you use memory BIOs for both the read and write channels. This means you will be responsible for taking the encrypted data from the write BIO and sending it over the socket with system calls, and likewise for passing data received from the network into the read BIO so that it can be properly decrypted with SSL_read.
In all cases, proper error handling and state management are crucial, especially when dealing with non-blocking sockets and event-driven architectures like .
User
How to empty data in the SSL_write buffer? How to set limit for it? Shortly
Assistant
When using SSL_write with OpenSSL, the data you write is buffered internally until it is ready to be sent over the network or retrieved through the appropriate BIOs. Here's how you can manage the buffer:
To empty the SSL_write buffer:
You would typically need to make sure that the buffer is properly flushed through whatever BIO you have associated with the SSL. If you're managing the network IO manually with the send system call instead of allowing OpenSSL to manage it:
After calling SSL_write, use a corresponding BIO method to read the encrypted data from the SSL object's internal write buffer.
Then, use the send call to send this encrypted data over the network.
Here's a brief example snippet to illustrate this:
c
BIO *wbio = SSL_get_wbio(ssl); // Get the write BIO
char buffer[4096];
int bytes;
do {
// Attempt to read encrypted data from the write BIO
bytes = BIO_read(wbio, buffer, sizeof(buffer));
if (bytes > 0) {
// Data is available to be sent over the network
send(sockfd, buffer, bytes, 0);
// Error and partial send check omitted for brevity
}
} while (bytes > 0); // Continue until BIO is empty
To set a limit for the SSL_write buffer:
OpenSSL itself does not provide an API to directly set a limit on the size of the SSL/TLS write buffer. The buffer is designed to hold at least one SSL/TLS record, and typically an SSL/TLS record can be up to 16KB in size, although this may vary depending on protocol version and configuration.
However, you can manage the amount of data being buffered at any given time by controlling the size of data you pass to SSL_write. If you know the size limit you want to apply, you can write data in smaller chunks that don't exceed this limit and make sure you flush the write buffer to the network as described above after each SSL_write call.
If there are concerns about memory usage and a guarantee is needed that OpenSSL internal buffers do not grow beyond a certain size, deeper changes to the OpenSSL library code or using a patched version of OpenSSL may be necessary.
In practice, managing the amount of data passed to SSL_write and timely flushing of data is often sufficient to effectively control the size of OpenSSL's internal buffers during data transmission.
User
how to flush it? I need just encrypt data with SSL_write then get it encrypted and empty the memory BIO of SSL_write. Shortly
Assistant
If you want to use SSL_write to just encrypt data and then directly access that data for manual handling (like sending over the network with send), you would do something like this using a memory BIO:
Create a memory BIO: For sending data, create an output memory BIO and attach it to your SSL object:
c
BIO *out_bio = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, NULL, out_bio); // Read bio is NULL, we're only considering write bio here
Encrypt data with SSL_write: Call SSL_write() with the data you wish to encrypt. This will cause the encrypted data to be written into out_bio.
c
int bytes_written = SSL_write(ssl, plaintext_data, plaintext_length);
// Check bytes_written for errors and proceed accordingly
Flush/get the encrypted data: Read the encrypted data out of out_bio. This empties the bio as it's read.
c
unsigned char encrypted_data[4096];
int read_bytes;
do {
read_bytes = BIO_read(out_bio, encrypted_data, sizeof(encrypted_data));
if (read_bytes > 0) {
// Now you can use the encrypted_data buffer to send over the network or handle as needed.
}
} while (read_bytes > 0);
By reading all the data from the output bio, you are effectively "flushing" its buffer, since the data is being removed and processed or sent elsewhere. You should read out all the data in a loop as above to ensure you have emptied the buffer. If you are repeatedly sending data, continue this process: encrypt with SSL_write, then read from the memory BIO until it's empty.
Remember that in real usage, you should check for SSL_write errors, handle network errors for send, and also manage SSL handshakes and shutdowns correctly. The above code is a simplified outline and does not include these considerations for brevity.
User
SSL_read and BIO_read serves different purposes? Can they be used interchangeably in the context? Shortly
Assistant
SSL_read and BIO_read do serve different purposes in the OpenSSL library, and they cannot be used interchangeably in most contexts.
SSL_read: This function is used to read and decrypt data received over an SSL/TLS connection. When data is received from the peer (through a socket or some other transport), it is typically read from the socket into a buffer and then passed to SSL_read. SSL_read decrypts this data and returns the plaintext to the application.
BIO_read: This function is used to read data from a BIO (Basic I/O) object in OpenSSL. BIOs can represent different sources or sinks of data, such as a memory buffer (BIO_s_mem) or a file (BIO_s_file). When using a memory BIO in the context of an SSL/TLS connection, BIO_read is used to read encrypted data that has been written to the BIO by OpenSSL, not for reading plaintext data.
In the context of encrypting and sending data with SSL_write and then flushing it:
You use SSL_write to encrypt your data. The encrypted data is written to the SSL object's output BIO (which you can set to a memory BIO if you don't want OpenSSL to send the data directly over the socket).
You then use BIO_read to read the encrypted data from the memory BIO so you can manually send it over the network with a system call like send.
In the opposite direction (receiving and decrypting data):
You receive encrypted data from the network with recv and write it into the SSL object's input BIO (if you're not allowing OpenSSL to read directly from the socket).
Then, you use SSL_read to decrypt this data and retrieve the plaintext.
So to conclude, you would not use SSL_read and BIO_read interchangeably. SSL_read is for decrypting data within an SSL/TLS session, and BIO_read is for reading data from various types of BIOs, possibly including encrypted data that is waiting to be sent over the network.
User
Does SSL_connect(ssl) send data to network? shortly
Assistant
Yes, SSL_connect(ssl) typically sends data to the network because it initiates the SSL/TLS handshake process with the server, which involves sending and receiving several messages over the network.
User
Is there a mechanism to initiate the handshake with OpenSSL with manual sending and receiving it but not send data to network directly with OpenSSL function?
Assistant
Yes, OpenSSL provides mechanisms to manually perform the handshake process, which allows you to send and receive the handshake data using your own network I/O functions instead of letting OpenSSL handle the network communication directly.
To achieve this manual handshake process, you use memory BIOs for both reading from and writing to the network. Following is a simplified example that outlines the basic steps:
Create SSL object: First, you need to create an SSL object from a context.
c
// Assume ctx is a properly initialized SSL_CTX *
SSL *ssl = SSL_new(ctx);
Attach memory BIOs: Create two memory BIOs—one for reading and one for writing—and attach them to the SSL object.
c
BIO *rbio = BIO_new(BIO_s_mem());
BIO *wbio = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, rbio, wbio); // SSL takes ownership of BIOs
Initiate the handshake: Call SSL_connect to start the handshake.
c
int status = SSL_connect(ssl);
// Since BIOs are memory BIOs, this will not send data over the network.
// Instead, data to be sent will be placed in the wbio to be sent manually by you.
Send and receive handshake data manually: Use BIO_read on the wbio to retrieve data to be sent and manually send it using system calls like send. Likewise, manually receive data from the network with recv and use BIO_write to write this data into the rbio.
c
char buffer[4096];
int bytes;
// To send data
while ((bytes = BIO_read(wbio, buffer, sizeof(buffer))) > 0) {
send(sockfd, buffer, bytes, 0); // Assumes sockfd is a valid non-blocking socket descriptor.
}
// To receive data
bytes = recv(sockfd, buffer, sizeof(buffer), 0);
if (bytes > 0) {
BIO_write(rbio, buffer, bytes);
}
Repeat as necessary: Continue to transfer data until the handshake completes successfully. Check SSL_get_error() when SSL_connect returns <= 0 to handle SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE, which indicate that the handshake isn't complete and you need to read more data from the network or write more data to the network.
Remember to perform proper error-handling and to handle non-blocking I/O correctly, such as with the use of epoll or similar mechanisms to wait for sockets to become ready for read or write operations. The example above is highly simplified and does not include error checking, buffer size checks, and other important real-world concerns.
User
Can I initiate a handshake with these functions? Is it sufficient?
Assistant
Yes, you can initiate an SSL/TLS handshake with OpenSSL using the functions and mechanisms mentioned. However, the outline I provided is just a simplified summary. A robust and secure real-world implementation involves additional considerations and safeguards.
Here is a more detailed outline of what you should consider when initiating a handshake:
SSL/TLS Library Initialization: Before you start using any SSL/TLS functions, initialize the OpenSSL library:
c
SSL_library_init();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
const SSL_METHOD *method = TLS_client_method(); // or TLS_server_method()
SSL_CTX *ctx = SSL_CTX_new(method);
// Set up additional context options like verifying certificates, etc.
Memory BIO Setup: Create memory BIOs for reading and writing and attach them to the SSL object:
c
BIO *rbio = BIO_new(BIO_s_mem());
BIO *wbio = BIO_new(BIO_s_mem());
SSL *ssl = SSL_new(ctx);
SSL_set_bio(ssl, rbio, wbio);
Handshake Initiation: Start the handshake process with SSL_connect or SSL_accept, depending on whether you are the client or server:
c
int ret = SSL_connect(ssl); // use SSL_accept(ssl) for server
// Check the return value here for failure (< 0), and use SSL_get_error() for details.
Handling Handshake States: React to the return value and SSL_get_error() output, as SSL_connect and SSL_accept may return for various reasons, especially with non-blocking BIOs:
SSL_ERROR_WANT_READ: More data is needed from the peer; wait until the socket is readable to continue.
SSL_ERROR_WANT_WRITE: OpenSSL has data that needs to be sent to the peer; write this data out and wait until the socket is writable to continue.
Network I/O: Use your manual network I/O calls (send, ) to handle data read from the write BIO (wbio) and data received from the socket that you'll write to the read BIO (rbio).
User
I said several times that my primary goal is to send and receive every byte of data with OS system calls, not with OpenSSl. OpenSSL I need for encryption purpose only. Can I initiate and complete a tls handshake this way?
Assistant
I apologize for the earlier confusion. Yes, you can complete a TLS handshake by exclusively using system calls for the transmission and reception of data and using OpenSSL solely for encryption and decryption purposes. Here's a simplified outline of how to do this:
Initialize the SSL context and SSL structure
c
SSL_library_init();
SSL_load_error_strings();
const SSL_METHOD *method = TLS_client_method(); // Or TLS_server_method()
SSL_CTX *ctx = SSL_CTX_new(method);
// Configure ctx as necessary (load certificates, set options, etc.)
SSL *ssl = SSL_new(ctx);
Create memory BIOs for reading and writing
Disallow OpenSSL from automatically managing socket I/O.
c
BIO *rbio = BIO_new(BIO_s_mem());
BIO *wbio = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, rbio, wbio); // Set up both the read and write BIOs
Initiate the handshake process
This will generate the necessary handshake data and place it within the memory BIOs.
c
int ret = SSL_connect(ssl); // Use SSL_accept(ssl) if the server
// ret will return -1 and SSL_get_error(ssl, ret) should return SSL_ERROR_WANT_READ at this point.
Perform the handshake loop
Use system calls like send and recv to perform the actual network I/O.
c
User
Does SSL_connect(ssl) send a data to network in this example?
Assistant
No, in the example given, calling SSL_connect(ssl) does not directly send data to the network because the SSL object is using memory BIOs (rbio and wbio). SSL_connect will instead generate handshake data and store it in the internal memory buffer associated with the write BIO (wbio). You then need to manually read this data from the memory BIO using BIO_read and send it over the network using the send system call.
The purpose of using memory BIOs is precisely to prevent OpenSSL from automatically performing network I/O and to give you full control over the actual sending and receiving of bytes over the network. So when you call SSL_connect, it will prepare the handshake data and place it into the memory BIO instead of sending it out over a network socket.
Following this pattern, all communication—including handshake messages and later application data—is managed manually using system calls like send and recv, while OpenSSL is strictly responsible for processing the encryption and decryption.
User
Does this approach the same for client and server applications?
Assistant
The approach is fundamentally the same for both client and server applications, but there are some differences you need to be aware of:
Handshake Function: The client uses SSL_connect, whereas the server uses SSL_accept to start the handshake process.
Client:
c
int ret = SSL_connect(ssl);
Server:
c
int ret = SSL_accept(ssl);
SSL Context Setup: The server's SSL context typically requires additional configuration, such as setting up the certificate and private key that the server will present to clients.
Handling Handshake States: Both client and server need to react to SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE during the handshake. These states indicate that the handshake process needs more data to be read from or written to the network.
Read and Write Operations: Both client and server use the same BIO_read and BIO_write operations on memory BIOs to handle the encrypted data sent to or received from the network.
Network I/O Calls: Both client and server use system calls like send and recv to manually handle network I/O.
Regardless of being a client or a server, you need to manage the non-blocking socket I/O outside of OpenSSL when using memory BIOs. This includes dealing with partial reads and writes, possible EAGAIN/EWOULDBLOCK errors (indicating the operation would block and should be retried later), and using select, poll, or epoll for multiplexing.
The primary differences stem from the different roles during the handshake and different requirements regarding SSL/TLS certificates and keys. After the handshake is completed, the process of encrypting and sending data as well as receiving and decrypting data is essentially the same.
User
Is SSL_in_init(ssl) function not needed in manual handshake?
Assistant
The function SSL_in_init(ssl) is indeed relevant and typically used in manual handshake scenarios when using OpenSSL. It is used to check if a handshake is currently in progress. More specifically, SSL_in_init(ssl) returns a non-zero value if the SSL/TLS handshake has not yet been completed.
When performing a manual handshake where you manage I/O with the network, SSL_in_init(ssl) is useful to determine the state of the handshake process within your I/O loop. Once SSL_in_init(ssl) returns 0, it indicates that the handshake process has been completed successfully, and you can proceed with the normal SSL data handling operations.
Here is an example usage within a loop structure for a manual handshake with non-blocking sockets:
c
// ... Assume SSL context and SSL object are set up, memory BIOs are attached.
// ... Assume non-blocking socket is set up and connected.
while (SSL_in_init(ssl)) {
// Perform SSL connection or accept as needed
int ret = (is_client ? SSL_connect(ssl) : SSL_accept(ssl));
if (ret != 1) {
int err = SSL_get_error(ssl, ret);
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
// OpenSSL needs to read or write more data for the handshake
// Use epoll or similar mechanism to wait for the socket to be ready
// Then exchange the data between network and memory BIOs as needed
} else {
// An actual error occurred, handle the error case
break;
}
}
// Try to read from the write BIO and send any pending data to the network
// Also, read data from the network and write it to the read BIO
// Repeat until SSL_in_init returns 0, indicating the handshake is done
}
In summary, SSL_in_init(ssl) is an indicator of whether the SSL handshake is still in progress. It is an important function when implementing manual handshake processes, and it should be used to manage the loop that controls the handshake progress.
User
Can you write a goood complete example of ssl manual handshake for client?
Assistant
Absolutely, I can provide you a more detailed example of a manual SSL handshake process for a client application. This example uses non-blocking sockets and assumes you are integrating with an event loop mechanism, such as epoll, to wait for sockets to become ready for read/write operations.
Please note that proper error checking is extremely important and should be more robust in production-quality code. The example below is simplified and educational.
c
User
Thank you. Can you write it for server?
Assistant
Sure, here is an example of a manual SSL handshake for a server application. This example assumes you've got a listening socket ready to accept connections and you're using epoll to wait for events. It continues from the point where a new client connection is accepted.
Please note, as with the client example, that thorough error checking is critical in real-world code. This example focuses on the handshake part with OpenSSL and is simplified for educational purposes.
c
User
Thanks. Can I do the same with libcrypto?
Assistant
No, you cannot perform an SSL/TLS handshake using only libcrypto. The reason for this is that libcrypto provides the cryptographic algorithms and primitives used by OpenSSL, but it does not implement the SSL/TLS protocol itself. The handshake process, which involves complex protocol-specific messaging and state management, is implemented in OpenSSL's libssl.
The libssl library builds on top of libcrypto and handles the higher-level protocol details needed for securing communications with SSL/TLS. This includes creating and parsing the handshake protocol messages, certificate exchange and verification, session key exchange, and the generation and management of session keys.
In summary, if you need to perform SSL/TLS handshakes and manage SSL/TLS communications, you have to use libssl. libcrypto is used internally by libssl to perform the necessary cryptographic operations. For manual control over sending and receiving data during an SSL/TLS handshake or encrypted sessions, you manage the I/O as shown in the previous examples using memory BIOs with libssl, while handling actual data transmission with system calls (like send and recv).
User
Libssl vs OpenSSL in short?
Assistant
OpenSSL is a cryptographic library that provides a comprehensive suite of tools for implementing SSL/TLS protocols and includes various cryptographic algorithms. It is composed of two primary libraries:
libssl: This is the library within OpenSSL that implements the SSL and TLS protocols. It provides functions to create and manage connections secured by SSL/TLS.
libcrypto: This library provides general cryptographic functions and algorithms used by libssl (such as symmetric encryption, public key encryption, hashing, and so on) and can also be used independently for non-SSL/TLS related cryptographic operations.
In short, libssl is specifically for SSL/TLS support within the broader OpenSSL library, while libcrypto is for cryptographic operations that may or may not be related to SSL/TLS. Both are part of OpenSSL, which is the overall project and library name.
User
Does libssl provide the same calls for manual tls connection like you showed? What's byte size in comparison to OpenSSL? Can I statically link it with a program? Is it good idea? In short.
Assistant
In the context of the OpenSSL project, libssl is part of the overall OpenSSL library. It provides the implementation of the SSL/TLS protocols, including the calls for manual TLS connections, such as SSL_connect, SSL_accept, SSL_read, SSL_write, and the use of memory BIOs (BIO_new, BIO_s_mem, etc.) as shown in the examples I provided.
Byte Size Comparison: The size of libssl relative to the entire OpenSSL library varies depending on the version and build configuration. libssl is generally smaller than the full OpenSSL library because libssl is just one component, while OpenSSL also includes libcrypto and potentially other tools and features. The exact size will depend on how OpenSSL is compiled (e.g., with or without deprecated algorithms, with or without certain optimizations or features).
Statically Linking: Yes, you can statically link libssl (and libcrypto) with a program. When you statically link a library, you include all the necessary code within your executable, so your program does not require the OpenSSL dynamic libraries to be present on the target system.
Is It a Good Idea?: Statically linking libssl has both advantages and disadvantages:
Advantages: Simplifies deployment as the executable is self-contained and does not have dependencies on external library files. It can help avoid "dependency hell" and ensures that your application is using the specific version of OpenSSL you've tested and developed against.
Disadvantages: Increases the executable size, may lead to security update challenges (you need to redistribute your application when a security fix is released for OpenSSL), and can have licensing implications that you need to consider due to OpenSSL's dual licensing under the Apache 2.0 License and the OpenSSL License.
Statically linking can be a good idea if you want a self-contained application and are ready to manage updates and comply with licensing. If you expect the libraries on the target system to be updated regularly with the latest security patches, you may prefer dynamic linking. It's critical to consider the security implications and ensure you stay up-to-date with any vulnerabilities and patches if you go the static linking route.
User
What library does Nginx use to tls connections? Briefly
Assistant
Nginx uses OpenSSL to handle TLS connections. OpenSSL provides the necessary SSL/TLS protocols, cryptographic algorithms, and other security-related features required for establishing secure client-server communication over the internet. Nginx was designed to work with OpenSSL from the start, leveraging its robust set of features for secure data transfer.
User
Does Nginx use manual handshake and memory BIO? Does it link OpenSSL dynamically? Briefly
Assistant
Nginx uses OpenSSL for TLS connections and leverages OpenSSL's library for the encryption and decryption of data, including the handshake process. Typically, Nginx does not use a manual handshake process; it utilizes OpenSSL's built-in methods to manage the handshake and session state.
Concerning memory BIOs, Nginx does not traditionally use them for network I/O related to SSL/TLS. It mainly uses OpenSSL's default BIOs that handle socket operations directly.
When it comes to linking, Nginx can be compiled to either dynamically or statically link to OpenSSL. The choice is usually made at compile-time based on the preference for deploying and maintaining Nginx installations. Distributions might choose dynamic linking for ease of applying security updates, while static linking can be used to create a self-contained binary with specific build options.
The configuration chosen for an Nginx installation will depend on the needs of the environment and the preference for flexibility versus control over OpenSSL versions.
User
What it theoretically more efficient a default OpenSSL's BIO or memory BIO for tls connections? Does OpenSSL provide epoll mechanism for its default BIOs or poll only? Briefly
Assistant
The efficiency of default OpenSSL's BIOs versus memory BIOs for TLS connections depends on the context and use case:
Default OpenSSL's BIOs: These are optimized for direct socket operations and involve less manual intervention. They are usually more efficient for straightforward use cases where the application does not need to manage the socket I/O or integrate deeply with an existing event-driven architecture.
Memory BIOs: These are typically used when an application needs to perform manual socket I/O, such as when integrating with an event loop like epoll or when wanting precise control over the reading and writing to the network. Memory BIOs introduce additional overhead because the application has to manually move data in and out of the BIOs. Still, they provide greater flexibility for complex use cases where this trade-off is justified.
OpenSSL does not directly provide an epoll mechanism or interface for its BIOs. It's up to the application to integrate with epoll or other event notification mechanisms. OpenSSL's BIOs are agnostic to the underlying polling mechanism used (whether it's epoll, select, poll, or others). It is up to the application to handle data readiness notifications and interact with OpenSSL's BIOs appropriately.
In summary, default BIOs are theoretically more efficient for simple, straightforward usage, while memory BIOs offer more flexibility at the cost of some efficiency. OpenSSL itself is agnostic to whether epoll or poll is used; that aspect of I/O management is controlled by the embedding application.
User
Can I use default OpenSSL's BIOs with epoll? Briefly
Assistant
Yes, you can use default OpenSSL BIOs with epoll, but you will need to manage the epoll event loop yourself. OpenSSL's default BIOs will perform socket I/O operations, but your application still needs to be responsible for using epoll to determine when the socket is ready for reading or writing.
In a typical setup, you would:
Configure your sockets as non-blocking.
Use epoll to wait for events on your sockets.
When epoll indicates a socket is ready for reading or writing, you call the appropriate OpenSSL functions (SSL_read, SSL_write, SSL_accept, or SSL_connect) to process the data.
It's important to correctly handle the potential return values from OpenSSL functions, especially SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE, and use the epoll event loop to wait for the socket to become ready again.
User
Does Nginx use KTLS? briefly
Assistant
As of my knowledge cutoff date in early 2023, Nginx does not natively support Kernel TLS (kTLS). KTLS is a feature in the Linux kernel that offloads some TLS processing tasks from user space to the kernel, potentially improving performance by reducing data copies and enabling sendfile optimizations.
Whether or not to support kTLS is something that would need to be explicitly integrated into the Nginx codebase, taking into account factors such as portability and compatibility with different kernels and OpenSSL versions. Users looking for kTLS support in Nginx would need to follow the project's updates or consider third-party patches or modules that may add this capability.
For the latest information about Nginx's features and support, please refer to the official Nginx documentation or changelogs from the Nginx website or repository.
Unfortunately, OpenSSL doesn't provide an entirely BIO-free mechanism for SSL/TLS encryption and decryption, because the BIO abstraction is integral to how OpenSSL manages its internal buffering and IO state. However, BIOs can be used purely in-memory without handling network operations, thereby allowing you to manage network IO separately through system calls and event loops like epoll. This way, OpenSSL doesn't directly perform network operations, but you're still using its BIOs internally to interact with its encryption and decryption routines.
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>
// Let's assume these are initialized and configured properly elsewhere
extern int clientfd; // Non-blocking socket connected to server
extern int epollfd; // Epoll instance already set up
// Initialize OpenSSL
SSL_library_init();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
const SSL_METHOD *method = TLS_client_method(); // Depending on context, could be TLS_server_method()
SSL_CTX *ctx = SSL_CTX_new(method);
// SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); // For verifying server certs
// SSL_CTX_load_verify_locations(ctx, "ca-cert.pem", NULL); // Path to CA certs
SSL *ssl = SSL_new(ctx);
// Associate the non-blocking socket with our SSL object
SSL_set_fd(ssl, clientfd);
// Begin non-blocking SSL handshake
int handshake_status = SSL_connect(ssl);
while (1) {
struct epoll_event events[10]; // Max events to process at once
int nevents = epoll_wait(epollfd, events, 10, -1); // Wait for events on epoll instance
for (int i = 0; i < nevents; ++i) {
if (events[i].data.fd == clientfd) {
if (SSL_in_init(ssl) && (events[i].events & (EPOLLIN | EPOLLOUT))) {
// The SSL handshake is not yet complete, continue the handshake process
handshake_status = SSL_do_handshake(ssl);
if (handshake_status == 1) {
// The handshake was successful
break;
} else {
int ssl_err = SSL_get_error(ssl, handshake_status);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
// The operation did not complete; the epoll loop will be re-entered
continue;
} else {
// An actual error occurred
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
} else if (events[i].events & EPOLLIN) {
// Ready to read encrypted data from socket
char buf[4096];
ssize_t bytes_received = recv(clientfd, buf, sizeof(buf), 0);
if (bytes_received > 0) {
// Provide the encrypted data to OpenSSL to decrypt
ssize_t ssl_bytes = SSL_read(ssl, buf, (int)bytes_received);
if (ssl_bytes > 0) {
// Data was successfully decrypted and is in `buf`
// Process decrypted data, for example:
write(STDOUT_FILENO, buf, ssl_bytes);
} else {
// Handle SSL read errors or SSL_ERROR_WANT_READ/SSL_ERROR_WANT_WRITE
}
} else {
// Handle recv errors or closed connection
}
} else if (events[i].events & EPOLLOUT) {
// Ready to write encrypted data to socket
char msg[] = "Hello, TLS!";
ssize_t ssl_bytes = SSL_write(ssl, msg, sizeof(msg));
if (ssl_bytes > 0) {
// The message was successfully encrypted by OpenSSL, now send it to the server
send(clientfd, SSL_get_wbio(ssl)->ptr, ssl_bytes, 0);
} else {
// Handle SSL write errors or SSL_ERROR_WANT_READ/SSL_ERROR_WANT_WRITE
}
}
}
}
}
// Clean up
SSL_free(ssl);
SSL_CTX_free(ctx);
In this example:
SSL_connect starts the handshake operation in a non-blocking manner.
Inside the epoll loop, we check if the connection is still in the handshake phase with SSL_in_init.
Depending on whether OpenSSL requires reading or writing, we wait for the socket to be ready for the operation OpenSSL wants to perform.
When recv indicates the socket is ready for reading, we read encrypted data from the socket and pass it to OpenSSL for decryption.
When send indicates the socket is ready for writing, we take unencrypted data, encrypt it with OpenSSL using SSL_write, and write the encrypted data to the socket.
Remember, this example is simplified and omits error checking, proper resource cleanup, and complete TLS configuration management (e.g., loading certificates, handling renegotiation). In a production application, you should also consider timeout and error conditions, robust event handling, and appropriate shutdown sequences (SSL_shutdown).
epoll
recv
Completion or Retry: Repeat steps (3) and (4) until the handshake is complete. The handshake is complete when SSL_connect or SSL_accept return 1. The functions can return 0 to signal that the connection has failed, or a negative value if an error occurred. For non-blocking sockets, you'll likely need to handle situations where you're waiting for either read or write availability on the socket.
Clean Up: Once you are done with the SSL session (either after the handshake completes successfully or in the case of an error), make sure to clean up resources accordingly:
c
SSL_free(ssl);
SSL_CTX_free(ctx);
Remember that this is still a simplified overview. In practice, you need to handle timeouts, potential renegotiations, and various socket states signalled by epoll or similar mechanisms. Proper error checking and handling is critical to establishing a secure connection. The handshake process also requires setting up the SSL context properly, including loading certificates and possibly private keys, especially if you are writing a server or if the client needs to present a client certificate.
char buffer[4096];
int bytes;
while (SSL_in_init(ssl)) {
// When OpenSSL wants to write handshake data...
while ((bytes = BIO_read(wbio, buffer, sizeof(buffer))) > 0) {
send(socket_fd, buffer, bytes, 0); // Assume socket_fd is a valid socket
}
// When you have received handshake data from the peer...
bytes = recv(socket_fd, buffer, sizeof(buffer), 0); // Blocking call, should use select/poll/epoll
if (bytes > 0) {
BIO_write(rbio, buffer, bytes);
}
// Retry handshake after feeding OpenSSL with the data from the peer
ret = SSL_do_handshake(ssl);
if (ret > 0) {
break; // Handshake was successful
} else {
int err = SSL_get_error(ssl, ret);
if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) {
// An error occurred that isn't related to non-blocking I/O
fprintf(stderr, "SSL handshake error: %d\n", err);
exit(EXIT_FAILURE);
}
}
}
After completing the handshake, use SSL_write to feed plaintext into OpenSSL for encryption and BIO_read on wbio to get the encrypted data for transmission. Likewise, use recv to get encrypted data from the network and BIO_write on rbio to provide it to OpenSSL, and use SSL_read to retrieve the decrypted plaintext data.
Please ensure that you use non-blocking sockets and properly integrate with an event loop (e.g., select, poll, or epoll) to avoid blocking the application workflow.
Remember, this is a simplified example for illustration purposes. Error handling, resource management, non-blocking operation handling, and potential re-negotiation need to be implemented thoroughly for robust and secure operation. Moreover, make sure to properly configure the SSL_CTX with the necessary certificates and key material.
#include <sys/socket.h>
#include <sys/epoll.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
// Utility function to set a socket to non-blocking mode.
void set_non_blocking(int socket_fd) {
int flags = fcntl(socket_fd, F_GETFL, 0);
if (flags < 0) return;
fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);
}
// Initiate connection to server (non-blocking socket assumed).
void initiate_connection(int socket_fd, struct sockaddr *server_addr) {
connect(socket_fd, server_addr, sizeof(*server_addr));
// We ignore EINPROGRESS - it will be handled by epoll wait loop.
}
// Simplified example of manual SSL handshake for client.
int main(int argc, char *argv[]) {
// Assume server_addr is populated with the server's address and client_fd is a socket.
// Initialize OpenSSL
SSL_library_init();
SSL_load_error_strings();
const SSL_METHOD *method = TLS_client_method();
SSL_CTX *ctx = SSL_CTX_new(method);
// Load client certificates and private key, set up verification, etc.
SSL *ssl = SSL_new(ctx);
// Create new non-blocking socket and initiate connection.
int client_fd = socket(AF_INET, SOCK_STREAM, 0);
set_non_blocking(client_fd);
initiate_connection(client_fd, &server_addr);
// Create and set up epoll for non-blocking I/O.
int epoll_fd = epoll_create1(0);
struct epoll_event ev, events[10];
ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
ev.data.fd = client_fd;
epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_fd, &ev);
// Attach memory BIOs to SSL. SSL_do_handshake() will write to wbio.
BIO *rbio = BIO_new(BIO_s_mem());
BIO *wbio = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, rbio, wbio);
int ssl_ret, epoll_ret, bytes;
char buffer[4096];
int handshake_done = 0;
// Perform manual handshake.
while (!handshake_done) {
ssl_ret = SSL_connect(ssl);
if (ssl_ret != 1) {
int ssl_err = SSL_get_error(ssl, ssl_ret);
if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
// A real error occurred, print it out and exit.
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
// Wait for events (readable/writable) on the socket.
epoll_ret = epoll_wait(epoll_fd, events, 10, -1);
for (int i = 0; i < epoll_ret; i++) {
if (events[i].data.fd == client_fd) {
if (events[i].events & EPOLLOUT) {
// socket is ready for writing
while ((bytes = BIO_read(wbio, buffer, sizeof(buffer))) > 0) {
ssize_t sent = send(client_fd, buffer, bytes, 0);
if (sent < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
perror("send failed");
exit(EXIT_FAILURE);
}
}
}
if (events[i].events & EPOLLIN) {
// Socket is ready for reading
bytes = recv(client_fd, buffer, sizeof(buffer), 0);
if (bytes > 0) {
BIO_write(rbio, buffer, bytes);
} else if (bytes < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
perror("recv failed");
exit(EXIT_FAILURE);
} else if (bytes == 0) {
// Server closed the connection
fprintf(stderr, "Server closed the connection.\n");
exit(EXIT_FAILURE);
}
}
}
}
// Check if handshake is done after reading/writing.
if (!SSL_in_init(ssl)) {
handshake_done = 1;
}
}
// Handshake is done - SSL connection is established!
printf("SSL Handshake completed!\n");
// Clean up after successful handshake.
close(client_fd);
close(epoll_fd);
SSL_free(ssl);
SSL_CTX_free(ctx);
return 0;
}
This example demonstrates a simplified, non-blocking, epoll-based SSL handshake for a client. The SSL* structure is set up to use two memory BIOs for reading and writing the encrypted handshake data. The epoll event loop is used to wait for the socket to become ready for reading or writing, and system calls (send and recv) are used to manually handle network I/O. The handshake is complete when SSL_in_init(ssl) returns 0.
Remember to replace placeholders like server_addr and client_fd with real server address information and a properly configured socket, respectively. Additionally, before running the code, you should load appropriate certificates and keys into the SSL_CTX, which is omitted here for simplicity.
In practical use, this code should be more robust and include thorough error checking, handle potential EINPROGRESS errors from connect correctly, deal with SSL/TLS negotiation details, and perform a clean shutdown of the SSL/TLS session. This example is intended for educational purposes to show how manual SSL handshake could be implemented using system calls with OpenSSL.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <fcntl.h>
#include <errno.h>
void set_non_blocking(int sockfd) {
int flags = fcntl(sockfd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl F_GETFL");
exit(EXIT_FAILURE);
}
if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1) {
perror("fcntl F_SETFL");
exit(EXIT_FAILURE);
}
}
int main() {
// Initialize the SSL library
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
// Create an SSL context and configure it
const SSL_METHOD *method = TLS_server_method();
SSL_CTX *ctx = SSL_CTX_new(method);
// Load your server certificate and private key, configure context
SSL_CTX_use_certificate_file(ctx, "server.crt", SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(ctx, "server.key", SSL_FILETYPE_PEM);
// Assume listen_sock is an already created and configured socket
int listen_sock; // Should already be bound to the correct port and listening
// Set up epoll to manage the connections
int epoll_fd = epoll_create1(0);
struct epoll_event ev, events[10];
// Accept a new connection
int client_sock = accept(listen_sock, NULL, NULL);
if (client_sock < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// Make the client socket non-blocking
set_non_blocking(client_sock);
// Register the client socket with epoll
ev.events = EPOLLIN | EPOLLOUT | EPOLLET; // Edge-triggered monitoring
ev.data.fd = client_sock;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client_sock, &ev) != 0) {
perror("epoll_ctl");
exit(EXIT_FAILURE);
}
// Create an SSL object, attach the client socket file descriptor
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, client_sock);
// Create memory BIOs to which the SSL object will read/write
BIO *rbio = BIO_new(BIO_s_mem());
BIO *wbio = BIO_new(BIO_s_mem());
SSL_set_bio(ssl, rbio, wbio); // SSL no longer owns the socket directly
int handshake_done = 0;
while (!handshake_done) {
// Perform SSL_accept() to handle the handshake
int ssl_accept_ret = SSL_accept(ssl);
if (ssl_accept_ret <= 0) {
// SSL handshake is not yet complete
int err = SSL_get_error(ssl, ssl_accept_ret);
if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) {
// A real error occurred
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
// Wait for the socket to become ready for I/O
int n_events = epoll_wait(epoll_fd, events, 10, -1);
for (int i = 0; i < n_events; ++i) {
if (events[i].events & EPOLLOUT) {
// Socket is ready for writing
char out_buffer[4096];
int bytes = BIO_read(wbio, out_buffer, sizeof(out_buffer));
if (bytes > 0) {
send(client_sock, out_buffer, bytes, 0);
}
}
if (events[i].events & EPOLLIN) {
// Socket is ready for reading
char in_buffer[4096];
int bytes = recv(client_sock, in_buffer, sizeof(in_buffer), 0);
if (bytes > 0) {
BIO_write(rbio, in_buffer, bytes);
}
}
}
// Check if handshake is complete
if (SSL_is_init_finished(ssl)) {
handshake_done = 1;
}
}
printf("SSL Handshake completed with client!\n");
// Here, we would continue handling communication with the client ...
// Cleanup
SSL_free(ssl);
SSL_CTX_free(ctx);
close(client_sock);
close(epoll_fd);
close(listen_sock); // Assuming you're done with listening
return 0;
}
This example follows a similar approach to the client one, with the key differences being the use of SSL_accept instead of SSL_connect, and the initial server setup, which includes binding and listening on a socket. You load your server certificate and private key into the SSL context, create an SSL object for the client connection, replace the socket with memory BIOs, and then manually read/write data with epoll, recv, and send.
Remember to replace placeholder code (like loading the certificates and keys, and creating, binding, and listening on the listen_sock socket) with real code appropriate for your environment, and add robust error checking, resource cleanup, and proper non-blocking IO handling as needed for your specific application.