예제 #1
0
//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;
        }
예제 #2
0
//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));
        }
예제 #3
0
 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);
     }
 }
예제 #4
0
        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);
            }
        }
예제 #5
0
 /// <summary>
 /// Create a Jersey HTTP client that is able to talk HTTPS and trusts all certificates.
 /// </summary>
 /// <returns> new client. </returns>
 private static Client CreateClient()
 {
     try
     {
         HostnameVerifier hostnameVerifier = HttpsURLConnection.DefaultHostnameVerifier;
         ClientConfig     config           = new DefaultClientConfig();
         SSLContext       ctx = SSLContext.getInstance("TLS");
         ctx.init(null, new TrustManager[] { new InsecureTrustManager() }, null);
         IDictionary <string, object> properties = config.Properties;
         properties[PROPERTY_HTTPS_PROPERTIES] = new HTTPSProperties(hostnameVerifier, ctx);
         properties[PROPERTY_FOLLOW_REDIRECTS] = false;
         return(Client.create(config));
     }
     catch (Exception e)
     {
         throw new Exception(e);
     }
 }
예제 #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void main(String[] paramArrayOfString) throws Exception
        public static void Main(string[] paramArrayOfString)
        {
            bool @bool;

            char[] arrayOfChar;
            char   c;
            string str1;

            if (paramArrayOfString.Length == 1 || paramArrayOfString.Length == 2)
            {
                string[] arrayOfString = paramArrayOfString[0].Split(":", true);
                str1 = arrayOfString[0];
                c    = (arrayOfString.Length == 1) ? (char)443 : (char)int.Parse(arrayOfString[1]);
                string str = (paramArrayOfString.Length == 1) ? "changeit" : paramArrayOfString[1];
                arrayOfChar = str.ToCharArray();
            }
            else
            {
                Console.WriteLine("Usage: java InstallCert [:port] [passphrase]");
                return;
            }
            File file = new File("jssecacerts");

            if (!file.File)
            {
                char c1    = Path.DirectorySeparatorChar;
                File file1 = new File(System.getProperty("java.home") + c1 + "lib" + c1 + "security");
                file = new File(file1, "jssecacerts");
                if (!file.File)
                {
                    file = new File(file1, "cacerts");
                }
            }
            Console.WriteLine("Loading KeyStore " + file + "...");
            FileStream fileInputStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            KeyStore   keyStore        = KeyStore.getInstance(KeyStore.DefaultType);

            keyStore.load(fileInputStream, arrayOfChar);
            fileInputStream.Close();
            SSLContext          sSLContext          = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.DefaultAlgorithm);

            trustManagerFactory.init(keyStore);
            X509TrustManager   x509TrustManager   = (X509TrustManager)trustManagerFactory.TrustManagers[0];
            SavingTrustManager savingTrustManager = new SavingTrustManager(x509TrustManager);

            sSLContext.init(null, new TrustManager[] { savingTrustManager }, null);
            SSLSocketFactory sSLSocketFactory = sSLContext.SocketFactory;

            Console.WriteLine("Opening connection to " + str1 + ":" + c + "...");
            SSLSocket sSLSocket = (SSLSocket)sSLSocketFactory.createSocket(str1, c);

            sSLSocket.SoTimeout = 10000;
            try
            {
                Console.WriteLine("Starting SSL handshake...");
                sSLSocket.startHandshake();
                sSLSocket.close();
                Console.WriteLine();
                Console.WriteLine("No errors, certificate is already trusted");
            }
            catch (SSLException sSLException)
            {
                Console.WriteLine();
                sSLException.printStackTrace(System.out);
            }
            X509Certificate[] arrayOfX509Certificate = savingTrustManager.chain;
            if (arrayOfX509Certificate == null)
            {
                Console.WriteLine("Could not obtain server certificate chain");
                return;
            }
            StreamReader bufferedReader = new StreamReader(System.in);

            Console.WriteLine();
            Console.WriteLine("Server sent " + arrayOfX509Certificate.Length + " certificate(s):");
            Console.WriteLine();
            MessageDigest messageDigest1;
            MessageDigest messageDigest2 = (messageDigest1 = MessageDigest.getInstance("SHA1")).getInstance("MD5");

            for (sbyte b = 0; b < arrayOfX509Certificate.Length; b++)
            {
                X509Certificate x509Certificate1 = arrayOfX509Certificate[b];
                Console.WriteLine(" " + (b + true) + " Subject " + x509Certificate1.SubjectDN);
                Console.WriteLine("   Issuer  " + x509Certificate1.IssuerDN);
                messageDigest1.update(x509Certificate1.Encoded);
                Console.WriteLine("   sha1    " + toHexString(messageDigest1.digest()));
                messageDigest2.update(x509Certificate1.Encoded);
                Console.WriteLine("   md5     " + toHexString(messageDigest2.digest()));
                Console.WriteLine();
            }
            Console.WriteLine("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
            string str2 = bufferedReader.ReadLine().Trim();

            try
            {
                @bool = (str2.Length == 0) ? 0 : (int.Parse(str2) - 1);
            }
            catch (System.FormatException)
            {
                Console.WriteLine("KeyStore not changed");
                return;
            }
            X509Certificate x509Certificate = arrayOfX509Certificate[@bool];
            string          str3            = str1 + "-" + (@bool + true);

            keyStore.setCertificateEntry(str3, x509Certificate);
            FileStream fileOutputStream = new FileStream("jssecacerts", FileMode.Create, FileAccess.Write);

            keyStore.store(fileOutputStream, arrayOfChar);
            fileOutputStream.Close();
            Console.WriteLine();
            Console.WriteLine(x509Certificate);
            Console.WriteLine();
            Console.WriteLine("Added certificate to keystore 'jssecacerts' using alias '" + str3 + "'");
        }
