ServidorTFG/conexion_ssl.cpp

133 lines
2.8 KiB
C++
Raw Normal View History

2020-05-08 12:43:46 +02:00
#include "conexion_ssl.h"
#include "session_manager.h"
#include "session_manager_ssl.h"
#include "config_reader.h"
#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <openssl/err.h>
#include <thread>
#include <stdlib.h>
void init_openssl();
void cleanup_openssl();
SSL_CTX *create_context();
void conexion_client(SSL_CTX *ctx,int client);
conexion_ssl::conexion_ssl(config_reader &conf):conexion(conf)
{
}
void conexion_ssl::start_server(){
int sock;
string port;
if(!this->config->get_param("port", port)){
perror("bad port in config file");
}
sock = this->create_socket(atoi(port.data()));
SSL_CTX *ctx;
init_openssl();
ctx = create_context();
this->configure_context(ctx);
while(1) {
struct sockaddr_in addr;
uint len = sizeof(addr);
2020-05-26 01:37:34 +02:00
2020-05-08 12:43:46 +02:00
int client = accept(sock, (struct sockaddr*)&addr, &len);
std::thread t_client(conexion_client,ctx , client);
t_client.detach();
}
close(sock);
SSL_CTX_free(ctx);
cleanup_openssl();
}
void init_openssl()
{
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
}
void cleanup_openssl()
{
EVP_cleanup();
}
SSL_CTX* conexion_ssl::create_context()
{
const SSL_METHOD *method;
SSL_CTX *ctx;
method = SSLv23_server_method();
ctx = SSL_CTX_new(method);
if (!ctx) {
perror("Unable to create SSL context");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
return ctx;
}
void conexion_ssl::configure_context(SSL_CTX *ctx)
{
SSL_CTX_set_ecdh_auto(ctx, 1);
/* Set the key and cert */
string cert;
if(!this->config->get_param("cert", cert)){
perror("bad cert in config file");
}
if (SSL_CTX_use_certificate_file(ctx, cert.data(), SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
string key;
if(!this->config->get_param("key", key)){
perror("bad key in config file");
}
if (SSL_CTX_use_PrivateKey_file(ctx, key.data(), SSL_FILETYPE_PEM) <= 0 ) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
}
void conexion_client(SSL_CTX *ctx,int client){
if (client < 0) {
perror("Unable to accept");
exit(EXIT_FAILURE);
}else{
SSL *ssl;
ssl = SSL_new(ctx);
SSL_set_fd(ssl, client);
if (SSL_accept(ssl) <= 0) {
ERR_print_errors_fp(stderr);
}
else {
session_manager* session = new session_manager_ssl(ssl);
2020-05-31 19:24:35 +02:00
bool enter=session->validate_pass();
while(!enter){
enter=session->validate_pass();
}
if(enter){
session->start_dialog();
}
2020-05-08 12:43:46 +02:00
delete (session);
}
SSL_shutdown(ssl);
SSL_free(ssl);
close(client);
}
}