1 /* serv.cpp - Minimal ssleay server for Unix
2 30.9.1996, Sampo Kellomaki <sampo@iki.fi> */
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
13 #include "rsa.h" /* SSLeay stuff */
20 #define HOME "/usr/users/sampo/sibs/tim/"
21 #define CERTF HOME "plain-cert.pem"
22 #define KEYF HOME "plain-key.pem"
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); }
33 struct sockaddr_in sa_serv;
34 struct sockaddr_in sa_cli;
42 /* SSL preliminaries. We keep the certificate and key with the context. */
44 SSL_load_error_strings();
45 ctx = SSL_CTX_new (); CHK_NULL(ctx);
47 err = SSL_CTX_use_RSAPrivateKey_file (ctx, KEYF, SSL_FILETYPE_PEM);
50 err = SSL_CTX_use_certificate_file (ctx, CERTF, SSL_FILETYPE_PEM);
53 /* ----------------------------------------------- */
54 /* Prepare TCP socket for receiving connections */
56 listen_sd = socket (AF_INET, SOCK_STREAM, 0); CHK_ERR(listen_sd, "socket");
58 memset (&sa_serv, '\0', sizeof(sa_serv));
59 sa_serv.sin_family = AF_INET;
60 sa_serv.sin_addr.s_addr = INADDR_ANY;
61 sa_serv.sin_port = htons (1111); /* Server Port number */
63 err = bind(listen_sd, (struct sockaddr*) &sa_serv,
64 sizeof (sa_serv)); CHK_ERR(err, "bind");
66 /* Receive a TCP connection. */
68 err = listen (listen_sd, 5); CHK_ERR(err, "listen");
70 client_len = sizeof(sa_cli);
71 sd = accept (listen_sd, (struct sockaddr*) &sa_cli, &client_len);
72 CHK_ERR(sd, "accept");
75 printf ("Connection from %lx, port %x\n",
76 sa_cli.sin_addr.s_addr, sa_cli.sin_port);
78 /* ----------------------------------------------- */
79 /* TCP connection is ready. Do server side SSL. */
81 ssl = SSL_new (ctx); CHK_NULL(ssl);
83 err = SSL_accept (ssl); CHK_SSL(err);
85 /* Get the cipher - opt */
87 printf ("SSL connection using %s\n", SSL_get_cipher (ssl));
89 /* Get client's certificate (note: beware of dynamic allocation) - opt */
91 client_cert = SSL_get_peer_certificate (ssl);
92 if (client_cert != NULL) {
93 printf ("Client certificate:\n");
95 str = X509_NAME_oneline (X509_get_subject_name (client_cert));
97 printf ("\t subject: %s\n", str);
100 str = X509_NAME_oneline (X509_get_issuer_name (client_cert));
102 printf ("\t issuer: %s\n", str);
105 /* We could do all sorts of certificate verification stuff here before
106 deallocating the certificate. */
108 X509_free (client_cert);
110 printf ("Client does not have certificate.\n");
112 /* DATA EXCHANGE - Receive message and send reply. */
114 err = SSL_read (ssl, buf, sizeof(buf) - 1); CHK_SSL(err);
116 printf ("Got %d chars:'%s'\n", err, buf);
118 err = SSL_write (ssl, "I hear you.", strlen("I hear you.")); CHK_SSL(err);