예제 #7
0
        public string UploadString(Uri u, string method, string data)
        {
            // http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/tip/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java
            // fails on openJDK why?

            Console.WriteLine("enter UploadString " + new { u, method });

            var w = new StringBuilder();

            HttpURLConnection xHttpURLConnection = null;

            try
            {
                #region NSA is that you? intercept? we can only trust pinned off device certs
                var trustAllCerts = new[] {
                    new localX509TrustManager {
                    }
                };

                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

                HttpsURLConnection.setDefaultHostnameVerifier(new localHostnameVerifier {
                });
                #endregion


                //UploadString getOutputStream
                //enter checkServerTrusted
                //enter getAcceptedIssuers
                //UploadString writeBytes

                var url = new java.net.URL(u.ToString());

                xHttpURLConnection = (HttpURLConnection)url.openConnection();



                var https = xHttpURLConnection as HttpsURLConnection;
                if (https != null)
                {
                    //Console.WriteLine(new { https });
                }


                //conn.setHostnameVerifier(new localHostnameVerifier { });

                xHttpURLConnection.setDoOutput(true);
                xHttpURLConnection.setDoInput(true);
                xHttpURLConnection.setInstanceFollowRedirects(false);
                //conn.setInstanceFollowRedirects(true);

                xHttpURLConnection.setRequestMethod(method);


                var xContentType = default(string);


                try
                {
                    if (Headers != null)
                    {
                        foreach (string key in Headers.AllKeys)
                        {
                            if (key == "Content-Type")
                            {
                                xContentType = Headers[key];
                            }


                            xHttpURLConnection.addRequestProperty(key, Headers[key]);
                        }
                    }
                }
                catch (Exception e)
                {
                    //System.Console.WriteLine("ERROR: Failed to write headers. Exception was:" + e.Message);
                }

                if (xContentType == null)
                {
                    xHttpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    xHttpURLConnection.setRequestProperty("charset", "utf-8");
                }

                //conn.setRequestProperty("content-length", "" + data.Length);
                xHttpURLConnection.setRequestProperty("Content-Length", "" + data.Length);

                xHttpURLConnection.setUseCaches(false);


                //Console.WriteLine("UploadString getOutputStream");
                var o = xHttpURLConnection.getOutputStream();

                //Console.WriteLine("UploadString writeBytes");

                //
                DataOutputStream wr = new DataOutputStream(o);
                wr.writeBytes(data);
                //Console.WriteLine("UploadString flush");
                wr.flush();
                //Console.WriteLine("UploadString close");
                wr.close();


                //Console.WriteLine("UploadString readLine");

                //var i = new java.io.InputStreamReader(url.openStream(), "UTF-8");
                var i      = new java.io.InputStreamReader(xHttpURLConnection.getInputStream(), "UTF-8");
                var reader = new java.io.BufferedReader(i);

                // can't we just read to the end?
                var line = reader.readLine();
                while (line != null)
                {
                    w.AppendLine(line);

                    line = reader.readLine();
                }
                reader.close();
            }
            catch (Exception err)
            {
                // 500 ?

                // = java.net.ProtocolException: Invalid HTTP method:

                // oops
                Console.WriteLine("UploadString " + new { err });
            }

            //Console.WriteLine("exit UploadString " + new { conn });

            if (xHttpURLConnection != null)
            {
                xHttpURLConnection.disconnect();
            }

            return(w.ToString());
        }
예제 #8
0
        private SSLSocketFactory getSSLSocketFactory()
        {
            SSLSocketFactory factory = null;

            try
            {
                //reading the keyStore path and password from the environment properties
                string keyStorePath = java.lang.System.getProperty("javax.net.ssl.keyStore");
                java.io.FileInputStream keyStoreStream = null;
                if (keyStorePath != null)
                {
                    java.io.File file = new java.io.File(keyStorePath);
                    if (file.exists())
                    {
                        keyStoreStream = new java.io.FileInputStream(file);
                    }
                    else
                    {
                        keyStoreStream = searchDefaultCacerts();
                    }
                }
                else
                {
                    keyStoreStream = searchDefaultCacerts();
                }

                string keyStorePassWord = java.lang.System.getProperty("javax.net.ssl.keyStorePassword");
                if (keyStorePassWord == null)
                {
                    keyStorePassWord = "******";
                }
                char[] passphrase = keyStorePassWord.ToCharArray();

                //initiating SSLContext
                SSLContext          ctx = SSLContext.getInstance("TLS");
                KeyManagerFactory   kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore            ks  = KeyStore.getInstance("JKS");
                if (keyStoreStream != null)
                {
                    ks.load(keyStoreStream, passphrase);
                }
                else
                {
                    ks.load(null, null);
                }
                kmf.init(ks, passphrase);
                tmf.init(ks);
                ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                factory = ctx.getSocketFactory();
            }
            catch (Exception e)
            {
                factory = null;
#if DEBUG
                Console.WriteLine("Can't get SSL Socket Factory, the exception is {0}, {1}", e.GetType(), e.Message);
#endif
            }

            return(factory);
        }