]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - test_tls.c
MSVC: Ifdef GCC pragmas
[openssl-gost/engine.git] / test_tls.c
1 /*
2  * Simple Client/Server connection test
3  *
4  * Based on OpenSSL example code.
5  * Copyright (C) 2019 vt@altlinux.org. All Rights Reserved.
6  *
7  * Contents licensed under the terms of the OpenSSL license
8  * See https://www.openssl.org/source/license.html for details
9  */
10
11 #include "e_gost_err.h"
12 #include "gost_lcl.h"
13 #include <openssl/evp.h>
14 #include <openssl/ssl.h>
15 #include <openssl/bio.h>
16 #include <openssl/rand.h>
17 #include <openssl/err.h>
18 #include <openssl/asn1.h>
19 #include <openssl/obj_mac.h>
20 #include <openssl/x509v3.h>
21 #include <openssl/ec.h>
22 #include <openssl/bn.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <sys/wait.h>
27 #include <sys/types.h>
28 #include <signal.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32
33 #ifdef __GNUC__
34 /* For X509_NAME_add_entry_by_txt */
35 # pragma GCC diagnostic ignored "-Wpointer-sign"
36 #endif
37
38 #define T(e) ({ if (!(e)) { \
39                 ERR_print_errors_fp(stderr); \
40                 OpenSSLDie(__FILE__, __LINE__, #e); \
41             } \
42         })
43 #define TE(e) ({ if (!(e)) { \
44                 ERR_print_errors_fp(stderr); \
45                 fprintf(stderr, "Error at %s:%d %s\n", __FILE__, __LINE__, #e); \
46                 return -1; \
47             } \
48         })
49
50 #define cRED    "\033[1;31m"
51 #define cDRED   "\033[0;31m"
52 #define cGREEN  "\033[1;32m"
53 #define cDGREEN "\033[0;32m"
54 #define cBLUE   "\033[1;34m"
55 #define cDBLUE  "\033[0;34m"
56 #define cNORM   "\033[m"
57 #define TEST_ASSERT(e) {if ((test = (e))) \
58                  printf(cRED "  Test FAILED\n" cNORM); \
59              else \
60                  printf(cGREEN "  Test passed\n" cNORM);}
61
62 struct certkey {
63     EVP_PKEY *pkey;
64     X509 *cert;
65 };
66
67 static int verbose;
68 static const char *cipher_list;
69
70 /* How much K to transfer between client and server. */
71 #define KTRANSFER (1 * 1024)
72
73 static void err(int eval, const char *fmt, ...)
74 {
75     va_list ap;
76
77     va_start(ap, fmt);
78     vprintf(fmt, ap);
79     va_end(ap);
80     printf(": %s\n", strerror(errno));
81     exit(eval);
82 }
83
84 /*
85  * Simple TLS Server code is based on
86  * https://wiki.openssl.org/index.php/Simple_TLS_Server
87  */
88 static int s_server(EVP_PKEY *pkey, X509 *cert, int client)
89 {
90     SSL_CTX *ctx;
91     T(ctx = SSL_CTX_new(TLS_server_method()));
92     T(SSL_CTX_use_certificate(ctx, cert));
93     T(SSL_CTX_use_PrivateKey(ctx, pkey));
94     T(SSL_CTX_check_private_key(ctx));
95
96     SSL *ssl;
97     T(ssl = SSL_new(ctx));
98     T(SSL_set_fd(ssl, client));
99     if (cipher_list)
100         T(SSL_set_cipher_list(ssl, cipher_list));
101     T(SSL_accept(ssl) == 1);
102
103     /* Receive data from client */
104     char buf[1024];
105     int i;
106     for (i = 0; i < KTRANSFER; i++) {
107         int k;
108
109         T(SSL_read(ssl, buf, sizeof(buf)) == sizeof(buf));
110         for (k = 0; k < sizeof(buf); k++)
111             if (buf[k] != 'c')
112                 err(1, "corruption from client");
113     }
114     /* Send data to client. */
115     memset(buf, 's', sizeof(buf));
116     for (i = 0; i < KTRANSFER; i++) {
117         T(SSL_write(ssl, buf, sizeof(buf)) == sizeof(buf));
118     }
119     SSL_shutdown(ssl);
120     SSL_free(ssl);
121     close(client);
122
123     SSL_CTX_free(ctx);
124     return 0;
125 }
126
127 /*
128  * Simple TLC Client code is based on man BIO_f_ssl and
129  * https://wiki.openssl.org/index.php/SSL/TLS_Client
130  */
131 static int s_client(int server)
132 {
133     SSL_CTX *ctx;
134     T(ctx = SSL_CTX_new(TLS_client_method()));
135
136     BIO *sbio;
137     T(sbio = BIO_new_ssl_connect(ctx));
138     SSL *ssl;
139     T(BIO_get_ssl(sbio, &ssl));
140     T(SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY));
141     if (cipher_list)
142         T(SSL_set_cipher_list(ssl, cipher_list));
143 #if 0
144     /* Does not work with reneg. */
145     BIO_set_ssl_renegotiate_bytes(sbio, 100 * 1024);
146 #endif
147     T(SSL_set_fd(ssl, server));
148     T(BIO_do_handshake(sbio) == 1);
149
150     printf("Protocol: %s\n", SSL_get_version(ssl));
151     printf("Cipher:   %s\n", SSL_get_cipher_name(ssl));
152     if (verbose) {
153         SSL_SESSION *sess = SSL_get0_session(ssl);
154         SSL_SESSION_print_fp(stdout, sess);
155     }
156
157     X509 *cert;
158     T(cert = SSL_get_peer_certificate(ssl));
159     X509_free(cert);
160     int verify = SSL_get_verify_result(ssl);
161     printf("Verify:   %s\n", X509_verify_cert_error_string(verify));
162     if (verify != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
163         err(1, "invalid SSL_get_verify_result");
164
165     /* Send data to server. */
166     char buf[1024];
167     int i;
168     memset(buf, 'c', sizeof(buf));
169     for (i = 0; i < KTRANSFER; i++) {
170         T(BIO_write(sbio, buf, sizeof(buf)) == sizeof(buf));
171     }
172     (void)BIO_shutdown_wr(sbio);
173
174     /* Receive data from server. */
175     for (i = 0; i < KTRANSFER; i++) {
176         int k;
177         int n = BIO_read(sbio, buf, sizeof(buf));
178
179         if (n != sizeof(buf)) {
180             printf("i:%d BIO_read:%d SSL_get_error:%d\n", i, n,
181                 SSL_get_error(ssl, n));
182             ERR_print_errors_fp(stderr);
183             err(1, "BIO_read");
184         }
185
186         for (k = 0; k < sizeof(buf); k++)
187             if (buf[k] != 's')
188                 err(1, "corruption from server");
189     }
190
191     i = BIO_get_num_renegotiates(sbio);
192     if (i)
193         printf("Renegs:   %d\n", i);
194     BIO_free_all(sbio);
195     SSL_CTX_free(ctx);
196
197     return 0;
198 }
199
200 /* Generate simple cert+key pair. Based on req.c */
201 static struct certkey certgen(const char *algname, const char *paramset)
202 {
203     /* Keygen. */
204     EVP_PKEY *tkey;
205     T(tkey = EVP_PKEY_new());
206     T(EVP_PKEY_set_type_str(tkey, algname, strlen(algname)));
207     EVP_PKEY_CTX *ctx;
208     T(ctx = EVP_PKEY_CTX_new(tkey, NULL));
209     T(EVP_PKEY_keygen_init(ctx));
210     if (paramset)
211         T(EVP_PKEY_CTX_ctrl_str(ctx, "paramset", paramset));
212     EVP_PKEY *pkey = NULL;
213     T((EVP_PKEY_keygen(ctx, &pkey)) == 1);
214     EVP_PKEY_CTX_free(ctx);
215     EVP_PKEY_free(tkey);
216
217     /* REQ. */
218     X509_REQ *req = NULL;
219     T(req = X509_REQ_new());
220     T(X509_REQ_set_version(req, 0L));
221     X509_NAME *name;
222     T(name = X509_NAME_new());
223     T(X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, "Test CA", -1, -1, 0));
224     T(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, "Test Key", -1, -1, 0));
225     T(X509_REQ_set_subject_name(req, name));
226     T(X509_REQ_set_pubkey(req, pkey));
227     X509_NAME_free(name);
228
229     /* Cert. */
230     X509 *x509ss = NULL;
231     T(x509ss = X509_new());
232     T(X509_set_version(x509ss, 2));
233     BIGNUM *brnd = BN_new();
234     T(BN_rand(brnd, 20 * 8 - 1, -1, 0));
235     T(BN_to_ASN1_INTEGER(brnd, X509_get_serialNumber(x509ss)));
236     T(X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)));
237     T(X509_gmtime_adj(X509_getm_notBefore(x509ss), 0));
238     T(X509_time_adj_ex(X509_getm_notAfter(x509ss), 1, 0, NULL));
239     T(X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req)));
240     T(X509_set_pubkey(x509ss, X509_REQ_get0_pubkey(req)));
241     X509_REQ_free(req);
242     BN_free(brnd);
243
244     X509V3_CTX v3ctx;
245     X509V3_set_ctx_nodb(&v3ctx);
246     X509V3_set_ctx(&v3ctx, x509ss, x509ss, NULL, NULL, 0);
247     X509_EXTENSION *ext;
248     T(ext = X509V3_EXT_conf_nid(NULL, &v3ctx, NID_basic_constraints, "critical,CA:TRUE"));
249     T(X509_add_ext(x509ss, ext, 0));
250     X509_EXTENSION_free(ext);
251     T(ext = X509V3_EXT_conf_nid(NULL, &v3ctx, NID_subject_key_identifier, "hash"));
252     T(X509_add_ext(x509ss, ext, 1));
253     X509_EXTENSION_free(ext);
254     T(ext = X509V3_EXT_conf_nid(NULL, &v3ctx, NID_authority_key_identifier, "keyid:always,issuer"));
255     T(X509_add_ext(x509ss, ext, 2));
256     X509_EXTENSION_free(ext);
257
258     EVP_MD_CTX *mctx;
259     T(mctx = EVP_MD_CTX_new());
260     T(EVP_DigestSignInit(mctx, NULL, NULL, NULL, pkey));
261     T(X509_sign_ctx(x509ss, mctx));
262     EVP_MD_CTX_free(mctx);
263 #if 0
264     /* Print cert in text format. */
265     X509_print_fp(stdout, x509ss);
266 #endif
267 #if 0
268     /* Print cert in PEM format. */
269     BIO *out = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
270     PEM_write_bio_X509(out, x509ss);
271     BIO_free_all(out);
272 #endif
273     return (struct certkey){ .pkey = pkey, .cert = x509ss };
274 }
275
276 int test(const char *algname, const char *paramset)
277 {
278     int ret = 0;
279
280     printf(cBLUE "Test %s", algname);
281     if (paramset)
282         printf(cBLUE ":%s", paramset);
283     printf(cNORM "\n");
284
285     struct certkey ck;
286     ck = certgen(algname, paramset);
287
288     int sockfd[2];
289     if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfd) == -1)
290         err(1, "socketpair");
291
292     setpgid(0, 0);
293
294     /* Run server in separate process. */
295     pid_t server_pid = fork();
296     if (server_pid < 0)
297         err(1, "fork server");
298     if (server_pid == 0) {
299         ret = s_server(ck.pkey, ck.cert, sockfd[1]);
300         X509_free(ck.cert);
301         EVP_PKEY_free(ck.pkey);
302         exit(ret);
303     }
304
305     /* Run client in separate process. */
306     pid_t client_pid = fork();
307     if (client_pid < 0)
308         err(1, "fork client");
309     if (client_pid == 0) {
310         ret = s_client(sockfd[0]);
311         X509_free(ck.cert);
312         EVP_PKEY_free(ck.pkey);
313         exit(ret);
314     }
315
316     /* Wait for first child to exit. */
317     int status;
318     pid_t exited_pid = wait(&status);
319     ret = (WIFEXITED(status) && WEXITSTATUS(status)) ||
320         (WIFSIGNALED(status) && WTERMSIG(status));
321     if (ret) {
322         fprintf(stderr, cRED "%s child %s with %d %s" cNORM,
323             exited_pid == server_pid? "server" : "client",
324             WIFSIGNALED(status)? "killed" : "exited",
325             WIFSIGNALED(status)? WTERMSIG(status) : WEXITSTATUS(status),
326             WIFSIGNALED(status)? strsignal(WTERMSIG(status)) : "");
327
328         /* If first child exited with error, kill other. */
329         fprintf(stderr, "terminating %s by force",
330             exited_pid == server_pid? "client" : "server");
331         kill(exited_pid == server_pid? client_pid : server_pid, SIGTERM);
332     }
333
334     exited_pid = wait(&status);
335     /* Report error unless we killed it. */
336     if (!ret && (!WIFEXITED(status) || WEXITSTATUS(status)))
337         fprintf(stderr, cRED "%s child %s with %d %s" cNORM,
338             exited_pid == server_pid? "server" : "client",
339             WIFSIGNALED(status)? "killed" : "exited",
340             WIFSIGNALED(status)? WTERMSIG(status) : WEXITSTATUS(status),
341             WIFSIGNALED(status)? strsignal(WTERMSIG(status)) : "");
342     ret |= (WIFEXITED(status) && WEXITSTATUS(status)) ||
343         (WIFSIGNALED(status) && WTERMSIG(status));
344
345     /* Every responsible process should free this. */
346     X509_free(ck.cert);
347     EVP_PKEY_free(ck.pkey);
348 #ifdef __SANITIZE_ADDRESS__
349     /* Abort on the first (hopefully) ASan error. */
350     if (ret)
351         _exit(ret);
352 #endif
353     return ret;
354 }
355
356 int main(int argc, char **argv)
357 {
358     int ret = 0;
359
360     OPENSSL_add_all_algorithms_conf();
361
362     char *p;
363     if ((p = getenv("VERBOSE")))
364         verbose = atoi(p);
365
366     ret |= test("rsa", NULL);
367     cipher_list = "LEGACY-GOST2012-GOST8912-GOST8912";
368     ret |= test("gost2012_256", "A");
369     ret |= test("gost2012_256", "B");
370     ret |= test("gost2012_256", "C");
371     ret |= test("gost2012_256", "TCA");
372     ret |= test("gost2012_512", "A");
373     ret |= test("gost2012_512", "B");
374     ret |= test("gost2012_512", "C");
375
376     if (ret)
377         printf(cDRED "= Some tests FAILED!\n" cNORM);
378     else
379         printf(cDGREEN "= All tests passed!\n" cNORM);
380     return ret;
381 }