private OkHttpClient CreateOkHttpClientInstance() { var builder = new OkHttpClient.Builder() .ConnectTimeout(100, TimeUnit.Seconds) .WriteTimeout(100, TimeUnit.Seconds) .ReadTimeout(100, TimeUnit.Seconds) .CookieJar(new JavaNetCookieJar(new Java.Net.CookieManager())); if (_certificatePinnerBuilder.IsValueCreated) { builder.CertificatePinner(_certificatePinnerBuilder.Value.Build()); } if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { // Support TLS1.2 on Android versions before Lollipop builder.SslSocketFactory(new TlsSslSocketFactory(KeyManagers, TrustManagers), _x509TrustManager ?? TlsSslSocketFactory.GetSystemDefaultTrustManager()); } else if (_keyMgrFactory != null || _trustMgrFactory != null) { var context = SSLContext.GetInstance("TLS"); context.Init(KeyManagers, TrustManagers, null); builder.SslSocketFactory(context.SocketFactory, _x509TrustManager ?? TlsSslSocketFactory.GetSystemDefaultTrustManager()); } return(builder.Build()); }
public void SetClientCertificate(byte[] pkcs12, char[] password) { keyManagers = GetKeyManagersFromClientCert(pkcs12, password); SSLContext newContext = GetSSLContext(); sslContext = newContext; }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void startServer(boolean httpEnabled, boolean httpsEnabled) throws Exception private void StartServer(bool httpEnabled, bool httpsEnabled) { CommunityServerBuilder serverBuilder = serverOnRandomPorts().usingDataDir(Folder.directory(Name.MethodName).AbsolutePath); if (!httpEnabled) { serverBuilder.WithHttpDisabled(); } if (httpsEnabled) { serverBuilder.WithHttpsEnabled(); } _server = serverBuilder.Build(); _server.start(); // Because we are generating a non-CA-signed certificate, we need to turn off verification in the client. // This is ironic, since there is no proper verification on the CA side in the first place, but I digress. TrustManager[] trustAllCerts = new TrustManager[] { new InsecureTrustManager() }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.DefaultSSLSocketFactory = sc.SocketFactory; }
static CURLcode OnSSLContext(SSLContext ctx, Object extraData) { // To do anything useful with the SSLContext object, you'll need // to call the OpenSSL native methods on your own. So for this // demo, we just return what cURL is expecting. return(CURLcode.CURLE_OK); }
SSLContext setupSSL() { // Setup the SSL Context using the JKS file created via gen_test_cert in the java/cert directory MQConnection con = connectToServer(address, "", ""); ErrorCode ec = con.DeleteUser(user); Assert.IsTrue(ec == ErrorCode.EC_NOERROR || ec == ErrorCode.EC_DOESNOTEXIST, "Delete User"); ec = con.CreateUser(user, password, description); Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "Create User"); Console.WriteLine("Adding Identity, user: "******" subject: " + subject); ec = con.AddUserIdentity(subject, issuer, user); Assert.IsTrue(ec == ErrorCode.EC_NOERROR, "AddUserIdentity"); con.Close(); SSLContext ctx = new SSLContext(); ctx.ServerValidator = new RemoteCertificateValidationCallback(SafmqSSLTest.ServerValidator); ctx.CertificateProvider = new LocalCertificateSelectionCallback(SafmqSSLTest.CertificateProvider); X509Certificate c = new X509Certificate(@"e:\blacksheep\safmq.trunk\safmq.net\safmq.net.test\sample.p12", "test"); ctx.ClientCertificateList = new X509CertificateCollection(); ctx.ClientCertificateList.Add(c); X509Certificate2 c2 = new X509Certificate2(@"e:\blacksheep\safmq.trunk\safmq.net\safmq.net.test\sample.p12", "test"); X509Store store = new X509Store(StoreName.My); store.Open(OpenFlags.ReadWrite); store.Add(c2); store.Close(); return(ctx); }
private static SSLSocketFactory SelfSignedSocketFactory() { var trustManager = new SelfSignedTrustManager(); var sslContext = SSLContext.GetInstance("TLS"); sslContext.Init(null, new[] { trustManager }, null); return(sslContext.SocketFactory); }
/// <summary>Initializes the factory.</summary> /// <exception cref="GeneralSecurityException"> /// thrown if an SSL initialization error /// happened. /// </exception> /// <exception cref="System.IO.IOException"> /// thrown if an IO error happened while reading the SSL /// configuration. /// </exception> public virtual void Init() { keystoresFactory.Init(mode); context = SSLContext.GetInstance("TLS"); context.Init(keystoresFactory.GetKeyManagers(), keystoresFactory.GetTrustManagers (), null); context.GetDefaultSSLParameters().SetProtocols(enabledProtocols); hostnameVerifier = GetHostnameVerifier(conf); }
public TlsSslSocketFactory(IKeyManager[] keyManagers = null, ITrustManager[] trustManagers = null) { if (keyManagers != null || trustManagers != null) { var context = SSLContext.GetInstance("TLS"); context.Init(keyManagers, trustManagers, null); _factory = context.SocketFactory; } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private static com.sun.jersey.api.client.Client createClient() throws Exception private static Client CreateClient() { HostnameVerifier hostnameVerifier = HttpsURLConnection.DefaultHostnameVerifier; ClientConfig config = new DefaultClientConfig(); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { new InsecureTrustManager() }, null); config.Properties.put(PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx)); return(Client.create(config)); }
/// <exception cref="Sharpen.NoSuchAlgorithmException"></exception> /// <exception cref="Sharpen.KeyManagementException"></exception> public virtual SSLContext Build() { SSLContext sslcontext = SSLContext.GetInstance(this.protocol != null ? this.protocol : Tls); sslcontext.Init(!keymanagers.IsEmpty() ? Sharpen.Collections.ToArray(keymanagers, new KeyManager[keymanagers.Count]) : null, !trustmanagers.IsEmpty() ? Sharpen.Collections.ToArray (trustmanagers, new TrustManager[trustmanagers.Count]) : null, secureRandom); return(sslcontext); }
/// <summary> /// Sets up the socket factory and hostname verifier to allow all /// certificates for all servers. /// </summary> public static void SetupDangerous() { // we want to use a new trust manager (high risk!) var context = SSLContext.GetInstance("TLSv1.2"); context.Init(null, new ITrustManager[] { new NullX509TrustManager() }, new SecureRandom()); // apply the new context Setup(context.SocketFactory, new NullHostnameVerifier()); }
private SSLSocketFactory GetSocketFactory() { // Create an SSLContext that uses our TrustManager var context = SSLContext.GetInstance("TLSv1.2"); context.Init(null, new ITrustManager[] { new CustomX509TrustManager() }, null); // return the final socket factory return(context.SocketFactory); }
void SetupSSL(HttpsURLConnection httpsConnection) { if (httpsConnection == null) { return; } SSLSocketFactory socketFactory = ConfigureCustomSSLSocketFactory(httpsConnection); if (socketFactory != null) { httpsConnection.SSLSocketFactory = socketFactory; return; } KeyStore keyStore = KeyStore.GetInstance(KeyStore.DefaultType); keyStore.Load(null, null); bool gotCerts = TrustedCerts?.Count > 0; if (gotCerts) { for (int i = 0; i < TrustedCerts.Count; i++) { Certificate cert = TrustedCerts [i]; if (cert == null) { continue; } keyStore.SetCertificateEntry($"ca{i}", cert); } } keyStore = ConfigureKeyStore(keyStore); KeyManagerFactory kmf = ConfigureKeyManagerFactory(keyStore); TrustManagerFactory tmf = ConfigureTrustManagerFactory(keyStore); if (tmf == null) { // If there are no certs and no trust manager factory, we can't use a custom manager // because it will cause all the HTTPS requests to fail because of unverified trust // chain if (!gotCerts) { return; } tmf = TrustManagerFactory.GetInstance(TrustManagerFactory.DefaultAlgorithm); tmf.Init(keyStore); } SSLContext context = SSLContext.GetInstance("TLS"); context.Init(kmf?.GetKeyManagers(), tmf.GetTrustManagers(), null); httpsConnection.SSLSocketFactory = context.SocketFactory; }
/// <summary>Creates default SSL context based on system properties.</summary> /// <remarks> /// Creates default SSL context based on system properties. This method obtains /// default SSL context by calling <code>SSLContext.getInstance("Default")</code>. /// Please note that <code>Default</code> algorithm is supported as of Java 6. /// This method will fall back onto /// <see cref="CreateDefault()">CreateDefault()</see> /// when /// <code>Default</code> algorithm is not available. /// </remarks> /// <returns>default system SSL context</returns> /// <exception cref="Apache.Http.Conn.Ssl.SSLInitializationException"></exception> public static SSLContext CreateSystemDefault() { try { return(SSLContext.GetInstance("Default")); } catch (NoSuchAlgorithmException) { return(CreateDefault()); } }
public void test_NullLogin() { SSLContext ctx = setupSSL(); MQConnection con; try { con = MQBuilder.BuildConnection(simpleAddress, null, null, ctx); con.Close(); } catch (Exception e) { Assert.IsTrue(e == null, "Reconnect with x.509 ident null ident " + e.ToString()); } }
public void test_EmptyPassword() { SSLContext ctx = setupSSL(); MQConnection con; try { con = MQBuilder.BuildConnection(simpleAddress, user, "", ctx); con.Close(); } catch (Exception e) { Assert.IsTrue(e == null, "Connect attempt with x.509 ident, name empty password " + e.ToString()); } }
public CallTrackerTask(string IpAddress, string deviceId) { _ipAddress = "https://" + IpAddress; _deviceId = deviceId; client.RetryOnConnectionFailure = true; SSLContext sslContext = SSLContext.GetInstance("SSL"); ITrustManager[] trustAllCerfs = new ITrustManager[] { new X509TrustManager() }; sslContext.Init(null, trustAllCerfs, new Java.Security.SecureRandom()); client.SetSslSocketFactory(sslContext.SocketFactory); client.SetHostnameVerifier(new HostNameVerifier()); }
public static void acceptUntrusted() { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.Default = sslContext; } catch (Exception ex) { throw new Exception("Could not change SSL TrustManager to accept arbitrary certificates", ex); } }
private OkHttpClient GetUnsafeOkHttpClient() { ITrustManager[] trustAllCerts = new ITrustManager[] { new X509TrustManager() }; SSLContext sslContext = SSLContext.GetInstance("SSL"); sslContext.Init(null, trustAllCerts, null); SSLSocketFactory sslSocketFactory = sslContext.SocketFactory; OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.SetSslSocketFactory(sslSocketFactory); okHttpClient.SetHostnameVerifier(new UnsafeHostnameVerifier()); return(okHttpClient); }
private SSLSocketFactory GetFactory() { if (_factory != null) { return(_factory); } Android.Util.Log.Warn("ModernHttpClient", "ImprovedSSLSocketFactory : creating factory again"); var context = SSLContext.GetInstance("TLS"); context.Init(null, new[] { _trustManager }, null); _factory = context.SocketFactory; return(_factory); }
//https://github.com/square/okhttp/issues/2372#issuecomment-244807676 public static OkHttpClient.Builder EnableTls12OnPreLollipopDevices(this OkHttpClient.Builder builder) { int currentVersion = (int)Build.VERSION.SdkInt; if (currentVersion >= 16 && currentVersion < 22) { try { //Creation of X509TrustManager : https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.Builder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory-javax.net.ssl.X509TrustManager- var trustManagerFactory = TrustManagerFactory.GetInstance(TrustManagerFactory.DefaultAlgorithm); trustManagerFactory.Init((Java.Security.KeyStore)null); var trustManagers = trustManagerFactory.GetTrustManagers(); if (trustManagers.Length != 1) { throw new Java.Lang.IllegalStateException($"Unexpected default trust managers: {trustManagers}"); } var trustManager = trustManagers[0].JavaCast <IX509TrustManager>(); if (trustManager == null) { throw new Java.Lang.IllegalStateException($"Unexpected default trust managers: {trustManagers}"); } var context = SSLContext.GetInstance("TLS"); context.Init(null, new ITrustManager[] { trustManager }, null); builder.SslSocketFactory(new ImprovedSSLSocketFactory(context.SocketFactory, trustManager), trustManager); ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.ModernTls) .TlsVersions(TlsVersion.Tls12) .Build(); List <ConnectionSpec> connexionSpecs = new List <ConnectionSpec> { new ConnectionSpec.Builder(ConnectionSpec.ModernTls).TlsVersions(TlsVersion.Tls12).Build(), ConnectionSpec.ModernTls, ConnectionSpec.CompatibleTls, ConnectionSpec.Cleartext, }; builder.ConnectionSpecs(connexionSpecs); } catch (Exception ex) { Android.Util.Log.Warn("ModernHttpClient", $"Unable to enable TLS 1.2 on okhttpclient: {ex}"); } } return(builder); }
public void test_BadPassword() { SSLContext ctx = setupSSL(); MQConnection con; try { con = MQBuilder.BuildConnection(simpleAddress, user, "12345", ctx); con.Close(); } catch (MQException e) { Assert.IsTrue(e.getErrorcode() == ErrorCode.EC_NOTAUTHORIZED, "Reconnect with x.509 ident, name wrong password" + e.ToString()); } catch (Exception e) { Assert.IsTrue(false, "Connect attempt with x.509 ident, name wrong password" + e.ToString()); // this is the correct case } }
private Socket CreateSecureSocket() { try { SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[0], new TrustManager[] { new NaiveTrustManager(_serverCertificatesSeen.add) }, new SecureRandom()); return(context.SocketFactory.createSocket()); } catch (Exception e) { throw new Exception(e); } }
public NativeMessageHandler(bool throwOnCaptiveNetwork, CustomSSLVerification customSSLVerification, NativeCookieHandler cookieHandler = null) { this.throwOnCaptiveNetwork = throwOnCaptiveNetwork; var clientBuilder = client.NewBuilder(); var specsBuilder = new ConnectionSpec.Builder(ConnectionSpec.ModernTls).TlsVersions(TlsVersion.Tls12); var specs = specsBuilder.Build(); clientBuilder.ConnectionSpecs(new List <ConnectionSpec>() { specs }); clientBuilder.Protocols(new[] { Protocol.Http11 }); // Required to avoid stream was reset: PROTOCOL_ERROR clientBuilder.HostnameVerifier(new HostnameVerifier(customSSLVerification.Pins)); this.CertificatePinnerBuilder = new CertificatePinner.Builder(); // Add Certificate Pins foreach (var pin in customSSLVerification.Pins) { this.CertificatePinnerBuilder.Add(pin.Hostname, pin.PublicKeys); } clientBuilder.CertificatePinner(CertificatePinnerBuilder.Build()); // Set client credentials SetClientCertificate(customSSLVerification.ClientCertificate); // Set SslSocketFactory if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { // Support TLS1.2 on Android versions before Lollipop clientBuilder.SslSocketFactory(new TlsSslSocketFactory(KeyManagers, null), TlsSslSocketFactory.GetSystemDefaultTrustManager()); } else { var sslContext = SSLContext.GetInstance("TLS"); sslContext.Init(KeyManagers, null, null); clientBuilder.SslSocketFactory(sslContext.SocketFactory, TlsSslSocketFactory.GetSystemDefaultTrustManager()); } if (cookieHandler != null) { clientBuilder.CookieJar(cookieHandler); } client = clientBuilder.Build(); }
public Communicator() { trustAllSslContext = SSLContext.GetInstance("SSL"); trustAllSslContext.Init(null, new ITrustManager[] { new CustomX509TrustManager() }, new SecureRandom()); client = new OkHttpClient(); client.SetConnectTimeout(5, Java.Util.Concurrent.TimeUnit.Seconds); client.SetSslSocketFactory(trustAllSslContext.SocketFactory); client.SetHostnameVerifier(new CustomHostNameVerifier()); client.SetProtocols(new Protocol[] { Protocol.Http11 }); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build(); StrictMode.SetThreadPolicy(policy); }
private void SetHandler() { var algoritm = TrustManagerFactory.DefaultAlgorithm; var trustManagerFactory = TrustManagerFactory.GetInstance(algoritm); trustManagerFactory.Init((KeyStore)null); var tm = new ITrustManager[] { new PublicKeyManager() }; SSLContext sslContext = SSLContext.GetInstance("TLS"); sslContext.Init(null, tm, null); SSLContext.Default = sslContext; HttpsURLConnection.DefaultSSLSocketFactory = sslContext.SocketFactory; }
public static void TrustEveryone() { try { HttpsURLConnection.DefaultHostnameVerifier = new HostnameVerifier(); SSLContext context = SSLContext.GetInstance("TLS"); context.Init(null, new ITrustManager[] { new MyX509TrustManager() }, new SecureRandom()); HttpsURLConnection.DefaultSSLSocketFactory = context.SocketFactory; } catch (Exception exc) { ToLog?.Invoke($"{nameof(TrustEveryone)}", $"{exc.Message}"); } }
public void Open(string url, string protocol, IDictionary <string, string> headers) { try { var ssl = SSLContext.GetInstance("TLS"); ssl.Init(null, null, null); _controller = new BridgeController(ssl); _controller.Proxy = this; _controller.Open(url, protocol, headers); } catch (Exception ex) { OnError(ex.Message); } }
private void AllowAllHosts() { // Setting TrustAll trust manager and AllowAllHostNameVerifier ITrustManager[] trustAllCerts = new ITrustManager[] { new AllowAllTrustManager() }; try { SSLContext sc = SSLContext.GetInstance("SSL"); sc.Init(null, trustAllCerts, new Java.Security.SecureRandom()); HttpsURLConnection.DefaultSSLSocketFactory = sc.SocketFactory; HttpsURLConnection.DefaultHostnameVerifier = new AllowAllHostNameVerifier(); } catch (Exception e) { Log.Error(TAG, "Exception during setting TrustAll key manager", e); } }
private static void trustAllHosts() { ITrustManager[] trustAllCerts = new TrustManager[] { }; try { SSLContext e = SSLContext.GetInstance("TLS"); e.Init((IKeyManager[])null, trustAllCerts, new SecureRandom()); HttpsURLConnection.DefaultSSLSocketFactory = e.SocketFactory; } catch (Java.Lang.Exception var2) { var2.PrintStackTrace(); } }