client-tls13.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /* client-tls13.c
  2. *
  3. * Copyright (C) 2006-2020 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL. (formerly known as CyaSSL)
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  20. */
  21. /* C Standard Library */
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <time.h>
  26. /* POSIX Library */
  27. #include <sys/socket.h>
  28. #include <arpa/inet.h>
  29. #include <netinet/in.h>
  30. #include <unistd.h>
  31. /* wolfSSL Library */
  32. #include <wolfssl/options.h>
  33. #include <wolfssl/ssl.h>
  34. #include <wolfssl/wolfio.h>
  35. #include <wolfssl/wolfcrypt/port/iotsafe/iotsafe.h>
  36. #include <wolfssl/error-ssl.h>
  37. /* IoTSAFE Certificate slots */
  38. /* File Slot '02' is pre-provisioned with
  39. * the client ECC public key certificate.
  40. */
  41. #define CRT_CLIENT_FILE_ID 0x02
  42. /* File Slot '03' is pre-provisioned with the
  43. * server ECC public key certificate.
  44. */
  45. #define CRT_SERVER_FILE_ID 0x03
  46. /* IoTSAFE Key slots */
  47. /* Key slot '01' is pre-provisioned with
  48. * the client ECC private key.
  49. */
  50. #define PRIVKEY_ID 0x01
  51. /* Key slot '04' is used to generate the ECDH
  52. * key pair that will be used during the TLS
  53. * session.
  54. */
  55. #define ECDH_KEYPAIR_ID 0x04
  56. /* Key slot '05' is used to store the ECDH public
  57. * key received from the peer during the TLS
  58. * session.
  59. */
  60. #define PEER_PUBKEY_ID 0x05
  61. /* Key slot '05' is used to store the public key
  62. * used for ECC verification - disabled in IoTSAFE.
  63. */
  64. #define PEER_CERT_ID 0x05
  65. /* Function Declarations */
  66. extern int client_loop(const char *peer_ip, const char *peer_name, const char *peer_port, const char *temperature);
  67. #if defined(USE_SECRET_CALLBACK)
  68. static int Tls13SecretCallback(WOLFSSL* ssl, int id, const unsigned char* secret, int secretSz, void* ctx);
  69. #endif
  70. /* Function Definitions */
  71. #if defined(USE_SECRET_CALLBACK)
  72. #ifndef WOLFSSL_SSLKEYLOGFILE_OUTPUT
  73. #define WOLFSSL_SSLKEYLOGFILE_OUTPUT "sslkeylog.log"
  74. #endif
  75. /* Callback function for TLS v1.3 secrets for use with Wireshark */
  76. static int Tls13SecretCallback(WOLFSSL* ssl, int id, const unsigned char* secret,
  77. int secretSz, void* ctx)
  78. {
  79. int i;
  80. const char* str = NULL;
  81. unsigned char clientRandom[32];
  82. size_t clientRandomSz;
  83. XFILE fp = stderr;
  84. if (ctx) {
  85. fp = XFOPEN((const char*)ctx, "ab");
  86. if (fp == XBADFILE) {
  87. return BAD_FUNC_ARG;
  88. }
  89. }
  90. clientRandomSz = wolfSSL_get_client_random(ssl, clientRandom,
  91. sizeof(clientRandom));
  92. switch (id) {
  93. case CLIENT_EARLY_TRAFFIC_SECRET:
  94. str = "CLIENT_EARLY_TRAFFIC_SECRET"; break;
  95. case EARLY_EXPORTER_SECRET:
  96. str = "EARLY_EXPORTER_SECRET"; break;
  97. case CLIENT_HANDSHAKE_TRAFFIC_SECRET:
  98. str = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"; break;
  99. case SERVER_HANDSHAKE_TRAFFIC_SECRET:
  100. str = "SERVER_HANDSHAKE_TRAFFIC_SECRET"; break;
  101. case CLIENT_TRAFFIC_SECRET:
  102. str = "CLIENT_TRAFFIC_SECRET_0"; break;
  103. case SERVER_TRAFFIC_SECRET:
  104. str = "SERVER_TRAFFIC_SECRET_0"; break;
  105. case EXPORTER_SECRET:
  106. str = "EXPORTER_SECRET"; break;
  107. }
  108. fprintf(fp, "%s ", str);
  109. for (i = 0; i < (int)clientRandomSz; i++) {
  110. fprintf(fp, "%02x", clientRandom[i]);
  111. }
  112. fprintf(fp, " ");
  113. for (i = 0; i < secretSz; i++) {
  114. fprintf(fp, "%02x", secret[i]);
  115. }
  116. fprintf(fp, "\n");
  117. if (fp != stderr) {
  118. XFCLOSE(fp);
  119. }
  120. return 0;
  121. }
  122. #endif /* USE_SECRET_CALLBACK */
  123. int client_loop(const char *peer_ip, const char *peer_name, const char *peer_port, const char *temperature)
  124. {
  125. int ret = 0;
  126. /* Declare TCP objects */
  127. int sockfd = -1;
  128. struct sockaddr_in servAddr = {0};
  129. /* Declare TCP messaging buffer */
  130. char buff[2048] = {0};
  131. size_t len = 0;
  132. /* Declare certificate temporary buffer */
  133. uint8_t cert_buffer[2048] = {0};
  134. uint32_t cert_buffer_size = 0;
  135. uint8_t *cert_iter = NULL;
  136. /* Declare wolfSSL objects */
  137. WOLFSSL_CTX* ctx = NULL;
  138. WOLFSSL* ssl = NULL;
  139. WC_RNG rng = {0};
  140. char randombytes[16] = {0};
  141. /* Construct HTTP POST */
  142. /* Header */
  143. strcat(buff, "POST /iot/device HTTP/1.1\r\n");
  144. strcat(buff, "Content-Type: application/json\r\n");
  145. strcat(buff, "Content-Length: 1000\r\n");
  146. strcat(buff, "Accept: */*\r\n");
  147. strcat(buff, "Host: ");
  148. strcat(buff, peer_name);
  149. strcat(buff, ":");
  150. strcat(buff, peer_port);
  151. strcat(buff, "\r\n");
  152. /* Delimiter */
  153. strcat(buff, "\r\n");
  154. /* Body */
  155. srand(time(NULL));
  156. int devid = rand() % 100;
  157. char snum[5] = {0};
  158. snprintf(snum, sizeof(snum), "%d", devid);
  159. strcat(buff, "{");
  160. strcat(buff, "\"deviceId\": \"");
  161. strcat(buff, snum);
  162. strcat(buff, "\",");
  163. strcat(buff, "\"sensorType\": \"Temperature\",");
  164. strcat(buff, "\"sensorValue\": \"");
  165. strcat(buff, temperature);
  166. strcat(buff, "\",");
  167. strcat(buff, "\"sensorUnit\": \"Celsius\",");
  168. strcat(buff, "\"sensorTime\": 1582181510");
  169. strcat(buff, "}");
  170. strcat(buff, "\r\n");
  171. printf("\n\nPOST REQUEST\n\n%s\n\n", buff);
  172. /*---------------------------------*/
  173. /* Start of Socket */
  174. /*---------------------------------*/
  175. printf("---- Preparing TCP socket\n");
  176. /* Create a socket that uses an internet IPv4 address,
  177. * Sets the socket to be stream based (TCP),
  178. * 0 means choose the default protocol. */
  179. printf("---- Creating socket\n");
  180. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  181. {
  182. fprintf(stderr, "ERROR: failed to create the socket\n");
  183. ret = -1;
  184. goto exit;
  185. }
  186. /* Fill in the server address */
  187. printf("Peer port: %s\n", peer_port);
  188. servAddr.sin_family = AF_INET; /* Using IPv4 */
  189. servAddr.sin_port = htons(atoi(peer_port));
  190. /* Get the server IPv4 address from the command line call */
  191. printf("---- Checking peer IP address\n");
  192. printf("Peer IP address: %s <IPv4 address>\n", peer_ip);
  193. if (inet_pton(AF_INET, peer_ip, &servAddr.sin_addr) != 1)
  194. {
  195. fprintf(stderr, "ERROR: invalid peer IP address\n");
  196. ret = -1;
  197. goto exit;
  198. }
  199. /* Connect to the server */
  200. printf("---- Connecting to the peer socket\n");
  201. if ((ret = connect(sockfd, (struct sockaddr*) &servAddr, sizeof(servAddr)))
  202. == -1)
  203. {
  204. fprintf(stderr, "ERROR: failed to connect\n");
  205. goto exit;
  206. }
  207. printf("---- TCP socket connection established\n");
  208. /*---------------------------------*/
  209. /* Start of Security */
  210. /*---------------------------------*/
  211. printf("---- Preparing wolfSSL TLS 1.3\n");
  212. /* Initialize wolfSSL */
  213. printf("---- Initializing wolfSSL\n");
  214. if ((ret = wolfSSL_Init()) != WOLFSSL_SUCCESS)
  215. {
  216. fprintf(stderr, "ERROR: Failed to initialize the library\n");
  217. goto exit;
  218. }
  219. /* Allow debug print in wolfSSL */
  220. printf("---- Allowing debug print in wolfSSL\n");
  221. if ((ret = wolfSSL_Debugging_ON()) != 0)
  222. {
  223. fprintf(stderr, "WARNING: Failed to enable wolfSSL debug print\n");
  224. }
  225. /* Initialize RNG */
  226. printf("---- Initializing RNG\n");
  227. if ((ret = wc_InitRng(&rng)) != 0)
  228. {
  229. fprintf(stderr, "ERROR: Failed to initialize the random number generator\n");
  230. goto exit;
  231. }
  232. /* Obtain a sample RND */
  233. printf("---- Testing getting RND\n");
  234. if ((ret = wc_RNG_GenerateBlock(
  235. &rng,
  236. (byte*)randombytes,
  237. sizeof(randombytes)))
  238. != 0)
  239. {
  240. fprintf(stderr, "ERROR: Failed to get random numbers\n");
  241. goto exit;
  242. }
  243. else
  244. {
  245. printf("Random bytes: ");
  246. for (uint8_t i = 0; i < sizeof(randombytes); i++)
  247. printf("%02X", (unsigned int)randombytes[i]);
  248. printf("\n");
  249. }
  250. /* Create and initialize WOLFSSL_CTX */
  251. printf("---- Creating wolfSSL TLS 1.3 context object\n");
  252. if ((ctx = wolfSSL_CTX_new(wolfTLSv1_3_client_method())) == NULL)
  253. {
  254. fprintf(stderr, "ERROR: failed to create WOLFSSL_CTX\n");
  255. ret = -1;
  256. goto exit;
  257. }
  258. /* Initialize IoTSAFE */
  259. printf("---- Enabling IoTSAFE\n");
  260. if ((ret = wolfSSL_CTX_iotsafe_enable(ctx)) != 0)
  261. {
  262. fprintf(stderr, "ERROR: Failed to initialize IoTSAFE\n");
  263. goto exit;
  264. }
  265. /* Extract client certificate from IoTSAFE*/
  266. printf("---- Extracting client certificate from IoTSAFE\n");
  267. if ((cert_buffer_size = wolfIoTSafe_GetCert(
  268. CRT_CLIENT_FILE_ID,
  269. cert_buffer,
  270. sizeof(cert_buffer)))
  271. < 1)
  272. {
  273. fprintf(stderr, "ERROR: Bad client certificate\n");
  274. ret = -1;
  275. goto exit;
  276. }
  277. /* Print extracted client certificate */
  278. printf("---- Printing extracted client certificate\n");
  279. cert_iter = (uint8_t*)&cert_buffer;
  280. printf("Extracted client certificate in HEX:\n");
  281. for (uint32_t i = 0; i < cert_buffer_size; i++)
  282. printf("%02X", (unsigned int)*(cert_iter++));
  283. printf("\n");
  284. /* Load client certificate */
  285. printf("---- Loading client certificate\n");
  286. if ((ret = wolfSSL_CTX_use_certificate_buffer(ctx, cert_buffer,
  287. cert_buffer_size, WOLFSSL_FILETYPE_ASN1))
  288. != WOLFSSL_SUCCESS)
  289. {
  290. fprintf(stderr, "ERROR: Failed to load client certificate\n");
  291. return -1;
  292. }
  293. /* Extract server certificate from IoTSAFE*/
  294. printf("---- Extracting server certificate from IoTSAFE\n");
  295. if ((cert_buffer_size = wolfIoTSafe_GetCert(
  296. CRT_SERVER_FILE_ID,
  297. cert_buffer,
  298. sizeof(cert_buffer)))
  299. < 1)
  300. {
  301. fprintf(stderr, "ERROR: Bad server certificate\n");
  302. ret = -1;
  303. goto exit;
  304. }
  305. /* Print extracted server certificate */
  306. printf("---- Printing extracted server certificate\n");
  307. cert_iter = (uint8_t*)&cert_buffer;
  308. printf("Extracted server certificate in HEX:\n");
  309. for (uint32_t i = 0; i < cert_buffer_size; i++)
  310. printf("%02X", (unsigned int)*(cert_iter++));
  311. printf("\n");
  312. /* Load server certificate */
  313. printf("---- Loading server certificate\n");
  314. if ((ret = wolfSSL_CTX_trust_peer_buffer(ctx, cert_buffer,
  315. cert_buffer_size, WOLFSSL_FILETYPE_ASN1))
  316. != WOLFSSL_SUCCESS)
  317. {
  318. fprintf(stderr, "ERROR: Failed to load server certificate\n");
  319. return -1;
  320. }
  321. /* Set client to authenticate server */
  322. printf("---- Enabling client to authenticate server\n");
  323. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL);
  324. /* Create a WOLFSSL object */
  325. printf("---- Creating wolfSSL TLS 1.3 connection object\n");
  326. if ((ssl = wolfSSL_new(ctx)) == NULL)
  327. {
  328. fprintf(stderr, "ERROR: failed to create WOLFSSL object\n");
  329. ret = -1;
  330. goto exit;
  331. }
  332. /* Attach IoTSAFE usage to the wolfSSL */
  333. printf("---- Using IoTSAFE for TLS 1.3\n");
  334. if ((ret = wolfSSL_iotsafe_on(
  335. ssl, PRIVKEY_ID, ECDH_KEYPAIR_ID,
  336. PEER_PUBKEY_ID, PEER_CERT_ID))
  337. != 0)
  338. {
  339. fprintf(stderr, "ERROR: Failed to use IoTSAFE\n");
  340. goto exit;
  341. }
  342. /* Attach wolfSSL to the socket */
  343. printf("---- Attaching TLS 1.3 to the socket\n");
  344. if ((ret = wolfSSL_set_fd(ssl, sockfd)) != WOLFSSL_SUCCESS)
  345. {
  346. fprintf(stderr, "ERROR: Failed to set the file descriptor\n");
  347. goto exit;
  348. }
  349. #ifdef USE_SECRET_CALLBACK
  350. /* Logging usage for wireshark */
  351. printf("---- Attaching TLS 1.3 secret callback for wireshark\n");
  352. if ((ret = wolfSSL_set_tls13_secret_cb(
  353. ssl,
  354. Tls13SecretCallback,
  355. (void*)WOLFSSL_SSLKEYLOGFILE_OUTPUT))
  356. != WOLFSSL_SUCCESS)
  357. {
  358. fprintf(stderr, "ERROR: Failed to set the secret callback\n");
  359. goto exit;
  360. }
  361. #endif
  362. /* Connect to wolfSSL on the server side */
  363. printf("---- Start TLS 1.3 handshaking\n");
  364. if ((ret = wolfSSL_connect(ssl)) != WOLFSSL_SUCCESS)
  365. {
  366. fprintf(stderr, "ERROR: failed to connect to wolfSSL\n");
  367. goto exit;
  368. }
  369. printf("---- wolfSSL TLS 1.3 connection established\n");
  370. /*---------------------------------*/
  371. /* Start of Communication */
  372. /*---------------------------------*/
  373. printf("---- Communication starts\n");
  374. /* Get a message for the server from stdin */
  375. printf("Enter message for server:\n");
  376. printf("[OUT]:\n");
  377. printf("\n\n%s\n\n", buff);
  378. len = strlen(buff);
  379. /* Send the message to the server */
  380. printf("Sending message to the server\n");
  381. if ((size_t) (ret = wolfSSL_write(ssl, buff, len)) != len)
  382. {
  383. fprintf(stderr, "ERROR: failed to write entire message\n");
  384. fprintf(stderr, "%d bytes of %d bytes were sent\n", ret, (int) len);
  385. goto exit;
  386. }
  387. /* Read the server data into our buff array */
  388. printf("Receiving message from the server\n");
  389. memset(buff, 0, sizeof(buff));
  390. if ((ret = wolfSSL_read(ssl, buff, sizeof(buff) - 1)) < 0)
  391. {
  392. fprintf(stderr, "ERROR: failed to read\n");
  393. goto exit;
  394. }
  395. /* Print to stdout any data the server sends */
  396. printf("[IN] :\n%s\n", buff);
  397. /* Return reporting a success */
  398. ret = 0;
  399. printf("---- Communication ends\n");
  400. exit:
  401. /* Cleanup and return */
  402. if (sockfd != -1)
  403. close(sockfd); /* Close the connection to the server */
  404. if (ssl)
  405. wolfSSL_free(ssl); /* Free the wolfSSL object */
  406. if (ctx)
  407. wolfSSL_CTX_free(ctx); /* Free the wolfSSL context object */
  408. wc_FreeRng(&rng); /* Cleanup the RNG */
  409. wolfSSL_Cleanup(); /* Cleanup the wolfSSL environment */
  410. return ret;
  411. }