SSL/TLS协议和Openssl

SSL/TLS是为了通信安全考虑,在网络传输层和应用层之间加了一层协议。早期的协议版本叫做SSL,后期的版本叫做TLS。

版本对应关系

SSL是以前的名字,现在叫TLS比较合适,如果非要把两个名字对应起来,可以如下:

协议层实现

TLS协议层是一套Web标准,所有的应用层报文按照这个通信标准来做,就能够保证安全的通信。

对TLS协议层一个常用的开源实现就是Openssl。这是一个开源程序库,引入这个库,就可以方便的让自己工程的应用层通信建立在TLS标准之上。而不用去顾及TLS协议中的各种加密、电子签名等细节,直接让自己的应用层数据在TLS上传输。

使用Openssl的一般过程

初始化工作
客户端和服务器端很类似。
#include <openssl/ssl.h>
int SSL_library_init(void);


创建SSL会话
#include <openssl/ssl.h>
SSL_CTX *SSL_CTX_new(const SSL_METHOD *method);   //输入是SSL_METHOD结构体,输出是SSL_CTX
// 证书和私钥是要导入到SSL_CTX会话结构中
int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); //从文件载入证书,type可以是SSL_FILETYPE_PEM.
int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); //从文件载入私钥,type可以是SSL_FILETYPE_PEM.
int SSL_CTX_check_private_key(const SSL_CTX *ctx); // 自己验证一下私钥和证书是否配套。


创建SSL套接字对象
#include <openssl/ssl.h>
SSL *SSL_new(SSL_CTX *ctx);


SSL套接字和传输层的套接字绑定起来
注意,是完成三次握手之后的已连接套接字,而不是监听套接字。
#include <openssl/ssl.h>
int SSL_set_fd(SSL *ssl, int fd);
int SSL_set_rfd(SSL *ssl, int fd);
int SSL_set_wfd(SSL *ssl, int fd);


完成SSL握手
#include <openssl/ssl.h>
int SSL_connect(SSL *ssl);  //客户端调用这个发起连接
int SSL_accept(SSL *ssl);  //服务器端调用这个等待连接


握手过程完成之后,通常需要询问通信双方的证书信息,以便进行相应的验证。
X509 *SSL_get_peer_certificate(const SSL *ssl); // 从SSL结构体中提取出对方的证书 ( 此时证书得到且已经验证过了 ) 整理成 X509 结构。


SSL通信
#include <openssl/ssl.h>
int SSL_read(SSL *ssl, void *buf, int num);
int SSL_write(SSL *ssl, const void *buf, int num);


SSL断开连接
#include <openssl/ssl.h>
int SSL_shutdown(SSL *ssl);   //关闭连接
void SSL_free(SSL *ssl); //释放SSL套接字对象
void SSL_CTX_free(SSL_CTX *ctx); //释放SSL会话环境

Openssl使用样例

服务器端例子

#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 isRoot()
{
	if (getuid() != 0)
		return 0;
	else
		return 1;
}

SSL_CTX* InitServerCTX(void)
{   const SSL_METHOD *method;
	SSL_CTX *ctx;

	OpenSSL_add_all_algorithms();  /* load & register all cryptos, etc. */
	SSL_load_error_strings();   /* load all error messages */
	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();
	}
	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 ) // loads the first certificate stored in file into ctx
	{
		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();
	}
}

// TCP initial
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;
}

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); //the subject name of certificate x
		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 connection socket that relates to this SSL*/
	SSL_free(ssl);         /* release SSL state */
	close(sd);          /* close connection socket*/
}

int main(int count, char *strings[])
{   SSL_CTX *ctx;
	int server; // TCP socket fd
	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(); // do initialization

	portnum = strings[1];
	ctx = InitServerCTX();        /* initialize SSL */
	LoadCertificates(ctx, "lu.pem", "lu.pem"); /* load certs */
	server = OpenListener(atoi(portnum));    /* create server socket */
	while (1)
	{   struct sockaddr_in addr;
		socklen_t len = sizeof(addr);
		SSL *ssl; // SSL socket fd

		int client = accept(server, (struct sockaddr*)&addr, &len);  // new socket fd for connection
		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 */
}

客户端例子

#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

SSL_CTX* InitCTX(void)
{   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 = TLSv1_2_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;
}

// create TCP socket
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;
}


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();
	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 Lucky...";
		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;
}

编译上面的例子

all: server.c client.c
	gcc -Wall -o ssl-client client.c -L/usr/lib -lssl -lcrypto
	gcc -Wall -o ssl-server server.c -L/usr/lib -lssl -lcrypto

.PHONY: clean
clean:
	rm ssl-client ssl-server
*****
Written by Lu.dev on 23 March 2016