wolfSSL-Example-IOCallbacks.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /* wolfSSL-Example-IOCallbacks.cs
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  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-1335, USA
  20. */
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Linq;
  24. using System.Text;
  25. using System.Threading.Tasks;
  26. using System.Net;
  27. using System.Net.Sockets;
  28. using System.Runtime.InteropServices;
  29. using System.IO;
  30. using wolfSSL.CSharp;
  31. class wolfSSL_Example_IOCallbacks
  32. {
  33. /// <summary>
  34. /// Example call back to allow receiving TLS information
  35. /// </summary>
  36. /// <param name="ssl">structure of ssl passed in</param>
  37. /// <param name="buf">buffer to contain received msg</param>
  38. /// <param name="sz">size of buffer for receiving</param>
  39. /// <param name="ctx">information passed in from set_fd</param>
  40. /// <returns>size of message received</returns>
  41. private static int wolfSSLCbIORecv(IntPtr ssl, IntPtr buf, int sz, IntPtr ctx)
  42. {
  43. if (sz <= 0)
  44. {
  45. wolfssl.log(wolfssl.ERROR_LOG, "wolfssl receive error, size less than 0");
  46. return wolfssl.CBIO_ERR_GENERAL;
  47. }
  48. int amtRecv = 0;
  49. try
  50. {
  51. System.Runtime.InteropServices.GCHandle gch;
  52. gch = GCHandle.FromIntPtr(ctx);
  53. Socket con = (System.Net.Sockets.Socket)gch.Target;
  54. Byte[] msg = new Byte[sz];
  55. amtRecv = con.Receive(msg, msg.Length, 0);
  56. Marshal.Copy(msg, 0, buf, sz);
  57. }
  58. catch (Exception e)
  59. {
  60. wolfssl.log(wolfssl.ENTER_LOG, "Error in receive " + e.ToString());
  61. return wolfssl.CBIO_ERR_CONN_CLOSE;
  62. }
  63. Console.WriteLine("Example custom receive got {0:D} bytes", amtRecv);
  64. return amtRecv;
  65. }
  66. /// <summary>
  67. /// Example call back used for sending TLS information
  68. /// </summary>
  69. /// <param name="ssl">pointer to ssl struct</param>
  70. /// <param name="buf">buffer containing information to send</param>
  71. /// <param name="sz">size of buffer to send</param>
  72. /// <param name="ctx">object that was set as fd</param>
  73. /// <returns>amount of information sent</returns>
  74. private static int wolfSSLCbIOSend(IntPtr ssl, IntPtr buf, int sz, IntPtr ctx)
  75. {
  76. if (sz <= 0)
  77. {
  78. wolfssl.log(wolfssl.ERROR_LOG, "wolfssl send error, size less than 0");
  79. return wolfssl.CBIO_ERR_GENERAL;
  80. }
  81. try
  82. {
  83. System.Runtime.InteropServices.GCHandle gch;
  84. gch = GCHandle.FromIntPtr(ctx);
  85. Socket con = (System.Net.Sockets.Socket)gch.Target;
  86. Byte[] msg = new Byte[sz];
  87. Marshal.Copy(buf, msg, 0, sz);
  88. con.Send(msg, 0, msg.Length, SocketFlags.None);
  89. Console.WriteLine("Example custom send sent {0:D} bytes", sz);
  90. return sz;
  91. }
  92. catch (Exception e)
  93. {
  94. wolfssl.log(wolfssl.ERROR_LOG, "socket connection issue " + e.ToString());
  95. return wolfssl.CBIO_ERR_CONN_CLOSE;
  96. }
  97. }
  98. /// <summary>
  99. /// Example of a PSK function call back
  100. /// </summary>
  101. /// <param name="ssl">pointer to ssl structure</param>
  102. /// <param name="identity">identity of client connecting</param>
  103. /// <param name="key">buffer to hold key</param>
  104. /// <param name="max_key">max key size</param>
  105. /// <returns>size of key set</returns>
  106. public static uint my_psk_server_cb(IntPtr ssl, string identity, IntPtr key, uint max_key)
  107. {
  108. /* perform a check on the identity sent across
  109. * log function must be set for print out of logging information
  110. */
  111. wolfssl.log(wolfssl.INFO_LOG, "PSK Client Identity = " + identity);
  112. /* Use desired key, note must be a key smaller than max key size parameter
  113. Replace this with desired key. Is trivial one for testing */
  114. if (max_key < 4)
  115. return 0;
  116. byte[] tmp = { 26, 43, 60, 77 };
  117. Marshal.Copy(tmp, 0, key, 4);
  118. return (uint)4;
  119. }
  120. /// <summary>
  121. /// Example of a certificate verify function
  122. /// </summary>
  123. /// <param name="preverify"></param>
  124. /// <param name="store">pointer to a WOLFSSL_X509_STORE_CTX</param>
  125. /// <returns>size of key set</returns>
  126. public static int my_verify_cb(int preverify, IntPtr store)
  127. {
  128. if (store == IntPtr.Zero)
  129. {
  130. Console.WriteLine("store is null");
  131. }
  132. Console.WriteLine("Status of certificate verify = " + preverify);
  133. Console.WriteLine("Error value for cert store is " + wolfssl.X509_STORE_CTX_get_error(store));
  134. /* look at the current cert in store */
  135. try
  136. {
  137. X509 x509 = wolfssl.X509_STORE_CTX_get_current_cert(store);
  138. Console.WriteLine("Issuer : " + x509.Issuer);
  139. Console.WriteLine("Subject : " + x509.Subject);
  140. Console.WriteLine("PEM of certificate:");
  141. Console.WriteLine(System.Text.Encoding.UTF8.GetString(x509.Export()));
  142. Console.WriteLine("DER of certificate:");
  143. Console.WriteLine(BitConverter.ToString(x509.Export(wolfssl.SSL_FILETYPE_ASN1)));
  144. Console.WriteLine("Public key:");
  145. Console.WriteLine(BitConverter.ToString(x509.GetPublicKey()));
  146. }
  147. catch (Exception e)
  148. {
  149. Console.WriteLine("Unable to get X509's" + e);
  150. }
  151. /* list all certs in store */
  152. try
  153. {
  154. int i;
  155. X509[] x509 = wolfssl.X509_STORE_CTX_get_certs(store);
  156. for (i = 0; i < x509.Length; i++)
  157. {
  158. Console.WriteLine("CERT[" + i + "]");
  159. Console.WriteLine("Issuer : " + x509[i].Issuer);
  160. Console.WriteLine("Subject : " + x509[i].Subject);
  161. Console.WriteLine("");
  162. }
  163. }
  164. catch (Exception e)
  165. {
  166. Console.WriteLine("Unable to get X509's" + e);
  167. }
  168. /* by returning 1 here we override any failure and report success */
  169. return preverify;
  170. }
  171. private static void clean(IntPtr ssl, IntPtr ctx)
  172. {
  173. wolfssl.free(ssl);
  174. wolfssl.CTX_free(ctx);
  175. wolfssl.Cleanup();
  176. }
  177. static void Main(string[] args)
  178. {
  179. IntPtr ctx;
  180. IntPtr ssl;
  181. Socket fd;
  182. wolfssl.CallbackVerify_delegate verify_cb = new wolfssl.CallbackVerify_delegate(my_verify_cb);
  183. /* These paths should be changed according to use */
  184. string fileCert = wolfssl.setPath("server-cert.pem");
  185. string fileKey = wolfssl.setPath("server-key.pem");
  186. StringBuilder dhparam = new StringBuilder(wolfssl.setPath("dh2048.pem"));
  187. if (fileCert == "" || fileKey == "" || dhparam.Length == 0) {
  188. Console.WriteLine("Platform not supported");
  189. return;
  190. }
  191. StringBuilder buff = new StringBuilder(1024);
  192. StringBuilder reply = new StringBuilder("Hello, this is the wolfSSL C# wrapper");
  193. wolfssl.Init();
  194. Console.WriteLine("Calling ctx Init from wolfSSL");
  195. ctx = wolfssl.CTX_new(wolfssl.useTLSv1_2_server());
  196. if (ctx == IntPtr.Zero)
  197. {
  198. Console.WriteLine("Error creating ctx structure");
  199. return;
  200. }
  201. Console.WriteLine("Finished init of ctx .... now load in cert and key");
  202. if (!File.Exists(fileCert) || !File.Exists(fileKey))
  203. {
  204. Console.WriteLine("Could not find cert or key file");
  205. wolfssl.CTX_free(ctx);
  206. return;
  207. }
  208. if (!File.Exists(dhparam.ToString())) {
  209. Console.WriteLine("Could not find dh file");
  210. wolfssl.CTX_free(ctx);
  211. return;
  212. }
  213. if (wolfssl.CTX_use_certificate_file(ctx, fileCert, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS)
  214. {
  215. Console.WriteLine("Error in setting cert file");
  216. wolfssl.CTX_free(ctx);
  217. return;
  218. }
  219. if (wolfssl.CTX_use_PrivateKey_file(ctx, fileKey, wolfssl.SSL_FILETYPE_PEM) != wolfssl.SUCCESS)
  220. {
  221. Console.WriteLine("Error in setting key file");
  222. wolfssl.CTX_free(ctx);
  223. return;
  224. }
  225. wolfssl.CTX_set_verify(ctx, wolfssl.SSL_VERIFY_PEER, verify_cb);
  226. /* Set using custom IO callbacks
  227. delegate memory is allocated when calling SetIO**** function and freed with ctx free
  228. */
  229. wolfssl.SetIORecv(ctx, new wolfssl.CallbackIORecv_delegate(wolfSSLCbIORecv));
  230. wolfssl.SetIOSend(ctx, new wolfssl.CallbackIOSend_delegate(wolfSSLCbIOSend));
  231. /* set up TCP socket */
  232. IPAddress ip = IPAddress.Parse("0.0.0.0"); //bind to any
  233. TcpListener tcp = new TcpListener(ip, 11111);
  234. tcp.Start();
  235. Console.WriteLine("Started TCP and waiting for a connection");
  236. fd = tcp.AcceptSocket();
  237. ssl = wolfssl.new_ssl(ctx);
  238. Console.WriteLine("Connection made wolfSSL_accept ");
  239. if (wolfssl.set_fd(ssl, fd) != wolfssl.SUCCESS)
  240. {
  241. /* get and print out the error */
  242. Console.WriteLine(wolfssl.get_error(ssl));
  243. tcp.Stop();
  244. clean(ssl, ctx);
  245. return;
  246. }
  247. if (wolfssl.accept(ssl) != wolfssl.SUCCESS)
  248. {
  249. /* get and print out the error */
  250. Console.WriteLine(wolfssl.get_error(ssl));
  251. tcp.Stop();
  252. clean(ssl, ctx);
  253. return;
  254. }
  255. /* print out results of TLS/SSL accept */
  256. Console.WriteLine("SSL version is " + wolfssl.get_version(ssl));
  257. Console.WriteLine("SSL cipher suite is " + wolfssl.get_current_cipher(ssl));
  258. /* read and print out the message then reply */
  259. if (wolfssl.read(ssl, buff, 1023) < 0)
  260. {
  261. Console.WriteLine("Error in read");
  262. tcp.Stop();
  263. clean(ssl, ctx);
  264. return;
  265. }
  266. Console.WriteLine(buff);
  267. if (wolfssl.write(ssl, reply, reply.Length) != reply.Length)
  268. {
  269. Console.WriteLine("Error in write");
  270. tcp.Stop();
  271. clean(ssl, ctx);
  272. return;
  273. }
  274. wolfssl.shutdown(ssl);
  275. fd.Close();
  276. tcp.Stop();
  277. clean(ssl, ctx);
  278. }
  279. }