80 lines
2.0 KiB
C++
80 lines
2.0 KiB
C++
#include "ssl.h"
|
|
#include "flow_help.h"
|
|
#include <unistd.h>
|
|
namespace pupes_message_client_lib {
|
|
|
|
SSL_CTX *InitTLS() {
|
|
OPENSSL_init_ssl(0, NULL);
|
|
|
|
// Create a TLS 1.3 client context
|
|
SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
|
|
if (ctx == NULL) {
|
|
ERR_print_errors_fp(stderr);
|
|
error("Failed to create SSL_CTX");
|
|
}
|
|
|
|
// Set minimum TLS version to 1.3
|
|
if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {
|
|
SSL_CTX_free(ctx);
|
|
ERR_print_errors_fp(stderr);
|
|
error("Error setting minimum TLS version");
|
|
}
|
|
|
|
// Load CA certificate for server verification
|
|
if (SSL_CTX_load_verify_locations(ctx, "certs/mldsa87_root_cert.pem", NULL) !=
|
|
1) {
|
|
SSL_CTX_free(ctx);
|
|
ERR_print_errors_fp(stderr);
|
|
error("Error loading CA certificate");
|
|
}
|
|
|
|
// Set cipher suite for TLS 1.3
|
|
if (SSL_CTX_set_ciphersuites(ctx, "TLS_AES_256_GCM_SHA384") != 1) {
|
|
SSL_CTX_free(ctx);
|
|
ERR_print_errors_fp(stderr);
|
|
error("Error setting cipher list");
|
|
}
|
|
return ctx;
|
|
}
|
|
|
|
SSL *TLS_handshake(SSL_CTX *ctx, int sockfd) {
|
|
// Create an SSL object
|
|
SSL *ssl = SSL_new(ctx);
|
|
if (ssl == NULL) {
|
|
close(sockfd);
|
|
SSL_CTX_free(ctx);
|
|
ERR_print_errors_fp(stderr);
|
|
error("Failed to create SSL object");
|
|
}
|
|
|
|
// Associate the socket with SSL
|
|
if (SSL_set_fd(ssl, sockfd) != 1) {
|
|
SSL_free(ssl);
|
|
close(sockfd);
|
|
SSL_CTX_free(ctx);
|
|
ERR_print_errors_fp(stderr);
|
|
error("Failed to set SSL file descriptor");
|
|
}
|
|
|
|
// Connect using TLS
|
|
int ret = SSL_connect(ssl);
|
|
if (ret != 1) {
|
|
fprintf(stderr, "TLS handshake failed: %d\n", SSL_get_error(ssl, ret));
|
|
ERR_print_errors_fp(stderr);
|
|
SSL_free(ssl);
|
|
close(sockfd);
|
|
SSL_CTX_free(ctx);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
printf("TLS 1.3 handshake successful using %s\n", SSL_get_cipher(ssl));
|
|
return ssl;
|
|
}
|
|
|
|
void SSLcleanup(SSL *ssl, SSL_CTX *ctx, int sockfd) {
|
|
SSL_shutdown(ssl);
|
|
SSL_free(ssl);
|
|
close(sockfd);
|
|
SSL_CTX_free(ctx);
|
|
}
|
|
} // namespace pupes_message_client_lib
|