0eb8e92c0cea55f6bcf1b88e570e8fefb2bdb78f
[openssl.git] / demos / state_machine / state_machine.c
1 /* ====================================================================
2  * Copyright (c) 2000 The OpenSSL Project.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the OpenSSL Project
19  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
20  *
21  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    openssl-core@openssl.org.
25  *
26  * 5. Products derived from this software may not be called "OpenSSL"
27  *    nor may "OpenSSL" appear in their names without prior written
28  *    permission of the OpenSSL Project.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the OpenSSL Project
33  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This product includes cryptographic software written by Eric Young
50  * (eay@cryptsoft.com).  This product includes software written by Tim
51  * Hudson (tjh@cryptsoft.com).
52  *
53  */
54
55 /*
56  * Nuron, a leader in hardware encryption technology, generously
57  * sponsored the development of this demo by Ben Laurie.
58  *
59  * See http://www.nuron.com/.
60  */
61
62 /*
63  * the aim of this demo is to provide a fully working state-machine
64  * style SSL implementation, i.e. one where the main loop acquires
65  * some data, then converts it from or to SSL by feeding it into the
66  * SSL state machine. It then does any I/O required by the state machine
67  * and loops.
68  *
69  * In order to keep things as simple as possible, this implementation
70  * listens on a TCP socket, which it expects to get an SSL connection
71  * on (for example, from s_client) and from then on writes decrypted
72  * data to stdout and encrypts anything arriving on stdin. Verbose
73  * commentary is written to stderr.
74  *
75  * This implementation acts as a server, but it can also be done for a client.  */
76
77 #include <openssl/ssl.h>
78 #include <assert.h>
79 #include <unistd.h>
80 #include <string.h>
81 #include <openssl/err.h>
82 #include <sys/types.h>
83 #include <sys/socket.h>
84 #include <netinet/in.h>
85
86 /* die_unless is intended to work like assert, except that it happens
87    always, even if NDEBUG is defined. Use assert as a stopgap. */
88
89 #define die_unless(x)   assert(x)
90
91 typedef struct
92     {
93     SSL_CTX *pCtx;
94     BIO *pbioRead;
95     BIO *pbioWrite;
96     SSL *pSSL;
97     } SSLStateMachine;
98
99 void SSLStateMachine_print_error(SSLStateMachine *pMachine,const char *szErr)
100     {
101     unsigned long l;
102
103     fprintf(stderr,"%s\n",szErr);
104     while((l=ERR_get_error()))
105         {
106         char buf[1024];
107
108         ERR_error_string_n(l,buf,sizeof buf);
109         fprintf(stderr,"Error %lx: %s\n",l,buf);
110         }
111     }
112
113 SSLStateMachine *SSLStateMachine_new(const char *szCertificateFile,
114                                      const char *szKeyFile)
115     {
116     SSLStateMachine *pMachine=malloc(sizeof *pMachine);
117     int n;
118
119     die_unless(pMachine);
120
121     pMachine->pCtx=SSL_CTX_new(SSLv23_server_method());
122     die_unless(pMachine->pCtx);
123
124     n=SSL_CTX_use_certificate_file(pMachine->pCtx,szCertificateFile,
125                                    SSL_FILETYPE_PEM);
126     die_unless(n > 0);
127
128     n=SSL_CTX_use_PrivateKey_file(pMachine->pCtx,szKeyFile,SSL_FILETYPE_PEM);
129     die_unless(n > 0);
130
131     pMachine->pSSL=SSL_new(pMachine->pCtx);
132     die_unless(pMachine->pSSL);
133
134     pMachine->pbioRead=BIO_new(BIO_s_mem());
135     /* Set EOF to return 0 (-1 is the default) */
136     BIO_ctrl(pMachine->pbioRead,BIO_C_SET_BUF_MEM_EOF_RETURN,0,NULL);
137
138     pMachine->pbioWrite=BIO_new(BIO_s_mem());
139
140     SSL_set_bio(pMachine->pSSL,pMachine->pbioRead,pMachine->pbioWrite);
141
142     SSL_set_accept_state(pMachine->pSSL);
143
144     return pMachine;
145     }
146
147 void SSLStateMachine_read_inject(SSLStateMachine *pMachine,
148                                  const unsigned char *aucBuf,int nBuf)
149     {
150     int n=BIO_write(pMachine->pbioRead,aucBuf,nBuf);
151     /* If it turns out this assert fails, then buffer the data here
152      * and just feed it in in churn instead. Seems to me that it
153      * should be guaranteed to succeed, though.
154      */
155     assert(n == nBuf);
156     fprintf(stderr,"%d bytes of encrypted data fed to state machine\n",n);
157     }
158
159 int SSLStateMachine_read_extract(SSLStateMachine *pMachine,
160                                  unsigned char *aucBuf,int nBuf)
161     {
162     int n;
163
164     if(!SSL_is_init_finished(pMachine->pSSL))
165         {
166         fprintf(stderr,"Doing SSL_accept\n");
167         n=SSL_accept(pMachine->pSSL);
168         if(n < 0)
169             SSLStateMachine_print_error(pMachine,"SSL_accept failed");
170         if(n == 0)
171             fprintf(stderr,"SSL_accept returned zero\n");
172         assert(n >= 0);
173         return 0;
174         }
175
176     n=SSL_read(pMachine->pSSL,aucBuf,nBuf);
177     fprintf(stderr,"%d bytes of decrypted data read from state machine\n",n);
178     return n;
179     }
180
181 int SSLStateMachine_write_can_extract(SSLStateMachine *pMachine)
182     {
183     int n=BIO_pending(pMachine->pbioWrite);
184     if(n)
185         fprintf(stderr,"There is encrypted data available to write\n");
186     else
187         fprintf(stderr,"There is no encrypted data available to write\n");
188
189     return n;
190     }
191
192 int SSLStateMachine_write_extract(SSLStateMachine *pMachine,
193                                   unsigned char *aucBuf,int nBuf)
194     {
195     int n;
196
197     n=BIO_read(pMachine->pbioWrite,aucBuf,nBuf);
198     fprintf(stderr,"%d bytes of encrypted data read from state machine\n",n);
199     return n;
200     }
201
202 void SSLStateMachine_write_inject(SSLStateMachine *pMachine,
203                                   const unsigned char *aucBuf,int nBuf)
204     {
205     int n=SSL_write(pMachine->pSSL,aucBuf,nBuf);
206     /* If it turns out this assert fails, then buffer the data here
207      * and just feed it in in churn instead. Seems to me that it
208      * should be guaranteed to succeed, though.
209      */
210     assert(n == nBuf);
211     fprintf(stderr,"%d bytes of unencrypted data fed to state machine\n",n);
212     }
213
214 int OpenSocket(int nPort)
215     {
216     int nSocket;
217     struct sockaddr_in saServer;
218     struct sockaddr_in saClient;
219     int one=1;
220     int nSize;
221     int nFD;
222     int nLen;
223
224     nSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
225     if(nSocket < 0)
226         {
227         perror("socket");
228         exit(1);
229         }
230
231     if(setsockopt(nSocket,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof one) < 0)
232         {
233         perror("setsockopt");
234         exit(2);
235         }
236
237     memset(&saServer,0,sizeof saServer);
238     saServer.sin_family=AF_INET;
239     saServer.sin_port=htons(nPort);
240     nSize=sizeof saServer;
241     if(bind(nSocket,(struct sockaddr *)&saServer,nSize) < 0)
242         {
243         perror("bind");
244         exit(3);
245         }
246
247     if(listen(nSocket,512) < 0)
248         {
249         perror("listen");
250         exit(4);
251         }
252
253     nLen=sizeof saClient;
254     nFD=accept(nSocket,(struct sockaddr *)&saClient,&nLen);
255     if(nFD < 0)
256         {
257         perror("accept");
258         exit(5);
259         }
260
261     fprintf(stderr,"Incoming accepted on port %d\n",nPort);
262
263     return nFD;
264     }
265
266 int main(int argc,char **argv)
267     {
268     SSLStateMachine *pMachine;
269     int nPort;
270     int nFD;
271     const char *szCertificateFile;
272     const char *szKeyFile;
273
274     if(argc != 4)
275         {
276         fprintf(stderr,"%s <port> <certificate file> <key file>\n",argv[0]);
277         exit(6);
278         }
279
280     nPort=atoi(argv[1]);
281     szCertificateFile=argv[2];
282     szKeyFile=argv[3];
283
284     SSL_library_init();
285     OpenSSL_add_ssl_algorithms();
286     SSL_load_error_strings();
287     ERR_load_crypto_strings();
288
289     nFD=OpenSocket(nPort);
290
291     pMachine=SSLStateMachine_new(szCertificateFile,szKeyFile);
292
293     for( ; ; )
294         {
295         fd_set rfds,wfds;
296         unsigned char buf[1024];
297         int n;
298
299         FD_ZERO(&rfds);
300         FD_ZERO(&wfds);
301
302         /* Select socket for input */
303         FD_SET(nFD,&rfds);
304
305         /* Select socket for output */
306         if(SSLStateMachine_write_can_extract(pMachine))
307             FD_SET(nFD,&wfds);
308
309         /* Select stdin for input */
310         FD_SET(0,&rfds);
311
312         /* Wait for something to do something */
313         n=select(nFD+1,&rfds,&wfds,NULL,NULL);
314         assert(n > 0);
315
316         /* Socket is ready for input */
317         if(FD_ISSET(nFD,&rfds))
318             {
319             n=read(nFD,buf,sizeof buf);
320             if(n == 0)
321                 {
322                 fprintf(stderr,"Got EOF on socket\n");
323                 exit(0);
324                 }
325             assert(n > 0);
326
327             SSLStateMachine_read_inject(pMachine,buf,n);
328             }
329
330         /* FIXME: we should only extract if stdout is ready */
331         n=SSLStateMachine_read_extract(pMachine,buf,n);
332         if(n < 0)
333             {
334             SSLStateMachine_print_error(pMachine,"read extract failed");
335             break;
336             }
337         assert(n >= 0);
338         if(n > 0)
339             {
340             int w;
341
342             w=write(1,buf,n);
343             /* FIXME: we should push back any unwritten data */
344             assert(w == n);
345             }
346
347         /* Socket is ready for output (and therefore we have output to send) */
348         if(FD_ISSET(nFD,&wfds))
349             {
350             int w;
351
352             n=SSLStateMachine_write_extract(pMachine,buf,sizeof buf);
353             assert(n > 0);
354
355             w=write(nFD,buf,n);
356             /* FIXME: we should push back any unwritten data */
357             assert(w == n);
358             }
359
360         /* Stdin is ready for input */
361         if(FD_ISSET(0,&rfds))
362             {
363             n=read(0,buf,sizeof buf);
364             if(n == 0)
365                 {
366                 fprintf(stderr,"Got EOF on stdin\n");
367                 exit(0);
368                 }
369             assert(n > 0);
370
371             SSLStateMachine_write_inject(pMachine,buf,n);
372             }
373         }
374     /* not reached */
375     return 0;
376     }