鱼塘

好多好多好多鱼

0%

C语言OpenSSL客户端编程

使用 C 语言基于 OpenSSL 的客户端程序。单向验证。

C语言OpenSSL客户端编程

基于OpenSSL编写的SSL客户端,单向验证

可以设置Client Hello包中的Servername

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
#include <errno.h>
#include "send.h"
#include "utils.h"

int u_alarm_handler()
{
printf_result(1, "connect timeout");
exit(0);
}

/*
* 发送数据:发送一次数据
*/
int send_tls_porbe(char *HOST, char *IP, uint16_t PORT, char *data, int data_len)
{
int sockfd, len;
struct sockaddr_in dest;
char buffer[BUFSIZE];
SSL_CTX *ctx;
SSL *ssl;

SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx == NULL)
{
ERR_print_errors_fp(stdout);
exit(1);
}

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket TLS Error");
exit(errno);
}

bzero(&dest, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(PORT);
if (inet_aton(IP, (struct in_addr *)&dest.sin_addr.s_addr) == 0)
{
perror(IP);
exit(errno);
}

//设置connect阻塞模式超时 15s
sigset(SIGALRM, u_alarm_handler);
alarm(CONNECT_TIMEOUT);

if (connect(sockfd, (struct sockaddr *)&dest, sizeof(dest)) != 0)
{
perror("Connect ");
exit(errno);
}

ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd);
/* 设置Client Hello的Servername*/
SSL_set_tlsext_host_name(ssl, HOST);
/* 建立 SSL 连接 */
if (SSL_connect(ssl) == -1)
ERR_print_errors_fp(stderr);

len = SSL_write(ssl, data, data_len);
if (len < 0)
printf("send failed %d '%s'\n", errno, strerror(errno));

struct timeval timeout = {RECV_TIMEOUT_TLS, 0};
int ret = setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
if (ret < 0)
{
printf_result(1, "setsockopt 1 error");
exit(1);
}

bzero(buffer, BUFSIZE);
len = SSL_read(ssl, buffer, BUFSIZE);

/* 关闭连接 */
SSL_shutdown(ssl);
SSL_free(ssl);
close(sockfd);
SSL_CTX_free(ctx);

if (len > 0)
{
int i;
for (i = 0; i < len; i++)
printf("%02x ", (uint8_t)buffer[i]);
printf("\n");
}
else if (len == 0)
{
printf("CUT_CONNECTED \n");
return CUT_CONNECTED;
}
else
{
printf("RECV TIMEOUT \n");
return RECV_TIME_OUT;
}
printf("RECV_DATA\n");
return RECV_DATA;
}