Add demo state machine.
[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 typedef struct
87     {
88     SSL_CTX *pCtx;
89     BIO *pbioRead;
90     BIO *pbioWrite;
91     SSL *pSSL;
92     } SSLStateMachine;
93
94 void SSLStateMachine_print_error(SSLStateMachine *pMachine,const char *szErr)
95     {
96     unsigned long l;
97
98     fprintf(stderr,"%s\n",szErr);
99     while((l=ERR_get_error()))
100         {
101         char buf[1024];
102
103         ERR_error_string_n(l,buf,sizeof buf);
104         fprintf(stderr,"Error %lx: %s\n",l,buf);
105         }
106     }
107
108 SSLStateMachine *SSLStateMachine_new(const char *szCertificateFile,
109                                      const char *szKeyFile)
110     {
111     SSLStateMachine *pMachine=malloc(sizeof *pMachine);
112     int n;
113
114     assert(pMachine);
115
116     pMachine->pCtx=SSL_CTX_new(SSLv23_server_method());
117     assert(pMachine->pCtx);
118
119     n=SSL_CTX_use_certificate_file(pMachine->pCtx,szCertificateFile,
120                                    SSL_FILETYPE_PEM);
121     assert(n > 0);
122
123     n=SSL_CTX_use_PrivateKey_file(pMachine->pCtx,szKeyFile,SSL_FILETYPE_PEM);
124     assert(n > 0);
125
126     pMachine->pSSL=SSL_new(pMachine->pCtx);
127     assert(pMachine->pSSL);
128
129     pMachine->pbioRead=BIO_new(BIO_s_mem());
130     /* Set EOF to return 0 (-1 is the default) */
131     BIO_ctrl(pMachine->pbioRead,BIO_C_SET_BUF_MEM_EOF_RETURN,0,NULL);
132
133     pMachine->pbioWrite=BIO_new(BIO_s_mem());
134
135     SSL_set_bio(pMachine->pSSL,pMachine->pbioRead,pMachine->pbioWrite);
136
137     SSL_set_accept_state(pMachine->pSSL);
138
139     return pMachine;
140     }
141
142 void SSLStateMachine_read_inject(SSLStateMachine *pMachine,
143                                  const unsigned char *aucBuf,int nBuf)
144     {
145     int n=BIO_write(pMachine->pbioRead,aucBuf,nBuf);
146     /* If it turns out this assert fails, then buffer the data here
147      * and just feed it in in churn instead. Seems to me that it
148      * should be guaranteed to succeed, though.
149      */
150     assert(n == nBuf);
151     fprintf(stderr,"%d bytes of encrypted data fed to state machine\n",n);
152     }
153
154 int SSLStateMachine_read_extract(SSLStateMachine *pMachine,
155                                  unsigned char *aucBuf,int nBuf)
156     {
157     int n;
158
159     if(!SSL_is_init_finished(pMachine->pSSL))
160         {
161         fprintf(stderr,"Doing SSL_accept\n");
162         n=SSL_accept(pMachine->pSSL);
163         if(n < 0)
164             SSLStateMachine_print_error(pMachine,"SSL_accept failed");
165         if(n == 0)
166             fprintf(stderr,"SSL_accept returned zero\n");
167         assert(n >= 0);
168         return 0;
169         }
170
171     n=SSL_read(pMachine->pSSL,aucBuf,nBuf);
172     fprintf(stderr,"%d bytes of decrypted data read from state machine\n",n);
173     return n;
174     }
175
176 int SSLStateMachine_write_can_extract(SSLStateMachine *pMachine)
177     {
178     int n=BIO_pending(pMachine->pbioWrite);
179     if(n)
180         fprintf(stderr,"There is encrypted data available to write\n");
181     else
182         fprintf(stderr,"There is no encrypted data available to write\n");
183
184     return n;
185     }
186
187 int SSLStateMachine_write_extract(SSLStateMachine *pMachine,
188                                   unsigned char *aucBuf,int nBuf)
189     {
190     int n;
191
192     n=BIO_read(pMachine->pbioWrite,aucBuf,nBuf);
193     fprintf(stderr,"%d bytes of encrypted data read from state machine\n",n);
194     return n;
195     }
196
197 void SSLStateMachine_write_inject(SSLStateMachine *pMachine,
198                                   const unsigned char *aucBuf,int nBuf)
199     {
200     int n=SSL_write(pMachine->pSSL,aucBuf,nBuf);
201     /* If it turns out this assert fails, then buffer the data here
202      * and just feed it in in churn instead. Seems to me that it
203      * should be guaranteed to succeed, though.
204      */
205     assert(n == nBuf);
206     fprintf(stderr,"%d bytes of unencrypted data fed to state machine\n",n);
207     }
208
209 int OpenSocket(int nPort)
210     {
211     int nSocket;
212     struct sockaddr_in saServer;
213     struct sockaddr_in saClient;
214     int one=1;
215     int nSize;
216     int nFD;
217     int nLen;
218
219     nSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
220     if(nSocket < 0)
221         {
222         perror("socket");
223         exit(1);
224         }
225
226     if(setsockopt(nSocket,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof one) < 0)
227         {
228         perror("setsockopt");
229         exit(2);
230         }
231
232     memset(&saServer,0,sizeof saServer);
233     saServer.sin_family=AF_INET;
234     saServer.sin_port=htons(nPort);
235     nSize=sizeof saServer;
236     if(bind(nSocket,(struct sockaddr *)&saServer,nSize) < 0)
237         {
238         perror("bind");
239         exit(3);
240         }
241
242     if(listen(nSocket,512) < 0)
243         {
244         perror("listen");
245         exit(4);
246         }
247
248     nLen=sizeof saClient;
249     nFD=accept(nSocket,(struct sockaddr *)&saClient,&nLen);
250     if(nFD < 0)
251         {
252         perror("accept");
253         exit(5);
254         }
255
256     fprintf(stderr,"Incoming accepted on port %d\n",nPort);
257
258     return nFD;
259     }
260
261 void main(int argc,char **argv)
262     {
263     SSLStateMachine *pMachine;
264     int nPort;
265     int nFD;
266     const char *szCertificateFile;
267     const char *szKeyFile;
268
269     if(argc != 4)
270         {
271         fprintf(stderr,"%s <port> <certificate file> <key file>\n",argv[0]);
272         exit(6);
273         }
274
275     nPort=atoi(argv[1]);
276     szCertificateFile=argv[2];
277     szKeyFile=argv[3];
278
279     SSL_library_init();
280     OpenSSL_add_ssl_algorithms();
281     SSL_load_error_strings();
282     ERR_load_crypto_strings();
283
284     nFD=OpenSocket(nPort);
285
286     pMachine=SSLStateMachine_new(szCertificateFile,szKeyFile);
287
288     for( ; ; )
289         {
290         fd_set rfds,wfds;
291         unsigned char buf[1024];
292         int n;
293
294         FD_ZERO(&rfds);
295         FD_ZERO(&wfds);
296
297         /* Select socket for input */
298         FD_SET(nFD,&rfds);
299
300         /* Select socket for output */
301         if(SSLStateMachine_write_can_extract(pMachine))
302             FD_SET(nFD,&wfds);
303
304         /* Select stdin for input */
305         FD_SET(0,&rfds);
306
307         /* Wait for something to do something */
308         n=select(nFD+1,&rfds,&wfds,NULL,NULL);
309         assert(n > 0);
310
311         /* Socket is ready for input */
312         if(FD_ISSET(nFD,&rfds))
313             {
314             n=read(nFD,buf,sizeof buf);
315             if(n == 0)
316                 {
317                 fprintf(stderr,"Got EOF on socket\n");
318                 exit(0);
319                 }
320             assert(n > 0);
321
322             SSLStateMachine_read_inject(pMachine,buf,n);
323             }
324
325         /* FIXME: we should only extract if stdout is ready */
326         n=SSLStateMachine_read_extract(pMachine,buf,n);
327         if(n < 0)
328             {
329             SSLStateMachine_print_error(pMachine,"read extract failed");
330             break;
331             }
332         assert(n >= 0);
333         if(n > 0)
334             {
335             int w;
336
337             w=write(1,buf,n);
338             /* FIXME: we should push back any unwritten data */
339             assert(w == n);
340             }
341
342         /* Socket is ready for output (and therefore we have output to send) */
343         if(FD_ISSET(nFD,&wfds))
344             {
345             int w;
346
347             n=SSLStateMachine_write_extract(pMachine,buf,sizeof buf);
348             assert(n > 0);
349
350             w=write(nFD,buf,n);
351             /* FIXME: we should push back any unwritten data */
352             assert(w == n);
353             }
354
355         /* Stdin is ready for input */
356         if(FD_ISSET(0,&rfds))
357             {
358             n=read(0,buf,sizeof buf);
359             if(n == 0)
360                 {
361                 fprintf(stderr,"Got EOF on stdin\n");
362                 exit(0);
363                 }
364             assert(n > 0);
365
366             SSLStateMachine_write_inject(pMachine,buf,n);
367             }
368         }
369     }