ssl_helper.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*
  2. * Adapted from:
  3. *
  4. * client.c
  5. *
  6. * Copyright (C) 2006-2015 wolfSSL Inc.
  7. *
  8. * This file is part of wolfSSL. (formerly known as CyaSSL)
  9. *
  10. * wolfSSL is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * wolfSSL is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. #include <stdlib.h>
  25. #include <unistd.h>
  26. #include <stdarg.h>
  27. #include <string.h>
  28. #include <errno.h>
  29. #include <fcntl.h>
  30. #include <stdio.h>
  31. #include <time.h>
  32. #include <poll.h>
  33. #include <sys/socket.h>
  34. #include <wolfssl/wolfcrypt/types.h>
  35. #include <wolfssl/ssl.h>
  36. #if 0
  37. # define dbg(...) say(__VA_ARGS__)
  38. #else
  39. # define dbg(...) ((void)0)
  40. #endif
  41. static ssize_t safe_write(int fd, const void *buf, size_t count)
  42. {
  43. ssize_t n;
  44. do {
  45. n = write(fd, buf, count);
  46. } while (n < 0 && errno == EINTR);
  47. return n;
  48. }
  49. static ssize_t full_write(int fd, const void *buf, size_t len)
  50. {
  51. ssize_t cc;
  52. ssize_t total;
  53. total = 0;
  54. while (len) {
  55. cc = safe_write(fd, buf, len);
  56. if (cc < 0) {
  57. if (total) {
  58. /* we already wrote some! */
  59. /* user can do another write to know the error code */
  60. return total;
  61. }
  62. return cc; /* write() returns -1 on failure. */
  63. }
  64. total += cc;
  65. buf = ((const char *)buf) + cc;
  66. len -= cc;
  67. }
  68. return total;
  69. }
  70. static void say(const char *s, ...)
  71. {
  72. char buf[256];
  73. va_list p;
  74. int sz;
  75. va_start(p, s);
  76. sz = vsnprintf(buf, sizeof(buf), s, p);
  77. full_write(STDERR_FILENO, buf, sz >= 0 && sz < sizeof(buf) ? sz : strlen(buf));
  78. va_end(p);
  79. }
  80. static void die(const char *s, ...)
  81. {
  82. char buf[256];
  83. va_list p;
  84. int sz;
  85. va_start(p, s);
  86. sz = vsnprintf(buf, sizeof(buf), s, p);
  87. full_write(STDERR_FILENO, buf, sz >= 0 && sz < sizeof(buf) ? sz : strlen(buf));
  88. exit(1);
  89. va_end(p);
  90. }
  91. static void err_sys(const char *msg)
  92. {
  93. die("%s\n", msg);
  94. }
  95. /* ==== */
  96. #if 0
  97. static void showPeer(WOLFSSL* ssl)
  98. {
  99. WOLFSSL_CIPHER* cipher;
  100. WOLFSSL_X509* peer = wolfSSL_get_peer_certificate(ssl);
  101. if (peer)
  102. ShowX509(peer, "peer's cert info:");
  103. else
  104. say("peer has no cert!\n");
  105. say("SSL version is %s\n", wolfSSL_get_version(ssl));
  106. cipher = wolfSSL_get_current_cipher(ssl);
  107. say("SSL cipher suite is %s\n", wolfSSL_CIPHER_get_name(cipher));
  108. {
  109. WOLFSSL_X509_CHAIN* chain = wolfSSL_get_peer_chain(ssl);
  110. int count = wolfSSL_get_chain_count(chain);
  111. int i;
  112. for (i = 0; i < count; i++) {
  113. int length;
  114. unsigned char buffer[3072];
  115. WOLFSSL_X509* chainX509;
  116. wolfSSL_get_chain_cert_pem(chain, i, buffer, sizeof(buffer), &length);
  117. buffer[length] = 0;
  118. say("cert %d has length %d data = \n%s\n", i, length, buffer);
  119. chainX509 = wolfSSL_get_chain_X509(chain, i);
  120. if (chainX509)
  121. ShowX509(chainX509, "session cert info:");
  122. else
  123. say("get_chain_X509 failed\n");
  124. wolfSSL_FreeX509(chainX509);
  125. }
  126. }
  127. }
  128. #endif
  129. WOLFSSL *prepare(int sockfd)
  130. {
  131. WOLFSSL_METHOD* method;
  132. WOLFSSL_CTX* ctx;
  133. WOLFSSL* ssl;
  134. wolfSSL_Init();
  135. method = wolfTLSv1_1_client_method();
  136. if (method == NULL)
  137. err_sys("out of memory");
  138. ctx = wolfSSL_CTX_new(method);
  139. if (ctx == NULL)
  140. err_sys("out of memory");
  141. // if (cipherList)
  142. // if (wolfSSL_CTX_set_cipher_list(ctx, cipherList) != SSL_SUCCESS)
  143. // err_sys("client can't set cipher list 1");
  144. // if (fewerPackets)
  145. // wolfSSL_CTX_set_group_messages(ctx);
  146. //#ifndef NO_DH
  147. // wolfSSL_CTX_SetMinDhKey_Sz(ctx, (word16)minDhKeyBits);
  148. //#endif
  149. // if (usePsk) {
  150. // wolfSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
  151. // if (cipherList == NULL) {
  152. // const char *defaultCipherList;
  153. //#if defined(HAVE_AESGCM) && !defined(NO_DH)
  154. // defaultCipherList = "DHE-PSK-AES128-GCM-SHA256";
  155. //#elif defined(HAVE_NULL_CIPHER)
  156. // defaultCipherList = "PSK-NULL-SHA256";
  157. //#else
  158. // defaultCipherList = "PSK-AES128-CBC-SHA256";
  159. //#endif
  160. // if (wolfSSL_CTX_set_cipher_list(ctx,defaultCipherList) != SSL_SUCCESS)
  161. // err_sys("client can't set cipher list 2");
  162. // }
  163. // useClientCert = 0;
  164. // }
  165. // if (useAnon) {
  166. // if (cipherList == NULL) {
  167. // wolfSSL_CTX_allow_anon_cipher(ctx);
  168. // if (wolfSSL_CTX_set_cipher_list(ctx,"ADH-AES128-SHA") != SSL_SUCCESS)
  169. // err_sys("client can't set cipher list 4");
  170. // }
  171. // useClientCert = 0;
  172. // }
  173. //#if defined(OPENSSL_EXTRA) || defined(HAVE_WEBSERVER)
  174. // wolfSSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
  175. //#endif
  176. // if (useOcsp) {
  177. // if (ocspUrl != NULL) {
  178. // wolfSSL_CTX_SetOCSP_OverrideURL(ctx, ocspUrl);
  179. // wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE
  180. // | WOLFSSL_OCSP_URL_OVERRIDE);
  181. // }
  182. // else
  183. // wolfSSL_CTX_EnableOCSP(ctx, WOLFSSL_OCSP_NO_NONCE);
  184. // }
  185. //
  186. //#ifdef USER_CA_CB
  187. // wolfSSL_CTX_SetCACb(ctx, CaCb);
  188. //#endif
  189. //
  190. //#ifdef VERIFY_CALLBACK
  191. // wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myVerify);
  192. //#endif
  193. //#if !defined(NO_FILESYSTEM) && !defined(NO_CERTS)
  194. // if (useClientCert) {
  195. // if (wolfSSL_CTX_use_certificate_chain_file(ctx, ourCert) != SSL_SUCCESS)
  196. // err_sys("can't load client cert file, check file and run from"
  197. // " wolfSSL home dir");
  198. // if (wolfSSL_CTX_use_PrivateKey_file(ctx, ourKey, SSL_FILETYPE_PEM) != SSL_SUCCESS)
  199. // err_sys("can't load client private key file, check file and run "
  200. // "from wolfSSL home dir");
  201. // }
  202. //
  203. // if (!usePsk && !useAnon) {
  204. // if (wolfSSL_CTX_load_verify_locations(ctx, verifyCert,0) != SSL_SUCCESS)
  205. // err_sys("can't load ca file, Please run from wolfSSL home dir");
  206. //#ifdef HAVE_ECC
  207. // /* load ecc verify too, echoserver uses it by default w/ ecc */
  208. // if (wolfSSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS)
  209. // err_sys("can't load ecc ca file, Please run from wolfSSL home dir");
  210. //#endif
  211. // }
  212. //#endif /* !NO_FILESYSTEM && !NO_CERTS */
  213. //#if !defined(NO_CERTS)
  214. // if (!usePsk && !useAnon && doPeerCheck == 0)
  215. // wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
  216. // if (!usePsk && !useAnon && overrideDateErrors == 1)
  217. // wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, myDateCb);
  218. //#endif
  219. wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
  220. //#ifdef HAVE_SNI
  221. // if (sniHostName)
  222. // if (wolfSSL_CTX_UseSNI(ctx, 0, sniHostName, XSTRLEN(sniHostName)) != SSL_SUCCESS)
  223. // err_sys("UseSNI failed");
  224. //#endif
  225. //#ifdef HAVE_MAX_FRAGMENT
  226. // if (maxFragment)
  227. // if (wolfSSL_CTX_UseMaxFragment(ctx, maxFragment) != SSL_SUCCESS)
  228. // err_sys("UseMaxFragment failed");
  229. //#endif
  230. //#ifdef HAVE_TRUNCATED_HMAC
  231. // if (truncatedHMAC)
  232. // if (wolfSSL_CTX_UseTruncatedHMAC(ctx) != SSL_SUCCESS)
  233. // err_sys("UseTruncatedHMAC failed");
  234. //#endif
  235. //#ifdef HAVE_SESSION_TICKET
  236. // if (wolfSSL_CTX_UseSessionTicket(ctx) != SSL_SUCCESS)
  237. // err_sys("UseSessionTicket failed");
  238. //#endif
  239. //#if defined(WOLFSSL_MDK_ARM)
  240. // wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
  241. //#endif
  242. ssl = wolfSSL_new(ctx);
  243. if (ssl == NULL)
  244. err_sys("out of memory");
  245. //#ifdef HAVE_SESSION_TICKET
  246. // wolfSSL_set_SessionTicket_cb(ssl, sessionTicketCB, (void*)"initial session");
  247. //#endif
  248. // if (doDTLS) {
  249. // SOCKADDR_IN_T addr;
  250. // build_addr(&addr, host, port, 1);
  251. // wolfSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
  252. // tcp_socket(&sockfd, 1);
  253. // } wlse {
  254. // tcp_connect(&sockfd, host, port, 0);
  255. // }
  256. //#ifdef HAVE_POLY1305
  257. // /* use old poly to connect with google server */
  258. // if (!XSTRNCMP(domain, "www.google.com", 14)) {
  259. // if (wolfSSL_use_old_poly(ssl, 1) != 0)
  260. // err_sys("unable to set to old poly");
  261. // }
  262. //#endif
  263. wolfSSL_set_fd(ssl, sockfd);
  264. //#ifdef HAVE_CRL
  265. // if (disableCRL == 0) {
  266. // if (wolfSSL_EnableCRL(ssl, WOLFSSL_CRL_CHECKALL) != SSL_SUCCESS)
  267. // err_sys("can't enable crl check");
  268. // if (wolfSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, 0) != SSL_SUCCESS)
  269. // err_sys("can't load crl, check crlfile and date validity");
  270. // if (wolfSSL_SetCRL_Cb(ssl, CRL_CallBack) != SSL_SUCCESS)
  271. // err_sys("can't set crl callback");
  272. // }
  273. //#endif
  274. //#ifdef HAVE_SECURE_RENEGOTIATION
  275. // if (scr) {
  276. // if (wolfSSL_UseSecureRenegotiation(ssl) != SSL_SUCCESS)
  277. // err_sys("can't enable secure renegotiation");
  278. // }
  279. //#endif
  280. //#ifdef ATOMIC_USER
  281. // if (atomicUser)
  282. // SetupAtomicUser(ctx, ssl);
  283. //#endif
  284. //#ifdef HAVE_PK_CALLBACKS
  285. // if (pkCallbacks)
  286. // SetupPkCallbacks(ctx, ssl);
  287. //#endif
  288. // if (matchName && doPeerCheck)
  289. // wolfSSL_check_domain_name(ssl, domain);
  290. if (wolfSSL_connect(ssl) != SSL_SUCCESS) {
  291. // /* see note at top of README */
  292. // int err = wolfSSL_get_error(ssl, 0);
  293. // char buffer[WOLFSSL_MAX_ERROR_SZ];
  294. // say("err = %d, %s\n", err,
  295. // wolfSSL_ERR_error_string(err, buffer));
  296. err_sys("SSL_connect failed");
  297. }
  298. // showPeer(ssl);
  299. //#ifdef HAVE_SECURE_RENEGOTIATION
  300. // if (scr && forceScr) {
  301. // if (wolfSSL_Rehandshake(ssl) != SSL_SUCCESS) {
  302. // int err = wolfSSL_get_error(ssl, 0);
  303. // char buffer[WOLFSSL_MAX_ERROR_SZ];
  304. // say("err = %d, %s\n", err,
  305. // wolfSSL_ERR_error_string(err, buffer));
  306. // err_sys("wolfSSL_Rehandshake failed");
  307. // }
  308. // }
  309. //#endif
  310. return ssl;
  311. }
  312. static struct pollfd pfd[2] = {
  313. { -1, POLLIN|POLLERR|POLLHUP, 0 },
  314. { -1, POLLIN|POLLERR|POLLHUP, 0 },
  315. };
  316. #define STDIN pfd[0]
  317. #define NETWORK pfd[1]
  318. #define STDIN_READY() (pfd[0].revents & (POLLIN|POLLERR|POLLHUP))
  319. #define NETWORK_READY() (pfd[1].revents & (POLLIN|POLLERR|POLLHUP))
  320. static void wait_for_input(void)
  321. {
  322. if (STDIN.fd == NETWORK.fd) /* means both are -1 */
  323. exit(0);
  324. dbg("polling\n");
  325. STDIN.revents = NETWORK.revents = 0;
  326. while (poll(pfd, 2, -1) < 0 && errno == EINTR)
  327. continue;
  328. }
  329. static void do_io_until_eof_and_exit(WOLFSSL *ssl, int fd)
  330. {
  331. int len;
  332. char ibuf[4 * 1024];
  333. NETWORK.fd = fd;
  334. STDIN.fd = 0;
  335. len = 0; /* only to suppress compiler warning */
  336. for (;;) {
  337. wait_for_input();
  338. if (STDIN_READY()) {
  339. dbg("reading stdin\n");
  340. len = read(STDIN_FILENO, ibuf, sizeof(ibuf));
  341. if (len < 0)
  342. die("read error on stdin\n");
  343. if (len == 0) {
  344. dbg("read len = 0, stdin not polled anymore\n");
  345. STDIN.fd = -1;
  346. } else {
  347. int n = wolfSSL_write(ssl, ibuf, len);
  348. if (n != len)
  349. die("SSL_write(%d) failed (returned %d)\n", len, n);
  350. }
  351. }
  352. if (NETWORK_READY()) {
  353. dbg("%s%s%s\n",
  354. (pfd[1].revents & POLLIN) ? "POLLIN" : "",
  355. (pfd[1].revents & POLLERR) ? "|POLLERR" : "",
  356. (pfd[1].revents & POLLHUP) ? "|POLLHUP" : ""
  357. );
  358. /* We are using blocking socket here.
  359. * (Nonblocking socket would complicate writing to it).
  360. * Therefore, SSL_read _can block_ here.
  361. * This is not what wget expects (it wants to see short reads).
  362. * Therefore, we use smallish buffer here, to approximate that.
  363. */
  364. len = wolfSSL_read(ssl, ibuf,
  365. sizeof(ibuf) < 1024 ? sizeof(ibuf) : 1024
  366. );
  367. if (len < 0)
  368. die("SSL_read error on network (%d)\n", len);
  369. if (len > 0) {
  370. int n;
  371. n = full_write(STDOUT_FILENO, ibuf, len);
  372. if (n != len)
  373. die("write(%d) to stdout returned %d\n", len, n);
  374. continue;
  375. }
  376. /* Blocking reads are easier wtr EOF detection (no EAGAIN error to check for) */
  377. dbg("read len = 0, network not polled anymore\n");
  378. NETWORK.fd = -1;
  379. /* saw EOF on network, and we processed
  380. * and wrote out all ssl data. Signal it:
  381. */
  382. close(STDOUT_FILENO);
  383. }
  384. }
  385. }
  386. int main(int argc, char **argv)
  387. {
  388. WOLFSSL *ssl;
  389. int fd;
  390. char *fd_str;
  391. if (!argv[1])
  392. die("Syntax error\n");
  393. if (argv[1][0] != '-')
  394. die("Syntax error\n");
  395. if (argv[1][1] != 'd')
  396. die("Syntax error\n");
  397. fd_str = argv[1] + 2;
  398. if (!fd_str[0])
  399. fd_str = argv[2];
  400. if (!fd_str || fd_str[0] < '0' || fd_str[0] > '9')
  401. die("Syntax error\n");
  402. fd = atoi(fd_str);
  403. if (fd < 3)
  404. die("Syntax error\n");
  405. ssl = prepare(fd);
  406. do_io_until_eof_and_exit(ssl, fd);
  407. /* does not return */
  408. // if (doDTLS == 0) { /* don't send alert after "break" command */
  409. // ret = wolfSSL_shutdown(ssl);
  410. // if (wc_shutdown && ret == SSL_SHUTDOWN_NOT_DONE)
  411. // wolfSSL_shutdown(ssl); /* bidirectional shutdown */
  412. // }
  413. //#ifdef ATOMIC_USER
  414. // if (atomicUser)
  415. // FreeAtomicUser(ssl);
  416. //#endif
  417. // wolfSSL_free(ssl);
  418. // CloseSocket(sockfd);
  419. // wolfSSL_CTX_free(ctx);
  420. return 0;
  421. }