-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssl_socket.c
109 lines (94 loc) · 2.69 KB
/
ssl_socket.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "ssl_socket.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
//opens a tcp client connection and returns an int with the result
// -1 if socket was created incorrectly
// 0 if no error occured
int open_clientside_tcp_connection(int* tcp_socket, char* port_string, char* url)
{
//target is used to hold the target, so the actual ip and port we are targeting
struct addrinfo* target, *addr;
//hints to help getaddrinfo resolve hostname
//gets an ip4 address, a tcp socket
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
//perform hostname resolution for the url
int status;
if ((status = getaddrinfo(url, port_string, &hints, &target)) != 0)
{
printf("Error resolving hostname: %s\n", gai_strerror(status));
return -1;
}
//loop through ips and attempt to connect to each, if we get a connection
//free the addr info object and return
for (addr = target; addr != NULL; addr = addr->ai_next)
{
if ((*tcp_socket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol)) < 0)
continue;
int status;
if((status = connect(*tcp_socket, addr->ai_addr, addr->ai_addrlen)) == -1)
{
close(*tcp_socket);
continue;
}
else
{
freeaddrinfo(target);
return 0;
}
}
//tcp socket connection failed
return -1;
}
//initialize the ssl library, error strings, and algorithms.
//Not sure if error strings is needed but is included.
SSL_CTX* init_ssl_ctx()
{
const SSL_METHOD *meth = TLS_client_method();
SSL_load_error_strings(); //MAY NOT BE NECESSARY
OpenSSL_add_all_algorithms();
return SSL_CTX_new(meth);
}
//return new ssl connection state
SSL* ssl_new(SSL_CTX* ssl_context)
{
return SSL_new(ssl_context);
}
//set the SNI for the TLS connection
//returns -1 if there was an error
//0 if none
int ssl_set_SNI(SSL* ssl_connection, char* name)
{
int err = SSL_set_tlsext_host_name(ssl_connection, name);
if(err == 0)
return -1;
else
return 0;
}
//attaches socket to the ssl connection
void ssl_fd(int* socket, SSL* ssl_connection)
{
SSL_set_fd(ssl_connection, *socket);
}
//frees the ssl connection state
void ssl_session_free(SSL* ssl)
{
SSL_free(ssl);
}
//free the ssl context
void ssl_context_free(SSL_CTX* ssl_context)
{
SSL_CTX_free(ssl_context);
}
//close the tcp socket used in the ssl connection
int ssl_socket_close(int* tcp_socket)
{
return close(*tcp_socket);
}