Skip to content

Instantly share code, notes, and snippets.

@ali-ince
Last active May 9, 2018 13:56
Show Gist options
  • Save ali-ince/c2aeb9bbec1dee79f641e4ac53c072af to your computer and use it in GitHub Desktop.
Save ali-ince/c2aeb9bbec1dee79f641e4ac53c072af to your computer and use it in GitHub Desktop.
SNI Test Code
using System;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace SNI.Test.Local
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
args = new[] {"https://localhost"};
}
Console.WriteLine(RuntimeInformation.FrameworkDescription);
Console.WriteLine(GetCommonName(new Uri(args[0])));
Console.WriteLine("Finished.");
Console.ReadLine();
}
private static string certSubject = null;
private static string GetCommonName(Uri uri)
{
var ipAddresses = Dns.GetHostAddressesAsync(uri.Host).GetAwaiter().GetResult();
foreach (var ipAddress in ipAddresses)
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipAddress, uri.Port);
using (var stream = new NetworkStream(socket, true))
{
using (var tlsStream = new SslStream(stream, true, UserCertificateValidationCallback,
LocalCertificateSelectionCallback, EncryptionPolicy.RequireEncryption))
{
tlsStream.AuthenticateAsClientAsync(uri.Host, null, SslProtocols.Tls12, false).GetAwaiter().GetResult();
}
}
return certSubject;
}
catch (Exception e)
{
return null;
}
}
return null;
}
private static bool UserCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{
certSubject = certificate.Subject;
return true;
}
private static X509Certificate LocalCertificateSelectionCallback(object sender, string targethost, X509CertificateCollection localcertificates, X509Certificate remotecertificate, string[] acceptableissuers)
{
return null;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp1.0;net452</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.InteropServices.RuntimeInformation" Version="4.0.0" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment