state_machine.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. * Nuron, a leader in hardware encryption technology, generously
  56. * sponsored the development of this demo by Ben Laurie.
  57. *
  58. * See http://www.nuron.com/.
  59. */
  60. /*
  61. * the aim of this demo is to provide a fully working state-machine
  62. * style SSL implementation, i.e. one where the main loop acquires
  63. * some data, then converts it from or to SSL by feeding it into the
  64. * SSL state machine. It then does any I/O required by the state machine
  65. * and loops.
  66. *
  67. * In order to keep things as simple as possible, this implementation
  68. * listens on a TCP socket, which it expects to get an SSL connection
  69. * on (for example, from s_client) and from then on writes decrypted
  70. * data to stdout and encrypts anything arriving on stdin. Verbose
  71. * commentary is written to stderr.
  72. *
  73. * This implementation acts as a server, but it can also be done for a client. */
  74. #include <openssl/ssl.h>
  75. #include <assert.h>
  76. #include <unistd.h>
  77. #include <string.h>
  78. #include <openssl/err.h>
  79. #include <sys/types.h>
  80. #include <sys/socket.h>
  81. #include <netinet/in.h>
  82. /*
  83. * die_unless is intended to work like assert, except that it happens always,
  84. * even if NDEBUG is defined. Use assert as a stopgap.
  85. */
  86. #define die_unless(x) assert(x)
  87. typedef struct {
  88. SSL_CTX *pCtx;
  89. BIO *pbioRead;
  90. BIO *pbioWrite;
  91. SSL *pSSL;
  92. } SSLStateMachine;
  93. void SSLStateMachine_print_error(SSLStateMachine * pMachine,
  94. const char *szErr)
  95. {
  96. unsigned long l;
  97. fprintf(stderr, "%s\n", szErr);
  98. while ((l = ERR_get_error())) {
  99. char buf[1024];
  100. ERR_error_string_n(l, buf, sizeof(buf));
  101. fprintf(stderr, "Error %lx: %s\n", l, buf);
  102. }
  103. }
  104. SSLStateMachine *SSLStateMachine_new(const char *szCertificateFile,
  105. const char *szKeyFile)
  106. {
  107. SSLStateMachine *pMachine = malloc(sizeof(*pMachine));
  108. int n;
  109. die_unless(pMachine);
  110. pMachine->pCtx = SSL_CTX_new(SSLv23_server_method());
  111. die_unless(pMachine->pCtx);
  112. n = SSL_CTX_use_certificate_file(pMachine->pCtx, szCertificateFile,
  113. SSL_FILETYPE_PEM);
  114. die_unless(n > 0);
  115. n = SSL_CTX_use_PrivateKey_file(pMachine->pCtx, szKeyFile,
  116. SSL_FILETYPE_PEM);
  117. die_unless(n > 0);
  118. pMachine->pSSL = SSL_new(pMachine->pCtx);
  119. die_unless(pMachine->pSSL);
  120. pMachine->pbioRead = BIO_new(BIO_s_mem());
  121. pMachine->pbioWrite = BIO_new(BIO_s_mem());
  122. SSL_set_bio(pMachine->pSSL, pMachine->pbioRead, pMachine->pbioWrite);
  123. SSL_set_accept_state(pMachine->pSSL);
  124. return pMachine;
  125. }
  126. void SSLStateMachine_read_inject(SSLStateMachine * pMachine,
  127. const unsigned char *aucBuf, int nBuf)
  128. {
  129. int n = BIO_write(pMachine->pbioRead, aucBuf, nBuf);
  130. /*
  131. * If it turns out this assert fails, then buffer the data here and just
  132. * feed it in in churn instead. Seems to me that it should be guaranteed
  133. * to succeed, though.
  134. */
  135. assert(n == nBuf);
  136. fprintf(stderr, "%d bytes of encrypted data fed to state machine\n", n);
  137. }
  138. int SSLStateMachine_read_extract(SSLStateMachine * pMachine,
  139. unsigned char *aucBuf, int nBuf)
  140. {
  141. int n;
  142. if (!SSL_is_init_finished(pMachine->pSSL)) {
  143. fprintf(stderr, "Doing SSL_accept\n");
  144. n = SSL_accept(pMachine->pSSL);
  145. if (n == 0)
  146. fprintf(stderr, "SSL_accept returned zero\n");
  147. if (n < 0) {
  148. int err;
  149. if ((err =
  150. SSL_get_error(pMachine->pSSL, n)) == SSL_ERROR_WANT_READ) {
  151. fprintf(stderr, "SSL_accept wants more data\n");
  152. return 0;
  153. }
  154. SSLStateMachine_print_error(pMachine, "SSL_accept error");
  155. exit(7);
  156. }
  157. return 0;
  158. }
  159. n = SSL_read(pMachine->pSSL, aucBuf, nBuf);
  160. if (n < 0) {
  161. int err = SSL_get_error(pMachine->pSSL, n);
  162. if (err == SSL_ERROR_WANT_READ) {
  163. fprintf(stderr, "SSL_read wants more data\n");
  164. return 0;
  165. }
  166. SSLStateMachine_print_error(pMachine, "SSL_read error");
  167. exit(8);
  168. }
  169. fprintf(stderr, "%d bytes of decrypted data read from state machine\n",
  170. n);
  171. return n;
  172. }
  173. int SSLStateMachine_write_can_extract(SSLStateMachine * pMachine)
  174. {
  175. int n = BIO_pending(pMachine->pbioWrite);
  176. if (n)
  177. fprintf(stderr, "There is encrypted data available to write\n");
  178. else
  179. fprintf(stderr, "There is no encrypted data available to write\n");
  180. return n;
  181. }
  182. int SSLStateMachine_write_extract(SSLStateMachine * pMachine,
  183. unsigned char *aucBuf, int nBuf)
  184. {
  185. int n;
  186. n = BIO_read(pMachine->pbioWrite, aucBuf, nBuf);
  187. fprintf(stderr, "%d bytes of encrypted data read from state machine\n",
  188. n);
  189. return n;
  190. }
  191. void SSLStateMachine_write_inject(SSLStateMachine * pMachine,
  192. const unsigned char *aucBuf, int nBuf)
  193. {
  194. int n = SSL_write(pMachine->pSSL, aucBuf, nBuf);
  195. /*
  196. * If it turns out this assert fails, then buffer the data here and just
  197. * feed it in in churn instead. Seems to me that it should be guaranteed
  198. * to succeed, though.
  199. */
  200. assert(n == nBuf);
  201. fprintf(stderr, "%d bytes of unencrypted data fed to state machine\n", n);
  202. }
  203. int OpenSocket(int nPort)
  204. {
  205. int nSocket;
  206. struct sockaddr_in saServer;
  207. struct sockaddr_in saClient;
  208. int one = 1;
  209. int nSize;
  210. int nFD;
  211. int nLen;
  212. nSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  213. if (nSocket < 0) {
  214. perror("socket");
  215. exit(1);
  216. }
  217. if (setsockopt
  218. (nSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)) < 0) {
  219. perror("setsockopt");
  220. exit(2);
  221. }
  222. memset(&saServer, 0, sizeof(saServer));
  223. saServer.sin_family = AF_INET;
  224. saServer.sin_port = htons(nPort);
  225. nSize = sizeof(saServer);
  226. if (bind(nSocket, (struct sockaddr *)&saServer, nSize) < 0) {
  227. perror("bind");
  228. exit(3);
  229. }
  230. if (listen(nSocket, 512) < 0) {
  231. perror("listen");
  232. exit(4);
  233. }
  234. nLen = sizeof(saClient);
  235. nFD = accept(nSocket, (struct sockaddr *)&saClient, &nLen);
  236. if (nFD < 0) {
  237. perror("accept");
  238. exit(5);
  239. }
  240. fprintf(stderr, "Incoming accepted on port %d\n", nPort);
  241. return nFD;
  242. }
  243. int main(int argc, char **argv)
  244. {
  245. SSLStateMachine *pMachine;
  246. int nPort;
  247. int nFD;
  248. const char *szCertificateFile;
  249. const char *szKeyFile;
  250. char rbuf[1];
  251. int nrbuf = 0;
  252. if (argc != 4) {
  253. fprintf(stderr, "%s <port> <certificate file> <key file>\n", argv[0]);
  254. exit(6);
  255. }
  256. nPort = atoi(argv[1]);
  257. szCertificateFile = argv[2];
  258. szKeyFile = argv[3];
  259. SSL_library_init();
  260. OpenSSL_add_ssl_algorithms();
  261. SSL_load_error_strings();
  262. ERR_load_crypto_strings();
  263. nFD = OpenSocket(nPort);
  264. pMachine = SSLStateMachine_new(szCertificateFile, szKeyFile);
  265. for (;;) {
  266. fd_set rfds, wfds;
  267. unsigned char buf[1024];
  268. int n;
  269. FD_ZERO(&rfds);
  270. FD_ZERO(&wfds);
  271. /* Select socket for input */
  272. FD_SET(nFD, &rfds);
  273. /* check whether there's decrypted data */
  274. if (!nrbuf)
  275. nrbuf = SSLStateMachine_read_extract(pMachine, rbuf, 1);
  276. /* if there's decrypted data, check whether we can write it */
  277. if (nrbuf)
  278. FD_SET(1, &wfds);
  279. /* Select socket for output */
  280. if (SSLStateMachine_write_can_extract(pMachine))
  281. FD_SET(nFD, &wfds);
  282. /* Select stdin for input */
  283. FD_SET(0, &rfds);
  284. /* Wait for something to do something */
  285. n = select(nFD + 1, &rfds, &wfds, NULL, NULL);
  286. assert(n > 0);
  287. /* Socket is ready for input */
  288. if (FD_ISSET(nFD, &rfds)) {
  289. n = read(nFD, buf, sizeof(buf));
  290. if (n == 0) {
  291. fprintf(stderr, "Got EOF on socket\n");
  292. exit(0);
  293. }
  294. assert(n > 0);
  295. SSLStateMachine_read_inject(pMachine, buf, n);
  296. }
  297. /* stdout is ready for output (and hence we have some to send it) */
  298. if (FD_ISSET(1, &wfds)) {
  299. assert(nrbuf == 1);
  300. buf[0] = rbuf[0];
  301. nrbuf = 0;
  302. n = SSLStateMachine_read_extract(pMachine, buf + 1,
  303. sizeof(buf) - 1);
  304. if (n < 0) {
  305. SSLStateMachine_print_error(pMachine, "read extract failed");
  306. break;
  307. }
  308. assert(n >= 0);
  309. ++n;
  310. if (n > 0) { /* FIXME: has to be true now */
  311. int w;
  312. w = write(1, buf, n);
  313. /* FIXME: we should push back any unwritten data */
  314. assert(w == n);
  315. }
  316. }
  317. /*
  318. * Socket is ready for output (and therefore we have output to send)
  319. */
  320. if (FD_ISSET(nFD, &wfds)) {
  321. int w;
  322. n = SSLStateMachine_write_extract(pMachine, buf, sizeof(buf));
  323. assert(n > 0);
  324. w = write(nFD, buf, n);
  325. /* FIXME: we should push back any unwritten data */
  326. assert(w == n);
  327. }
  328. /* Stdin is ready for input */
  329. if (FD_ISSET(0, &rfds)) {
  330. n = read(0, buf, sizeof(buf));
  331. if (n == 0) {
  332. fprintf(stderr, "Got EOF on stdin\n");
  333. exit(0);
  334. }
  335. assert(n > 0);
  336. SSLStateMachine_write_inject(pMachine, buf, n);
  337. }
  338. }
  339. /* not reached */
  340. return 0;
  341. }