I found a pretty good SSL/TLS server-client example in C and I wanted to adapt it for use with the BIO library. And I pretty much succeeded except one error I get when running the server:
$ ./ssl-server
68671:error:140950D3:SSL routines:SSL3_READ_N:read bio not set:/SourceCache/OpenSSL098/OpenSSL098-35.1/src/ssl/s3_pkt.c:203:
I'm using gcc -o ssl-server SSL-Server.c -lssl -lcrypto -Wall to compile the server:
//SSL-Server.c
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#define FAIL -1
#define PORT "2013"
SSL_CTX* InitServerCTX(void)
{
SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = SSLv3_server_method();
ctx = SSL_CTX_new(method);
if( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
if( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
if( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
if( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}
void ShowCerts(SSL* ssl)
{
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl);
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
{
printf("No certificates.\n");
}
}
void Servlet(SSL* ssl)
{
char buf[1024];
int sd, bytes;
if( SSL_accept(ssl) == FAIL )
{
ERR_print_errors_fp(stderr);
}
else
{
ShowCerts(ssl);
bytes = SSL_read(ssl, buf, sizeof(buf));
if( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
SSL_write(ssl, "back message", strlen("back message"));
}
else
{
ERR_print_errors_fp(stderr);
}
}
sd = SSL_get_fd(ssl);
SSL_free(ssl);
close(sd);
}
int main(int count, char *strings[])
{
SSL_CTX *ctx;
BIO *acc, *client;
SSL_library_init();
ctx = InitServerCTX();
LoadCertificates(ctx, "mycert.pem", "mycert.pem");
acc = BIO_new_accept(PORT);
if(!acc)
{
printf("Error creating server socket");
}
while(1)
{
if(BIO_do_accept(acc) <= 0)
{
printf("Error binding server socket");
}
SSL *ssl;
client = BIO_pop(acc);
if(!(ssl = SSL_new(ctx)))
{
printf("Error creating SSL context");
}
SSL_set_bio(ssl, client, client);
// Here should be created threads
Servlet(ssl);
}
SSL_CTX_free(ctx);
}
I'm using gcc -o ssl-client SSL-Client.c -lssl -lcrypto -Wall to compile the client:
//SSL-Client.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#define FAIL -1
#define SERVER "localhost"
#define PORT "2013"
SSL_CTX* InitCTX(void)
{
SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = SSLv3_client_method();
ctx = SSL_CTX_new(method);
if( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void ShowCerts(SSL* ssl)
{
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl);
if( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
{
printf("No certificates.\n");
}
}
int main(int count, char *strings[])
{
SSL_CTX *ctx;
SSL *ssl;
BIO *conn;
char buf[1024];
int bytes;
SSL_library_init();
ctx = InitCTX();
conn = BIO_new_connect(SERVER ":" PORT);
if(!conn)
{
printf("Error creating connection BIO");
}
if(BIO_do_connect(conn) <= 0)
{
printf("Error connecting to remote machine");
}
ssl = SSL_new(ctx);
SSL_set_bio(ssl, conn, conn);
if( SSL_connect(ssl) <= 0 )
{
printf("Error connecting SSL object");
}
else
{
printf("Connected!");
ShowCerts(ssl);
SSL_write(ssl, "ana are mere", strlen("ana are mere") );
bytes = SSL_read(ssl, buf, sizeof(buf));
printf("%s\n", buf);
SSL_free(ssl);
}
SSL_CTX_free(ctx);
return 0;
}
I'm generating the certificate with the openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem command.
Everything works well and the messages are sending OK. Please ignore the lack of error checking and excuse the total mess in the code, it's just for learning purposes.
Can anyone point me what's wrong? Also can you tell if I'm doing major mistakes, I'm trying to learn?(e.g. routine call order, major security problems, etc.)
Thanks!
According to the manual page (the example code at the bottom is very illustrative), the first call to BIO_do_accept() will set up the accept BIO and does nothing else. Only the second and all subsequent calls will be actual calls to accept connections. This is quite illustrative of why OpenSSL will never win an award for «most intuitive API design».
So what happens in your code? You only call BIO_do_accept() within the loop. First time through the loop, it will set up the BIO and return immediately. Your code calls Servlet() on the inexisting connection, and SSL_accept() fails, returning the error you are seeing. After Servlet() returns, your code loops happily into the second invocation of BIO_do_accept() which this time blocks, waiting for the first connection, and everything works as intended from here.
To fix this, you need to call BIO_do_accept() once before the loop, like this (using your broken style of error handling for consistency -- you really need to fix your error handling!):
[...]
acc = BIO_new_accept(PORT);
if(!acc)
{
printf("Error creating server socket");
}
/* first call is to set up accept BIO */
if(BIO_do_accept(acc) <= 0)
{
printf("Error calling BIO_do_accept() the first time");
}
while(1)
{
if(BIO_do_accept(acc) <= 0)
{
printf("Error binding server socket");
}
[...]
Related
openssl_1.1.1_perl_dump.txt
We are trying to upgrade on Openssl version 1.1.1, with security layer from TLS 1.2 to TLS 1.3.
Our code base performs SSL handshake, and later use send & read/recv function to transfer data. *Note - it is working fine for TLS 1.2.
However when we switch to TLS 1.3, and data packets are not received for send & read/recv, but working only when we use SSL_write & SSL_read.
Below we have tried to make sample server & client program, where we use send & read/recv functions after successful SSL connection, here also it works fine for TLS 1.2, but in case of TLS 1.3 there is lag in packets received, the first response from server is blank, please refer outputs below. For out put of 'perl configdata.pm --dump' refer attachment.
Used steps mentioned as per this reference article https://help.ubuntu.com/community/OpenSSL - to create SSL certificates.
server.c
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "/usr/include/openssl/ssl.h"
#include "/usr/include/openssl/crypto.h"
#include "/usr/include/openssl/err.h"
#define FAIL -1
int OpenListener(int port)
{ int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
perror("can't bind port");
abort();
}
if ( listen(sd, 10) != 0 )
{
perror("Can't configure listening port");
abort();
}
return sd;
}
int isRoot()
{
if (getuid() != 0)
{
return 0;
}
else
{
return 1;
}
}
SSL_CTX* InitServerCTX(void)
{ SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
SSL_load_error_strings(); /* load all error messages */
char *imethod=getenv("TLS_METHOD");
if(imethod!=NULL && strncmp(imethod, "1.3", 3)==0){
printf("\nSetting TLS1.3 method\n");
fflush(stdout);
method = TLS_server_method(); /* create new server-method instance */
}
else{
printf("\nSetting TLS1.2 method\n");
fflush(stdout);
method = TLSv1_2_server_method(); /* create new server-method instance */
}
ctx = SSL_CTX_new(method); /* create new context from method */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
if(imethod!=NULL && strncmp(imethod, "1.3", 3)==0)
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
SSL_CTX_load_verify_locations(ctx, "01.pem", "/home/qarun/aparopka/myCA/signedcerts");
/* set the local certificate from CertFile */
if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* set the private key from KeyFile (may be the same as CertFile) */
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* verify private key */
if ( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
//New lines - Force the client-side have a certificate
/*SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL);
SSL_CTX_set_verify_depth(ctx, 2);*/
//End new lines
}
void ShowCerts(SSL* ssl)
{ X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
printf("No certificates.\n");
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{ char buf[1024];
char reply[1024];
int sd, bytes;
const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
sd = SSL_get_fd(ssl); /* get socket connection */
printf("\nsd: <%d>", sd);
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
/*if(SSL_do_handshake(ssl) <= 0){
printf("\n SSL_do_handshake failed....\n");
}*/
ShowCerts(ssl); /* get any certificates */
do{
//bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
//bytes = read(sd, buf, sizeof(buf));
bytes = recv(sd, buf, sizeof(buf), 0);
if ( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
sprintf(reply, HTMLecho, buf); /* construct reply */
//SSL_write(ssl, reply, strlen(reply)); /* send reply */
send(sd, reply, strlen(reply), 0); // MSG_NOSIGNAL | MSG_DONTWAIT); //MSG_CONFIRM);
}
else
ERR_print_errors_fp(stderr);
}while(bytes>0);
}
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
char *portnum;
if(!isRoot())
{
printf("This program must be run as root/sudo user!!");
//exit(0);
}
if ( count != 2 )
{
printf("Usage: %s <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();
portnum = strings[1];
ctx = InitServerCTX(); /* initialize SSL */
LoadCertificates(ctx, "/home/qarun/aparopka/myCA/server_crt.pem", "/home/qarun/aparopka/myCA/server_key.pem"); /* load certs */
server = OpenListener(atoi(portnum)); /* create server socket */
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
client.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define FAIL -1
//Added the LoadCertificates how in the server-side makes.
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
/* set the local certificate from CertFile */
if ( SSL_CTX_use_certificate_chain_file(ctx, CertFile ) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* set the private key from KeyFile (may be the same as CertFile) */
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* verify private key */
if ( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}
int OpenConnection(const char *hostname, int port)
{ int sd;
struct hostent *host;
struct sockaddr_in addr;
if ( (host = gethostbyname(hostname)) == NULL )
{
perror(hostname);
abort();
}
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
close(sd);
perror(hostname);
abort();
}
return sd;
}
SSL_CTX* InitCTX(void)
{ SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */
SSL_load_error_strings(); /* Bring in and register error messages */
char *imethod=getenv("TLS_METHOD");
if(imethod!=NULL && strncmp(imethod, "1.3", 3)==0){
printf("\nSetting TLS1.3 method\n");
fflush(stdout);
method = TLS_client_method(); /* create new server-method instance */
}
else{
printf("\nSetting TLS1.2 method\n");
fflush(stdout);
method = TLSv1_2_client_method(); /* create new server-method instance */
}
ctx = SSL_CTX_new(method); /* Create new context */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
if(imethod!=NULL && strncmp(imethod, "1.3", 3)==0)
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
return ctx;
}
void ShowCerts(SSL* ssl)
{ X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line); /* free the malloc'ed string */
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line); /* free the malloc'ed string */
X509_free(cert); /* free the malloc'ed certificate copy */
}
else
printf("Info: No client certificates configured.\n");
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
SSL *ssl;
char buf[1024];
int bytes;
char *hostname, *portnum;
if ( count != 3 )
{
printf("usage: %s <hostname> <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();
hostname=strings[1];
portnum=strings[2];
ctx = InitCTX();
LoadCertificates(ctx, "/home/qarun/aparopka/myCA/server_crt.pem", "/home/qarun/aparopka/myCA/server_key.pem");
server = OpenConnection(hostname, atoi(portnum));
ssl = SSL_new(ctx); /* create new SSL connection state */
SSL_set_fd(ssl, server); /* attach the socket descriptor */
int sd = SSL_get_fd(ssl);
int flip=1;
printf("\nsd: <%d>", sd);
if ( SSL_connect(ssl) == FAIL ) /* perform the connection */
ERR_print_errors_fp(stderr);
else
{ //char *msg = "Hello???";
if(SSL_do_handshake(ssl) <= 0){
printf("\n client SSL_do_handshake failed....\n");
}
char msg[1024];
printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
ShowCerts(ssl); /* get any certs */
while(1){
bzero(msg, 1024);
bzero(buf, 1024);
printf("\nEnter message: ");
fgets(msg, 1024, stdin);
//SSL_write(ssl, msg, strlen(msg)); /* encrypt & send message */
send(sd, msg, strlen(msg), 0); //MSG_NOSIGNAL | MSG_DONTWAIT); //MSG_CONFIRM);
//bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
//bytes = read(sd, buf, sizeof(buf));
bytes = recv(sd, buf, sizeof(buf), 0);
/* read again for TLS 1.3 only for first time */
/*char *imethod=getenv("TLS_METHOD");
if(imethod!=NULL && strncmp(imethod, "1.3", 3)==0
&& flip){
bytes = read(sd, buf, sizeof(buf));
flip=0;
}*/
buf[bytes] = 0;
printf("Received: \"%s\"\n", buf);
}
SSL_free(ssl); /* release connection state */
}
close(server); /* close socket */
SSL_CTX_free(ctx); /* release context */
return 0;
}
Server & client Output with TLS 1.2
**$ ./ssl_server_working 2023**
Setting TLS1.2 method
Connection: 10.250.14.23:41152
sd: <4>No certificates.
Client msg: "first
"
Client msg: "second
"
Client msg: "third
"
**./ssl_client_working 10.250.14.23 2023**
Setting TLS1.2 method
sd: <3>Connected with ECDHE-RSA-AES256-GCM-SHA384 encryption
Server certificates:
Subject: /CN=MyOwn Root Certificate Authority/ST=CA/C=US/emailAddress=amit.paropkari#quest.com/O=SharePlex/OU=IT Department
Issuer: /CN=MyOwn Root Certificate Authority/ST=CA/C=US/emailAddress=amit.paropkari#quest.com/O=SharePlex/OU=IT Department
Enter message: first
Received: "<html><body><pre>first
</pre></body></html>
"
Enter message: second
Received: "<html><body><pre>second
</pre></body></html>
"
Enter message: third
Received: "<html><body><pre>third
</pre></body></html>
"
Server & client output for TLS 1.3 : Note the response for first client request is blank, which is received in next response for second request.
export TLS_METHOD=1.3
**./ssl_server_working 2024**
Setting TLS1.3 method
Connection: 10.250.14.23:34012
sd: <4>No certificates.
Client msg: "first
"
Client msg: "second
"
Client msg: "third
"
**./ssl_client_working 10.250.14.23 2024**
Setting TLS1.3 method
sd: <3>Connected with TLS_AES_256_GCM_SHA384 encryption
Server certificates:
Subject: /CN=MyOwn Root Certificate Authority/ST=CA/C=US/emailAddress=amit.paropkari#quest.com/O=SharePlex/OU=IT Department
Issuer: /CN=MyOwn Root Certificate Authority/ST=CA/C=US/emailAddress=amit.paropkari#quest.com/O=SharePlex/OU=IT Department
Enter message: first
Received: ""
Enter message: second
Received: "<html><body><pre>first
</pre></body></html>
"
Enter message: third
Received: "<html><body><pre>second
</pre></body></html>
"
We got the answer for this. Turns out TLS 1.3 has added one more handshake step, where after server Finish message Client again sends Server finish message, server verifies it, & sends post-handshake protocol level message, called as 'NewSessionTicket message'. We can disable it with SSL_CTX_set_num_tickets method, before initiating SSL server.
SSL_set_num_tickets(ssl, 0); /* Disable post-handshake token */
sd = SSL_get_fd(ssl); /* get socket connection */
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
As for people concerned about this not being secure, in our case of requirement we only need initial secure authentication, and then we do session tunneling. After that if we use SSL_write SSL_read for every transaction (which are in huge volume & time constraint) , the encryption decryption step would degrade the performance. So we are using send & recv for sending data.
I'm trying to make a client/server program with the OpenSSL that can set up a secure connection and then pass encrypted messages back and forth. I'm using a self-signed certificate for the server and a private key for the client. When a connection is established, I use SSL_accept() to initiate the handshake. This is where the program breaks. On the client-side, the error message is:
140104940065408:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../ssl/record/rec_layer_s3.c:1543:SSL alert number 40
and on the server-side the error message is:
140062094398080:error:1417A0C1:SSL routines:tls_post_process_client_hello:no shared cipher:../ssl/statem/statem_srvr.c:2283:
I'm very new to OpenSSL and to cryptography in general so I'm quite lost as to how to proceed from here. Any help would be greatly appreciated. I'll post the full code for the client and server below.
Client Program:
#include <errno.h> /*USING THE ERROR LIBRARY FOR FINDING ERRORS*/
#include <stdio.h> /*standard i/o*/
#include <unistd.h> /*FOR USING FORK for at a time send and receive messages*/
#include <malloc.h> /*FOR MEMORY ALLOCATION */
#include <string.h> /*using fgets funtions for geting input from user*/
#include <sys/socket.h> /*for creating sockets*/
#include <resolv.h> /*server to find out the runner's IP address*/
#include <netdb.h> /*definitions for network database operations */
#include <openssl/ssl.h> /*using openssl function's and certificates and configuring them*/
#include <openssl/err.h> /* helps in finding out openssl errors*/
#include <unistd.h> /*FOR USING FORK for at a time send and receive messages*/
#define FAIL -1 /*for error output == -1 */
#define BUFFER 1024 /*buffer for reading messages*/
// CLIENT PROGRAM
//code from: https://github.com/ElectronSz/Encrypted-Chat-Server-Using-C-Programming-and-OpenSSL-AES-DES
int OpenConnection(const char *hostname, int port) {
int sd;
struct hostent *host;
struct sockaddr_in addr; /*creating the sockets*/
if ( (host = gethostbyname(hostname)) == NULL ) {
perror(hostname);
abort();
}
sd = socket(PF_INET, SOCK_STREAM, 0); /* setting the connection as tcp it creates endpoint for connection */
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 ) /*initiate a connection on a socket*/ {
close(sd);
perror(hostname);
abort();
}
return sd;
}
void LoadKey(SSL_CTX* ctx, char* KeyFile) /* to load a certificate into an SSL_CTX structure*/ {
/* set the private key from KeyFile (may be the same as CertFile) */
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 ) {
ERR_print_errors_fp(stderr);
abort();
}
}
SSL_CTX* InitCTX(void) /*creating and setting up ssl context structure*/ {
const SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */
SSL_load_error_strings(); /* Bring in and register error messages */
method = TLS_client_method(); /* Create new client-method instance */
ctx = SSL_CTX_new(method); /* Create new context */
if ( ctx == NULL ) {
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void ShowCerts(SSL* ssl) /*show the ceritficates to server and match them but here we are not using any client certificate*/ {
X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
if ( cert != NULL ) {
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line); /* free the malloc'ed string */
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line); /* free the malloc'ed string */
X509_free(cert); /* free the malloc'ed certificate copy */
} else {
printf("Info: No client certificates configured.\n");
}
}
int main(int count, char *strings[]) /* getting port and ip as an argument*/ {
SSL_CTX *ctx;
int server;
SSL *ssl;
char buf[1024];
char input[BUFFER];
int bytes;
char *hostname, *portnum;
pid_t cpid; /* fork variable*/
if ( count != 3 ) {
printf("usage: %s \n", strings[0]);
exit(0);
}
SSL_library_init(); /*load encryption and hash algo's in ssl*/
hostname=strings[1];
portnum=strings[2];
ctx = InitCTX();
//SSL_CTX_set_ciphersuites(ctx, OSSL_default_ciphersuites());
LoadKey(ctx, "client.pem"); /* load certs */
server = OpenConnection(hostname, atoi(portnum)); /*converting ascii port to interger */
ssl = SSL_new(ctx); /* create new SSL connection state */
SSL_set_fd(ssl, server); /* attach the socket descriptor */
//SSL_set_ciphersuites(ssl, OSSL_default_ciphersuites());
/* Host common name */
// Not necessarily needed
//SSL_set_tlsext_host_name(ssl, "Conor");
if ( SSL_connect(ssl) == FAIL ) /* perform the connection */ {
ERR_print_errors_fp(stderr);
} else {
printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
ShowCerts(ssl);
/* get any certs */
cpid=fork();
/*Fork system call is used to create a new process*/
if(cpid==0) {
while(1) {
fflush(stdout);
printf("\nMESSAGE TO SERVER:");
fgets(input, BUFFER, stdin);
SSL_write(ssl, input, strlen(input)); /* encrypt & send message */
}
} else {
while(1) {
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
if ( bytes > 0 ) {
buf[bytes] = 0;
printf("\nMESSAGE FROM SERVER: %s\n", buf);
printf("\nMESSAGE TO SERVER:");
fflush(stdout);
}
}
}
SSL_free(ssl); /* release connection state */
}
close(server); /* close socket */
SSL_CTX_free(ctx); /* release context */
return 0;
}
Server Program:
//#include <openssl/applink.c>
#include <unistd.h> /*FOR USING FORK for at a time send and receive messages*/
#include <errno.h> /*USING THE ERROR LIBRARY FOR FINDING ERRORS*/
#include <malloc.h> /*FOR MEMORY ALLOCATION */
#include <string.h> /*using fgets funtions for geting input from user*/
#include <arpa/inet.h> /*for using ascii to network bit*/
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h> /* network to asii bit */
#include <resolv.h> /*server to find out the runner's IP address*/
#include <stdio.h> /*standard i/o*/
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <inttypes.h>
#define FAIL -1 /*for error output == -1 */
#define BUFFER 1024 /*buffer for reading messages*/
// SERVER PROGRAM
void InitializeSSL() {
SSL_load_error_strings();
SSL_library_init();
OpenSSL_add_all_algorithms();
}
void DestroySSL() {
ERR_free_strings();
EVP_cleanup();
}
void ShutdownSSL(SSL* cSSL) {
SSL_shutdown(cSSL);
SSL_free(cSSL);
}
int OpenListener(int port) {
int sd;
struct sockaddr_in addr; /*creating the sockets*/
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr)); /*free output the garbage space in memory*/
addr.sin_family = AF_INET; /*getting ip address form machine */
addr.sin_port = htons(port); /* converting host bit to n/w bit */
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 ) /* assiging the ip address and port*/ {
perror("can't bind port"); /* reporting error using errno.h library */
abort(); /*if error will be there then abort the process */
}
if ( listen(sd, 10) != 0 ) /*for listening to max of 10 clients in the queue*/ {
perror("Can't configure listening port"); /* reporting error using errno.h library */
abort(); /*if erroor will be there then abort the process */
}
return sd;
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */ {
char buf[1024];
int sd, bytes;
char input[BUFFER];
pid_t cpid;
//Here is the SSL Accept portion. Now all reads and writes must use SSL
int ret = SSL_accept(ssl);
printf("%d\n", ret);
if (ret == 0) {
/* Hard error */
exit(-1);
} else if ( ret == -1 ) /* do SSL-protocol accept */ {
printf("Handshake Error %d\n", SSL_get_error(ssl, ret));
ERR_print_errors_fp(stderr);
exit(-1);
}
/*Fork system call is used to create a new process*/
cpid=fork();
if(cpid==0) {
while(1) {
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request and read message from server*/
if ( bytes > 0 ) {
buf[bytes] = 0;
printf("\nMESSAGE FROM CLIENT: %s\n", buf);
printf("\nMESSAGE TO CLIENT:");
fflush(stdout);
} else {
ERR_print_errors_fp(stderr);
}
}
} else {
while(1) {
fflush(stdout);
printf("\nMESSAGE TO CLIENT:");
fgets(input, BUFFER, stdin); /* get request and reply to client*/
SSL_write(ssl, input, strlen(input));
}
}
sd = SSL_get_fd(ssl); /* get socket connection */
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
bool str_to_uint16(char *str, uint16_t *res) {
char *end;
errno = 0;
intmax_t val = strtoimax(str, &end, 10);
if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0') {
return false;
}
*res = (uint16_t) val;
return true;
}
int main(int count, char *strings[]) /* getting port as a argument*/ {
int sockfd, newsockfd;
SSL_CTX *sslctx;
SSL *cSSL;
char buf[1024];
char input[BUFFER];
int bytes;
char *portnum;
pid_t cpid; /* fork variable*/
if ( count != 2 ) {
printf("Usage: %s <portnum> \n", strings[0]); /*send the usage guide if syntax of setting port is different*/
exit(0);
}
portnum = strings[1];
uint16_t temp;
uint16_t *aPortNumber = &temp;
if (str_to_uint16(portnum, aPortNumber) == false) {
printf("Port number must be between 0 and 65535.");
exit(1);
}
InitializeSSL();
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0) {
//Log and Error
exit(1);
}
struct sockaddr_in saiServerAddress;
bzero((char *) &saiServerAddress, sizeof(saiServerAddress));
saiServerAddress.sin_family = AF_INET;
saiServerAddress.sin_addr.s_addr = INADDR_ANY;
saiServerAddress.sin_port = htons(*aPortNumber);
bind(sockfd, (struct sockaddr *) &saiServerAddress, sizeof(saiServerAddress));
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
listen(sockfd,5);
newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &len);
sslctx = SSL_CTX_new( TLS_server_method());
// check return values vvvv
int use_cert = SSL_CTX_use_certificate_file(sslctx, "server.pem" , SSL_FILETYPE_PEM);
if (use_cert == 0) {
ERR_print_errors_fp(stderr);
exit(-1);
}
int use_prv = SSL_CTX_use_PrivateKey_file(sslctx, "private-key.pem", SSL_FILETYPE_PEM);
if (use_prv == 0) {
ERR_print_errors_fp(stderr);
exit(-1);
}
cSSL = SSL_new(sslctx);
SSL_set_fd(cSSL, newsockfd );
//SSL_CTX_set_ciphersuites(sslctx, cipher_list.c_str());
//SSL_set_ciphersuites(cSSL, cipher_list.c_str());
Servlet(cSSL);
ShutdownSSL(cSSL);
return 0;
}
I've created a simple GET request using openssl and I'm having trouble on reading and returning the response. This is my code:
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <string.h>
#define HOST "google.com"
#define PORT "443"
int main() {
BIO* bio;
SSL* ssl;
SSL_CTX* ctx;
SSL_library_init();
ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx == NULL) {
printf("CTX is null\n");
}
bio = BIO_new_ssl_connect(ctx);
BIO_set_conn_hostname(bio, HOST ":" PORT);
if (BIO_do_connect(bio) <= 0) {
printf("Failed connection\n");
return 1;
} else {
printf("Connected\n");
}
char* write_buf = "GET / HTTP/1.0\r\n"
"HOST: google.com\r\n"
"\r\n";
if (BIO_write(bio, write_buf, strlen(write_buf) <= 0)) {
if (!BIO_should_retry(bio)) {
}
printf("Failed write\n");
}
printf("%s", write_buf);
int size;
char buf[1024];
for (;;) {
size = BIO_read(bio, buf, 1023);
if (size <= 0) {
printf("No more data");
break;
}
buf[size] = 0;
printf("%s\n", buf);
}
BIO_free_all(bio);
SSL_CTX_free(ctx);
return 0;
}
When I run this, the program is able to connect:
Connected
GET / HTTP/1.0
HOST: www.google.com
But it do not return any response, I have noted that the for loop for reading the response only takes one iteration, I don't know what I am doing wrong, any suggestions for solving this issue?
I am trying to build a ssl client and testing it with s_server provided by openssl. Until socket's connection, everything is fine but SSL_connect() fails and returns SSL_ERROR_SYSCALL.
SSL_ERROR_SYSCALL: Some I/O error occurred. The OpenSSL error queue may contain more information on the error. If the error queue is empty (i.e. ERR_get_error() returns 0), ret can be used to find out more about the error: If ret == 0, an EOF was observed that violates the protocol. If ret == -1, the underlying BIO reported an I/O error (for socket I/O on Unix systems, consult errno for details).
As documentation states, I further diagnosed with ERR_get_error() and it returned 0. How can I look errno in windows? On other side, server also doesn't show a lot.
D:\server>openssl s_server -accept 5555 -cert server.crt -key server.key -msg -debug
Using default temp DH parameters
ACCEPT
read from 0x600077c90 [0x600096e40] (11 bytes => 0 (0x0))
ERROR
shutting down SSL
CONNECTION CLOSED
EDIT Today I tried to print error string
err = SSL_connect(ssl);
ERR_error_string(SSL_get_error(ssl, err), buf);
printf("Error: %s\n", buf);
and the output was
Error: error:00000005:lib(0):func(0):DH lib
Which looks like something with Diffie-Hellman problem. there is another discussion about dH parameters but as they mentioned, I am not setting dh parameters myself.
Other similar questions talk about ssl version. I have also tried their suggestions but doesn't help.
Environment: I am on Windows, gcc (cygwin) compiler, openssl-1.02k
I also tried with errno but it returns No Error
case SSL_ERROR_SYSCALL:
perror(errno);
break;
Complete code from client is
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
#define ON 1
#define OFF 0
#define RETURN_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(1); }
#define RETURN_NULL(x) if ((x)==NULL) exit (1)
int sock_conn;
SSL_CTX *ctx;
#define DEFAULT_BUF_SIZE 64
void handle_error(const char *file, int lineno, const char *msg) {
fprintf(stderr, "** %s:%i %s\n", file, lineno, msg);
ERR_print_errors_fp(stderr);
exit(1);
}
void Errors_SSL(const char * file, int line)
{
char *buf;
unsigned long code;
code = ERR_get_error();
while (code)
{
ERR_error_string(code, buf);
printf(buf);
printf("error code: %lu in %s line %d.\n", code, file, line);
code = ERR_get_error();
}
}
#define ssl_error() Errors_SSL( __FILE__, __LINE__)
#define int_error(msg) handle_error(__FILE__, __LINE__, msg)
void die(const char *msg) {
perror(msg);
exit(1);
}
int startTCPConnection()
{
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0 )
int_error("socket() fails");
struct sockaddr_in server_addr;
memset (&server_addr, '\0', sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5555); /* Server Port number */
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* Server IP */
if ( connect(sock, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0 )
int_error("connect() fails");
printf("TCP Socket Connected\n");
return sock;
}
SSL_CTX *createSSLObject()
{
int verify_client = OFF;
SSL_CTX *ct = SSL_CTX_new(SSLv23_client_method());
if (ct == NULL)
int_error("SSL_CTX_new() returned 0");
if(verify_client == ON)
{
/* Load the client certificate into the SSL_CTX structure */
if (SSL_CTX_use_certificate_file(ct, "device.pem", SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stderr);
exit(1);
}
/* Load the private-key corresponding to the client certificate */
if (SSL_CTX_use_PrivateKey_file(ct, "device.key", SSL_FILETYPE_PEM) <= 0)
{
ERR_print_errors_fp(stderr);
exit(1);
}
/* Check if the client certificate and private-key matches */
if (!SSL_CTX_check_private_key(ct))
{
fprintf(stderr,"Private key does not match the certificate public key\n");
exit(1);
}
}
//SSL_CTX_set_mode(ct, SSL_MODE_AUTO_RETRY);
if (!SSL_CTX_load_verify_locations(ct, "rootCA.pem", NULL))
int_error("SSL_CTX_load_verify_locations() failed");
SSL_CTX_set_verify(ct, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ct,2);
return ct;
}
int main()
{
int err, e;
char hello[80];
//printf ("Message to be sent to the SSL server: ");
//fgets (hello, 80, stdin);
SSL_library_init(); // load all cipher and crypto algorithms
SSL_load_error_strings(); // error strings for libssl
ERR_load_BIO_strings();
ERR_load_crypto_strings(); // error strings for libcrypto
ctx = createSSLObject();
sock_conn = startTCPConnection();
SSL * ssl = SSL_new(ctx);
RETURN_NULL(ssl);
SSL_set_fd(ssl, sock_conn);
SSL_set_connect_state(ssl);
do
{
err = SSL_connect(ssl);
if (err < 0)
{
switch (SSL_get_error(ssl, err))
{
case SSL_ERROR_NONE:
printf("SSL_ERROR_NONE");
break;
case SSL_ERROR_ZERO_RETURN:
printf("SSL_ERROR_ZERO_RETURN");
break;
case SSL_ERROR_WANT_READ:
printf("SSL_ERROR_WANT_READ\n");
break;
case SSL_ERROR_WANT_WRITE:
printf("SSL_ERROR_WANT_WRITE\n");
break;
case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT:
printf("SSL_ERROR_WANT_CONNECT || SSL_ERROR_WANT_ACCEPT\n");
break;
case SSL_ERROR_WANT_X509_LOOKUP:
printf("SSL_ERROR_WANT_X509_LOOKUP");
break;
case SSL_ERROR_SYSCALL:
do
{
e = ERR_get_error();
if (e > 0)
int_error("Error");
}while (e > 0);
printf("SSL_ERROR_SYSCALL\n");
break;
case SSL_ERROR_SSL:
printf("SSL_ERROR_SSL");
break;
default:
break;
}
//ERR_clear_error();
}
}while(SSL_is_init_finished(ssl) == 0);
printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
X509 *server_cert = SSL_get_peer_certificate (ssl);
if (server_cert != NULL)
{
printf ("Server certificate:\n");
char *str = X509_NAME_oneline(X509_get_subject_name(server_cert),0,0);
printf ("\t subject: %s\n", str);
free (str);
str = X509_NAME_oneline(X509_get_issuer_name(server_cert),0,0);
printf ("\t issuer: %s\n", str);
free(str);
X509_free (server_cert);
}
return 0;
}
A long time ago I got this problem and could not got any solution and never worked again due to time issue.
Note: I have also tried many off the shelf tutorial client examples from other people and all of them fails on connect. There is another non blocking socket solution, that works fine for me but I want to dig out why a blocking socket is failing.
I'm trying to create server busy by adding delay in the SSL Server code(given below) before accept(), then from the SSL client trying to connect to server. After approx 2 minutes i'm getting SSL error and client returns as expected.
When i try to analyse wireshark log i can seen "Client Hello TCP retramission" message 10 times. I'm trying to understand the reason and source of this retransmission. Is it in TCP Layer or SSL Layer?
I'm doing this on linux ubuntu 14.04 x86. Below are the ssl-server and ssl-client downloaded.
I tried changing /proc/sys/net/ipv4/tcp_retries2 but it doesn't effect the number of retries. From Wireshark log i can see the number of retries for client hello is 10.
Thanks in advance.
//SSL-Server.c
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#define FAIL -1
int OpenListener(int port)
{ int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
perror("can't bind port");
abort();
}
if ( listen(sd, 1) != 0 )
{
perror("Can't configure listening port");
abort();
}
return sd;
}
int isRoot()
{
if (getuid() != 0)
{
return 0;
}
else
{
return 1;
}
}
SSL_CTX* InitServerCTX(void)
{ SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */
SSL_load_error_strings(); /* load all error messages */
method = SSLv3_server_method(); /* create new server-method instance */
ctx = SSL_CTX_new(method); /* create new context from method */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
/* set the local certificate from CertFile */
if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* set the private key from KeyFile (may be the same as CertFile) */
if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
{
ERR_print_errors_fp(stderr);
abort();
}
/* verify private key */
if ( !SSL_CTX_check_private_key(ctx) )
{
fprintf(stderr, "Private key does not match the public certificate\n");
abort();
}
}
void ShowCerts(SSL* ssl)
{ X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line);
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line);
X509_free(cert);
}
else
printf("No certificates.\n");
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{ char buf[1024];
char reply[1024];
int sd, bytes;
const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */
ERR_print_errors_fp(stderr);
else
{
ShowCerts(ssl); /* get any certificates */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
if ( bytes > 0 )
{
buf[bytes] = 0;
printf("Client msg: \"%s\"\n", buf);
sprintf(reply, HTMLecho, buf); /* construct reply */
SSL_write(ssl, reply, strlen(reply)); /* send reply */
}
else
ERR_print_errors_fp(stderr);
}
sd = SSL_get_fd(ssl); /* get socket connection */
SSL_free(ssl); /* release SSL state */
close(sd); /* close connection */
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
char *portnum;
if(!isRoot())
{
printf("This program must be run as root/sudo user!!");
exit(0);
}
if ( count != 2 )
{
printf("Usage: %s <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();
portnum = strings[1];
ctx = InitServerCTX(); /* initialize SSL */
LoadCertificates(ctx, "mycert.pem", "mycert.pem"); /* load certs */
server = OpenListener(atoi(portnum)); /* create server socket */
while (1)
{ struct sockaddr_in addr;
socklen_t len = sizeof(addr);
SSL *ssl;
sleep(1200);
// sleep(12);
int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */
printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
//Wait before close connection to check max connections error
ssl = SSL_new(ctx); /* get new SSL state with context */
SSL_set_fd(ssl, client); /* set connection socket to SSL state */
Servlet(ssl); /* service connection */
}
close(server); /* close server socket */
SSL_CTX_free(ctx); /* release context */
}
SSL Client.c
//SSL-Client.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define FAIL -1
int OpenConnection(const char *hostname, int port)
{ int sd;
struct hostent *host;
struct sockaddr_in addr;
if ( (host = gethostbyname(hostname)) == NULL )
{
perror(hostname);
abort();
}
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
close(sd);
perror(hostname);
abort();
}
return sd;
}
SSL_CTX* InitCTX(void)
{ SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms(); /* Load cryptos, et.al. */
SSL_load_error_strings(); /* Bring in and register error messages */
method = SSLv3_client_method(); /* Create new client-method instance */
ctx = SSL_CTX_new(method); /* Create new context */
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
void ShowCerts(SSL* ssl)
{ X509 *cert;
char *line;
cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
if ( cert != NULL )
{
printf("Server certificates:\n");
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
printf("Subject: %s\n", line);
free(line); /* free the malloc'ed string */
line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
printf("Issuer: %s\n", line);
free(line); /* free the malloc'ed string */
X509_free(cert); /* free the malloc'ed certificate copy */
}
else
printf("No certificates.\n");
}
int main(int count, char *strings[])
{ SSL_CTX *ctx;
int server;
SSL *ssl;
char buf[1024];
int bytes;
char *hostname, *portnum;
if ( count != 3 )
{
printf("usage: %s <hostname> <portnum>\n", strings[0]);
exit(0);
}
SSL_library_init();
hostname=strings[1];
portnum=strings[2];
ctx = InitCTX();
server = OpenConnection(hostname, atoi(portnum));
ssl = SSL_new(ctx); /* create new SSL connection state */
SSL_set_fd(ssl, server); /* attach the socket descriptor */
if ( SSL_connect(ssl) == FAIL ) /* perform the connection */
ERR_print_errors_fp(stderr);
else
{ char *msg = "Hello???";
printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
ShowCerts(ssl); /* get any certs */
SSL_write(ssl, msg, strlen(msg)); /* encrypt & send message */
bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
buf[bytes] = 0;
printf("Received: \"%s\"\n", buf);
SSL_free(ssl); /* release connection state */
}
close(server); /* close socket */
SSL_CTX_free(ctx); /* release context */
return 0;
}
EDIT: Below is the Retransmission Message from the Wireshark log, SSL-Server is running on X.X.X.241, Client is on X.X.X.242
5 0.206404000 X.X.X.242 X.X.X.241 SSL 363 [TCP Retransmission] Client Hello
Your delay is added before accept not before SSL_accept. At this stage the tcp 3-way handshake has not completed, and therefore the SSL/TLS layer has not even started. What will be happening is the client will be sending a SYN packet, and the server responding only after a delay with an ACK packet. My recollection is the default is 5 SYN packet retries over 20 seconds; I can't immediately explain why you are seeing more than that, but it may be because you are attempting to acknowledge a SYN which itself has been replaced. The knob to adjust this is net.ipv4.tcp_syn_retries not tcp_retries2, and it needs to be adjusted on the client not the server.
There is no such thing (to my knowledge) as a 'TCP Hello Transmission'; that would seem to be a poor message client side. Perhaps the same routing opens the TCP connection and sends the SSL handshake.