2 * Copyright (c) 2007, Cameron Rich
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 * * Neither the name of the axTLS project nor the names of its contributors
15 * may be used to endorse or promote products derived from this software
16 * without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * Demonstrate the use of the axTLS library in C# with a set of
33 * command-line parameters similar to openssl. In fact, openssl clients
34 * should be able to communicate with axTLS servers and visa-versa.
36 * This code has various bits enabled depending on the configuration. To enable
37 * the most interesting version, compile with the 'full mode' enabled.
39 * To see what options you have, run the following:
40 * > axssl.csharp.exe s_server -?
41 * > axssl.csharp.exe s_client -?
43 * The axtls shared library must be in the same directory or be found
49 using System.Net.Sockets;
57 public static void Main(string[] args)
59 if (args.Length == 1 && args[0] == "version")
61 Console.WriteLine("axssl.csharp " + SSLUtil.Version());
65 axssl runner = new axssl();
67 if (args.Length < 1 || (args[0] != "s_server" && args[0] != "s_client"))
68 runner.print_options(args.Length > 0 ? args[0] : "");
70 int build_mode = SSLUtil.BuildMode();
72 if (args[0] == "s_server")
73 runner.do_server(build_mode, args);
75 runner.do_client(build_mode, args);
81 private void do_server(int build_mode, string[] args)
85 uint options = axtls.SSL_DISPLAY_CERTS;
87 string password = null;
88 string private_key_file = null;
90 /* organise the cert/ca_cert lists */
91 int cert_size = SSLUtil.MaxCerts();
92 int ca_cert_size = SSLUtil.MaxCACerts();
93 string[] cert = new string[cert_size];
94 string[] ca_cert = new string[ca_cert_size];
96 int ca_cert_index = 0;
98 while (i < args.Length)
100 if (args[i] == "-accept")
102 if (i >= args.Length-1)
104 print_server_options(build_mode, args[i]);
107 port = Int32.Parse(args[++i]);
109 else if (args[i] == "-quiet")
112 options &= ~(uint)axtls.SSL_DISPLAY_CERTS;
114 else if (build_mode >= axtls.SSL_BUILD_SERVER_ONLY)
116 if (args[i] == "-cert")
118 if (i >= args.Length-1 || cert_index >= cert_size)
120 print_server_options(build_mode, args[i]);
123 cert[cert_index++] = args[++i];
125 else if (args[i] == "-key")
127 if (i >= args.Length-1)
129 print_server_options(build_mode, args[i]);
132 private_key_file = args[++i];
133 options |= axtls.SSL_NO_DEFAULT_KEY;
135 else if (args[i] == "-pass")
137 if (i >= args.Length-1)
139 print_server_options(build_mode, args[i]);
142 password = args[++i];
144 else if (build_mode >= axtls.SSL_BUILD_ENABLE_VERIFICATION)
146 if (args[i] == "-verify")
148 options |= axtls.SSL_CLIENT_AUTHENTICATION;
150 else if (args[i] == "-CAfile")
152 if (i >= args.Length-1 || ca_cert_index >= ca_cert_size)
154 print_server_options(build_mode, args[i]);
157 ca_cert[ca_cert_index++] = args[++i];
159 else if (build_mode == axtls.SSL_BUILD_FULL_MODE)
161 if (args[i] == "-debug")
163 options |= axtls.SSL_DISPLAY_BYTES;
165 else if (args[i] == "-state")
167 options |= axtls.SSL_DISPLAY_STATES;
169 else if (args[i] == "-show-rsa")
171 options |= axtls.SSL_DISPLAY_RSA;
174 print_server_options(build_mode, args[i]);
177 print_server_options(build_mode, args[i]);
180 print_server_options(build_mode, args[i]);
183 print_server_options(build_mode, args[i]);
188 /* Create socket for incoming connections */
189 IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);
190 TcpListener server_sock = new TcpListener(ep);
193 /**********************************************************************
194 * This is where the interesting stuff happens. Up until now we've
195 * just been setting up sockets etc. Now we do the SSL handshake.
196 **********************************************************************/
197 SSLServer ssl_ctx = new SSLServer(
198 options, axtls.SSL_DEFAULT_SVR_SESS);
202 Console.Error.WriteLine("Error: Server context is invalid");
206 if (private_key_file != null)
208 int obj_type = axtls.SSL_OBJ_RSA_KEY;
210 if (private_key_file.EndsWith(".p8"))
211 obj_type = axtls.SSL_OBJ_PKCS8;
212 else if (private_key_file.EndsWith(".p12"))
213 obj_type = axtls.SSL_OBJ_PKCS12;
215 if (ssl_ctx.ObjLoad(obj_type,
216 private_key_file, password) != axtls.SSL_OK)
218 Console.Error.WriteLine("Private key '" + private_key_file +
224 for (i = 0; i < cert_index; i++)
226 if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CERT,
227 cert[i], null) != axtls.SSL_OK)
229 Console.WriteLine("Certificate '" + cert[i] +
235 for (i = 0; i < ca_cert_index; i++)
237 if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CACERT,
238 ca_cert[i], null) != axtls.SSL_OK)
240 Console.WriteLine("Certificate '" + cert[i] +
253 Console.WriteLine("ACCEPT");
256 Socket client_sock = server_sock.AcceptSocket();
258 SSL ssl = ssl_ctx.Connect(client_sock);
260 /* do the actual SSL handshake */
261 while ((res = ssl_ctx.Read(ssl, out buf)) == axtls.SSL_OK)
263 /* check when the connection has been established */
264 if (ssl.HandshakeStatus() == axtls.SSL_OK)
267 /* could do something else here */
270 if (res == axtls.SSL_OK) /* connection established and ok */
274 display_session_id(ssl);
278 /* now read (and display) whatever the client sends us */
281 /* keep reading until we get something interesting */
282 while ((res = ssl_ctx.Read(ssl, out buf)) == axtls.SSL_OK)
284 /* could do something else here */
287 if (res < axtls.SSL_OK)
291 Console.WriteLine("CONNECTION CLOSED");
297 /* convert to string */
298 char[] str = new char[res];
299 for (i = 0; i < res; i++)
301 str[i] = (char)buf[i];
309 SSLUtil.DisplayError(res);
312 /* client was disconnected or the handshake failed. */
317 /* ssl_ctx.Dispose(); */
323 private void do_client(int build_mode, string[] args)
325 if (build_mode < axtls.SSL_BUILD_ENABLE_CLIENT)
327 print_client_options(build_mode, args[1]);
333 string password = null;
335 string private_key_file = null;
336 string hostname = "127.0.0.1";
338 /* organise the cert/ca_cert lists */
340 int ca_cert_index = 0;
341 int cert_size = SSLUtil.MaxCerts();
342 int ca_cert_size = SSLUtil.MaxCACerts();
343 string[] cert = new string[cert_size];
344 string[] ca_cert = new string[ca_cert_size];
346 uint options = axtls.SSL_SERVER_VERIFY_LATER|axtls.SSL_DISPLAY_CERTS;
347 byte[] session_id = null;
349 while (i < args.Length)
351 if (args[i] == "-connect")
355 if (i >= args.Length-1)
357 print_client_options(build_mode, args[i]);
360 host_port = args[++i];
363 if ((index_colon = host_port.IndexOf(':')) < 0)
364 print_client_options(build_mode, args[i]);
366 hostname = new string(host_port.ToCharArray(),
368 port = Int32.Parse(new String(host_port.ToCharArray(),
369 index_colon+1, host_port.Length-index_colon-1));
371 else if (args[i] == "-cert")
373 if (i >= args.Length-1 || cert_index >= cert_size)
375 print_client_options(build_mode, args[i]);
378 cert[cert_index++] = args[++i];
380 else if (args[i] == "-key")
382 if (i >= args.Length-1)
384 print_client_options(build_mode, args[i]);
387 private_key_file = args[++i];
388 options |= axtls.SSL_NO_DEFAULT_KEY;
390 else if (args[i] == "-CAfile")
392 if (i >= args.Length-1 || ca_cert_index >= ca_cert_size)
394 print_client_options(build_mode, args[i]);
397 ca_cert[ca_cert_index++] = args[++i];
399 else if (args[i] == "-verify")
401 options &= ~(uint)axtls.SSL_SERVER_VERIFY_LATER;
403 else if (args[i] == "-reconnect")
407 else if (args[i] == "-quiet")
410 options &= ~(uint)axtls.SSL_DISPLAY_CERTS;
412 else if (args[i] == "-pass")
414 if (i >= args.Length-1)
416 print_client_options(build_mode, args[i]);
419 password = args[++i];
421 else if (build_mode == axtls.SSL_BUILD_FULL_MODE)
423 if (args[i] == "-debug")
425 options |= axtls.SSL_DISPLAY_BYTES;
427 else if (args[i] == "-state")
429 options |= axtls.SSL_DISPLAY_STATES;
431 else if (args[i] == "-show-rsa")
433 options |= axtls.SSL_DISPLAY_RSA;
436 print_client_options(build_mode, args[i]);
438 else /* don't know what this is */
439 print_client_options(build_mode, args[i]);
444 // IPHostEntry hostInfo = Dns.Resolve(hostname);
445 IPHostEntry hostInfo = Dns.GetHostEntry(hostname);
446 IPAddress[] addresses = hostInfo.AddressList;
447 IPEndPoint ep = new IPEndPoint(addresses[0], port);
448 Socket client_sock = new Socket(AddressFamily.InterNetwork,
449 SocketType.Stream, ProtocolType.Tcp);
450 client_sock.Connect(ep);
452 if (!client_sock.Connected)
454 Console.WriteLine("could not connect");
460 Console.WriteLine("CONNECTED");
463 /**********************************************************************
464 * This is where the interesting stuff happens. Up until now we've
465 * just been setting up sockets etc. Now we do the SSL handshake.
466 **********************************************************************/
467 SSLClient ssl_ctx = new SSLClient(options,
468 axtls.SSL_DEFAULT_CLNT_SESS);
472 Console.Error.WriteLine("Error: Client context is invalid");
476 if (private_key_file != null)
478 int obj_type = axtls.SSL_OBJ_RSA_KEY;
480 if (private_key_file.EndsWith(".p8"))
481 obj_type = axtls.SSL_OBJ_PKCS8;
482 else if (private_key_file.EndsWith(".p12"))
483 obj_type = axtls.SSL_OBJ_PKCS12;
485 if (ssl_ctx.ObjLoad(obj_type,
486 private_key_file, password) != axtls.SSL_OK)
488 Console.Error.WriteLine("Private key '" + private_key_file +
494 for (i = 0; i < cert_index; i++)
496 if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CERT,
497 cert[i], null) != axtls.SSL_OK)
499 Console.WriteLine("Certificate '" + cert[i] +
505 for (i = 0; i < ca_cert_index; i++)
507 if (ssl_ctx.ObjLoad(axtls.SSL_OBJ_X509_CACERT,
508 ca_cert[i], null) != axtls.SSL_OK)
510 Console.WriteLine("Certificate '" + cert[i] +
516 SSL ssl = new SSL(new IntPtr(0)); /* keep compiler happy */
518 /* Try session resumption? */
521 while (reconnect-- > 0)
523 ssl = ssl_ctx.Connect(client_sock, session_id);
525 if ((res = ssl.HandshakeStatus()) != axtls.SSL_OK)
529 SSLUtil.DisplayError(res);
536 display_session_id(ssl);
537 session_id = ssl.GetSessionId();
545 client_sock = new Socket(AddressFamily.InterNetwork,
546 SocketType.Stream, ProtocolType.Tcp);
547 client_sock.Connect(ep);
553 ssl = ssl_ctx.Connect(client_sock, null);
556 /* check the return status */
557 if ((res = ssl.HandshakeStatus()) != axtls.SSL_OK)
561 SSLUtil.DisplayError(res);
570 ssl.GetCertificateDN(axtls.SSL_X509_CERT_COMMON_NAME);
572 if (common_name != null)
574 Console.WriteLine("Common Name:\t\t\t" + common_name);
577 display_session_id(ssl);
583 string user_input = Console.ReadLine();
585 if (user_input == null)
588 byte[] buf = new byte[user_input.Length+2];
589 buf[buf.Length-2] = (byte)'\n'; /* add the carriage return */
590 buf[buf.Length-1] = 0; /* null terminate */
592 for (i = 0; i < buf.Length-2; i++)
594 buf[i] = (byte)user_input[i];
597 if ((res = ssl_ctx.Write(ssl, buf, buf.Length)) < axtls.SSL_OK)
601 SSLUtil.DisplayError(res);
612 * We've had some sort of command-line error. Print out the basic options.
614 private void print_options(string option)
616 Console.WriteLine("axssl: Error: '" + option +
617 "' is an invalid command.");
618 Console.WriteLine("usage: axssl.csharp [s_server|" +
619 "s_client|version] [args ...]");
624 * We've had some sort of command-line error. Print out the server options.
626 private void print_server_options(int build_mode, string option)
628 int cert_size = SSLUtil.MaxCerts();
629 int ca_cert_size = SSLUtil.MaxCACerts();
631 Console.WriteLine("unknown option " + option);
632 Console.WriteLine("usage: s_server [args ...]");
633 Console.WriteLine(" -accept arg\t- port to accept on (default " +
635 Console.WriteLine(" -quiet\t\t- No server output");
637 if (build_mode >= axtls.SSL_BUILD_SERVER_ONLY)
639 Console.WriteLine(" -cert arg\t- certificate file to add (in " +
640 "addition to default) to chain -");
641 Console.WriteLine("\t\t Can repeat up to " + cert_size + " times");
642 Console.WriteLine(" -key arg\t- Private key file to use");
643 Console.WriteLine(" -pass\t\t- private key file pass phrase source");
646 if (build_mode >= axtls.SSL_BUILD_ENABLE_VERIFICATION)
648 Console.WriteLine(" -verify\t- turn on peer certificate " +
650 Console.WriteLine(" -CAfile arg\t- Certificate authority.");
651 Console.WriteLine("\t\t Can repeat up to " +
652 ca_cert_size + "times");
655 if (build_mode == axtls.SSL_BUILD_FULL_MODE)
657 Console.WriteLine(" -debug\t\t- Print more output");
658 Console.WriteLine(" -state\t\t- Show state messages");
659 Console.WriteLine(" -show-rsa\t- Show RSA state");
666 * We've had some sort of command-line error. Print out the client options.
668 private void print_client_options(int build_mode, string option)
670 int cert_size = SSLUtil.MaxCerts();
671 int ca_cert_size = SSLUtil.MaxCACerts();
673 Console.WriteLine("unknown option " + option);
675 if (build_mode >= axtls.SSL_BUILD_ENABLE_CLIENT)
677 Console.WriteLine("usage: s_client [args ...]");
678 Console.WriteLine(" -connect host:port - who to connect to " +
679 "(default is localhost:4433)");
680 Console.WriteLine(" -verify\t- turn on peer certificate " +
682 Console.WriteLine(" -cert arg\t- certificate file to use");
683 Console.WriteLine("\t\t Can repeat up to %d times", cert_size);
684 Console.WriteLine(" -key arg\t- Private key file to use");
685 Console.WriteLine(" -CAfile arg\t- Certificate authority.");
686 Console.WriteLine("\t\t Can repeat up to " + ca_cert_size +
688 Console.WriteLine(" -quiet\t\t- No client output");
689 Console.WriteLine(" -pass\t\t- private key file pass " +
691 Console.WriteLine(" -reconnect\t- Drop and re-make the " +
692 "connection with the same Session-ID");
694 if (build_mode == axtls.SSL_BUILD_FULL_MODE)
696 Console.WriteLine(" -debug\t\t- Print more output");
697 Console.WriteLine(" -state\t\t- Show state messages");
698 Console.WriteLine(" -show-rsa\t- Show RSA state");
703 Console.WriteLine("Change configuration to allow this feature");
710 * Display what cipher we are using
712 private void display_cipher(SSL ssl)
714 Console.Write("CIPHER is ");
716 switch (ssl.GetCipherId())
718 case axtls.SSL_AES128_SHA:
719 Console.WriteLine("AES128-SHA");
722 case axtls.SSL_AES256_SHA:
723 Console.WriteLine("AES256-SHA");
726 case axtls.SSL_RC4_128_SHA:
727 Console.WriteLine("RC4-SHA");
730 case axtls.SSL_RC4_128_MD5:
731 Console.WriteLine("RC4-MD5");
735 Console.WriteLine("Unknown - " + ssl.GetCipherId());
741 * Display what session id we have.
743 private void display_session_id(SSL ssl)
745 byte[] session_id = ssl.GetSessionId();
747 if (session_id.Length > 0)
749 Console.WriteLine("-----BEGIN SSL SESSION PARAMETERS-----");
750 foreach (byte b in session_id)
752 Console.Write("{0:x02}", b);
755 Console.WriteLine("\n-----END SSL SESSION PARAMETERS-----");