added ssl

This commit is contained in:
Pin
2022-02-17 23:22:30 -05:00
parent 5c60a475e7
commit 1c083b90f8
8 changed files with 300 additions and 25 deletions

View File

@@ -3,6 +3,59 @@
#include <sys/socket.h>
#include <netinet/in.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "socketHelp.h"
SSL_CTX* InitServerCTX() {
SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = TLS_server_method();
ctx = SSL_CTX_new(method);
if ( ctx == NULL ) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, char* certFile, char* keyFile) {
// Set local certificate from certFile
if ( SSL_CTX_use_certificate_file(ctx, certFile, SSL_FILETYPE_PEM) <= 0 ) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// Set local priv key from keyFile
if ( SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) <=0 ) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// Verify priv key
if ( !SSL_CTX_check_private_key(ctx) ) {
fprintf(stderr, "Private key does not match passed certificate file\n");
exit(EXIT_FAILURE);
}
return;
}
int createSecureSocket(int port, int *server_fd, struct sockaddr_in *address, int *addrlen, SSL_CTX **ctx, char certFile[], char keyFile[]) {
SSL_library_init();
*ctx = InitServerCTX();
LoadCertificates(*ctx, certFile, keyFile);
if ( createSocket(port, server_fd, address, addrlen) ) {
fprintf(stderr, "Error create socket\n");
exit(EXIT_FAILURE);
}
return 0;
}
int createSocket(int port, int *server_fd, struct sockaddr_in *address, int *addrlen) {
int opt = 1;