1
/* cli.cpp - Minimal ssleay client for Unix
2
30.9.1996, Sampo Kellomaki <sampo@iki.fi> */
4
/* mangled to work with SSLeay-0.9.0b and OpenSSL 0.9.2b
5
Simplified to be even more minimal
6
12/98 - 4/99 Wade Scholine <wades@mail.cybg.com> */
11
#include <sys/types.h>
12
#include <sys/socket.h>
13
#include <netinet/in.h>
14
#include <arpa/inet.h>
17
#include <openssl/crypto.h>
18
#include <openssl/x509.h>
19
#include <openssl/pem.h>
20
#include <openssl/ssl.h>
21
#include <openssl/err.h>
24
#define CHK_NULL(x) if ((x)==NULL) exit (1)
25
#define CHK_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
26
#define CHK_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(2); }
32
struct sockaddr_in sa;
40
SSLeay_add_ssl_algorithms();
41
meth = SSLv2_client_method();
42
SSL_load_error_strings();
43
ctx = SSL_CTX_new (meth); CHK_NULL(ctx);
47
/* ----------------------------------------------- */
48
/* Create a socket and connect to server using normal socket calls. */
50
sd = socket (AF_INET, SOCK_STREAM, 0); CHK_ERR(sd, "socket");
52
memset (&sa, '\0', sizeof(sa));
53
sa.sin_family = AF_INET;
54
sa.sin_addr.s_addr = inet_addr ("127.0.0.1"); /* Server IP */
55
sa.sin_port = htons (1111); /* Server Port number */
57
err = connect(sd, (struct sockaddr*) &sa,
58
sizeof(sa)); CHK_ERR(err, "connect");
60
/* ----------------------------------------------- */
61
/* Now we have TCP conncetion. Start SSL negotiation. */
63
ssl = SSL_new (ctx); CHK_NULL(ssl);
65
err = SSL_connect (ssl); CHK_SSL(err);
67
/* Following two steps are optional and not required for
68
data exchange to be successful. */
70
/* Get the cipher - opt */
72
printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
74
/* Get server's certificate (note: beware of dynamic allocation) - opt */
76
server_cert = SSL_get_peer_certificate (ssl); CHK_NULL(server_cert);
77
printf ("Server certificate:\n");
79
str = X509_NAME_oneline (X509_get_subject_name (server_cert),0,0);
81
printf ("\t subject: %s\n", str);
84
str = X509_NAME_oneline (X509_get_issuer_name (server_cert),0,0);
86
printf ("\t issuer: %s\n", str);
89
/* We could do all sorts of certificate verification stuff here before
90
deallocating the certificate. */
92
X509_free (server_cert);
94
/* --------------------------------------------------- */
95
/* DATA EXCHANGE - Send a message and receive a reply. */
97
err = SSL_write (ssl, "Hello World!", strlen("Hello World!")); CHK_SSL(err);
99
err = SSL_read (ssl, buf, sizeof(buf) - 1); CHK_SSL(err);
101
printf ("Got %d chars:'%s'\n", err, buf);
102
SSL_shutdown (ssl); /* send SSL/TLS close_notify */