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 "rsa.h" /* SSLeay stuff */
18 #include <openssl/crypto.h>
19 #include <openssl/x509.h>
20 #include <openssl/pem.h>
21 #include <openssl/ssl.h>
22 #include <openssl/err.h>
25 #define CHK_NULL(x) if ((x)==NULL) exit (1)
26 #define CHK_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
27 #define CHK_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(2); }
33 struct sockaddr_in sa;
41 SSLeay_add_ssl_algorithms();
42 meth = SSLv2_client_method();
43 SSL_load_error_strings();
44 ctx = SSL_CTX_new (meth); CHK_NULL(ctx);
48 /* ----------------------------------------------- */
49 /* Create a socket and connect to server using normal socket calls. */
51 sd = socket (AF_INET, SOCK_STREAM, 0); CHK_ERR(sd, "socket");
53 memset (&sa, '\0', sizeof(sa));
54 sa.sin_family = AF_INET;
55 sa.sin_addr.s_addr = inet_addr ("127.0.0.1"); /* Server IP */
56 sa.sin_port = htons (1111); /* Server Port number */
58 err = connect(sd, (struct sockaddr*) &sa,
59 sizeof(sa)); CHK_ERR(err, "connect");
61 /* ----------------------------------------------- */
62 /* Now we have TCP conncetion. Start SSL negotiation. */
64 ssl = SSL_new (ctx); CHK_NULL(ssl);
66 err = SSL_connect (ssl); CHK_SSL(err);
68 /* Following two steps are optional and not required for
69 data exchange to be successful. */
71 /* Get the cipher - opt */
73 printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
75 /* Get server's certificate (note: beware of dynamic allocation) - opt */
77 server_cert = SSL_get_peer_certificate (ssl); CHK_NULL(server_cert);
78 printf ("Server certificate:\n");
80 str = X509_NAME_oneline (X509_get_subject_name (server_cert),0,0);
82 printf ("\t subject: %s\n", str);
85 str = X509_NAME_oneline (X509_get_issuer_name (server_cert),0,0);
87 printf ("\t issuer: %s\n", str);
90 /* We could do all sorts of certificate verification stuff here before
91 deallocating the certificate. */
93 X509_free (server_cert);
95 /* --------------------------------------------------- */
96 /* DATA EXCHANGE - Send a message and receive a reply. */
98 err = SSL_write (ssl, "Hello World!", strlen("Hello World!")); CHK_SSL(err);
100 err = SSL_read (ssl, buf, sizeof(buf) - 1); CHK_SSL(err);
102 printf ("Got %d chars:'%s'\n", err, buf);
103 SSL_shutdown (ssl); /* send SSL/TLS close_notify */