一个 SSL 客户端实例

源代码

/* ssl-test.c
 * Heiher <admin@heiher.info>
 */
 
#include <stdio.h>
#include <string.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
 
int main(int argc, char * argv[])
{
	BIO * bio = NULL;
	SSL * ssl = NULL;
	SSL_CTX * ctx = NULL;
	char buf[512];
	char * request = 
		"GET /sftp/ HTTP/1.1\r\n"
		"Host: www.heiher.info:443\r\n"
		"User-Agent: Mozilla/5.0 (X11; U; Linux mips64; en-US; rv:1.9.1.10)"
				" Gecko/20100623 Iceweasel/3.5.10 (like Firefox/3.5.10)\r\n"
		"Accept: text/html,application/xhtml+xml,application/xml;"
				"q=0.9,*/*;q=0.8\r\n"
		"Accept-Language: en-us,en;q=0.5\r\n"
		"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n"
		"Connection: close\r\n"
		"\r\n";
 
	/* ssl init */
	SSL_load_error_strings();
	ERR_load_BIO_strings();
	OpenSSL_add_all_algorithms();
 
	SSL_library_init();
 
	/* create ssl context */
	ctx = SSL_CTX_new(SSLv23_client_method());
	/* load the trust certificate store */
	if(!SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs"))
	{
		printf("load certs failed!\r\n");
	}
	/* create the connection */
	bio = BIO_new_ssl_connect(ctx);
	/* set up the BIO object */
	BIO_get_ssl(bio, &ssl);
	SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
 
	/* open a secure connection */
	BIO_set_conn_hostname(bio, "www.heiher.info:443");
	if(0 >= BIO_do_connect(bio))
	{
		printf("connect failed!\r\n");
		return -1;
	}
 
	if(X509_V_OK != SSL_get_verify_result(ssl))
	{
		/* print warning message */
	}
 
	/* send request message */
	if(0 >= BIO_write(bio, request, strlen(request)))
	{
		if(!BIO_should_retry(bio))
		{
			/* handle failed write here */
		}
		/* do something to handle the retry */
	}
 
	/* recv response message & print */
	while(1)
	{
		int len = BIO_read(bio, buf, 512);
 
		if(0 == len)
		{
			/* handle closed connection */
			break;
		}
		else if(0 >= len)
		{
			if(!BIO_should_retry(bio))
			{
				/* handle failed read here */
			}
			/* do something to handle the retry */
		}
		else
		{
			/* write to stdout */
			write(1, buf, len);
		}
	}
 
	/* free */
	BIO_free_all(bio);
	SSL_CTX_free(ctx);
 
	return 0;
}

编译命令

gcc `pkg-config --cflags --libs libssl` -o ssl-test ssl-test.c

Over!

Leave a Reply

Your email address will not be published. Required fields are marked *