Beispiel #1
1
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SslProtocols protocol = SslProtocols.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SslProtocols.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate2(args [2], password));
				break;
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection));

		ssl.AuthenticateAsClient (host, certificates, protocol, false); 	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
Beispiel #2
0
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SecurityProtocolType protocol = SecurityProtocolType.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SecurityProtocolType.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate(cert.RawData));
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslClientStream ssl = new SslClientStream (client.GetStream(), host, false, protocol, certificates);
 		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);
 		ssl.ClientCertSelectionDelegate += new CertificateSelectionCallback (ClientCertificateSelection);
 		ssl.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (PrivateKeySelection);
	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
		protected virtual X509CertificateCollection GetCertificates ()
		{
			var certificates = new X509CertificateCollection ();
			if (Config.Certificate != null)
				certificates.Add (Config.Certificate);
			return certificates;
		}
        public bool Connect(string host, int port)
        {
            Host = host;
            Port = port;


            IPEndPoint myEnd = null;

            try
            {
                myEnd = new IPEndPoint(IPAddress.Parse(host), port);
            }
            catch (FormatException)
            {
                foreach (IPAddress s in Dns.GetHostAddresses(host))
                {
                    if (!s.IsIPv6LinkLocal)
                    {
                        myEnd = new IPEndPoint(s, port);
                    }
                }
            }


            try
            {
                TcpClient.Connect(myEnd.Address, Port);
            }
            catch (Exception er)
            {
                if (ErrorLog != null)
                {
                    ErrorLog(er.Message);
                }

                return(false);
            }


            SslStreamx = new SslStream(TcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

            X509CertificateCollection certs = null;

            if (CertPath != null)
            {
                certs = new X509CertificateCollection();
                X509Certificate cert = X509Certificate.CreateFromCertFile(CertPath);
                certs.Add(cert);
            }
            else
            {
                certs = GetCerts();
            }

            try
            {
                if (SSLHost == null)
                {
                    SslStreamx.AuthenticateAsClient(Host, certs, SslProtocols.Tls, false);
                }
                else
                {
                    SslStreamx.AuthenticateAsClient(SSLHost, certs, SslProtocols.Tls, false);
                }
            }
            catch (AuthenticationException e)
            {
                if (ErrorLog != null)
                {
                    ErrorLog("Exception:" + e.Message);
                }


                if (e.InnerException != null)
                {
                    if (ErrorLog != null)
                    {
                        ErrorLog("Inner exception:" + e.InnerException.Message);
                    }
                }

                TcpClient.Close();
                return(false);
            }

            return(true);
        }
Beispiel #5
0
        static X509CertificateCollection LoadCertificates(string filename, string password, bool verbose)
        {
            X509Certificate           x509 = null;
            X509CertificateCollection coll = new X509CertificateCollection();

            switch (Path.GetExtension(filename).ToUpper())
            {
            case ".P7B":
            case ".SPC":
                SoftwarePublisherCertificate spc = SoftwarePublisherCertificate.CreateFromFile(filename);
                coll.AddRange(spc.Certificates);
                spc = null;
                break;

            case ".CER":
            case ".CRT":
                using (FileStream fs = File.OpenRead(filename)) {
                    byte[] data = new byte [fs.Length];
                    fs.Read(data, 0, data.Length);
                    if (data [0] != 0x30)
                    {
                        // maybe it's ASCII PEM base64 encoded ?
                        data = PEM("CERTIFICATE", data);
                    }
                    if (data != null)
                    {
                        x509 = new X509Certificate(data);
                    }
                }
                if (x509 != null)
                {
                    coll.Add(x509);
                }
                break;

            case ".P12":
            case ".PFX":
                PKCS12 p12 = password == null?PKCS12.LoadFromFile(filename)
                                 : PKCS12.LoadFromFile(filename, password);

                X509CertificateCollection tmp = new X509CertificateCollection(p12.Certificates);

                for (int i = 0; i != p12.Keys.Count; i++)
                {
                    X509Certificate          cert = p12.Certificates[i];
                    RSACryptoServiceProvider pk   = p12.Keys[i] as RSACryptoServiceProvider;

                    if (pk == null || pk.PublicOnly)
                    {
                        continue;
                    }

                    if (verbose)
                    {
                        Console.WriteLine("Found key for certificate: {0}", cert.SubjectName);
                    }

                    tmp[0].RSA = pk;
                }
                coll.AddRange(tmp);
                p12 = null;
                break;

            default:
                Console.WriteLine("Unknown file extension: {0}",
                                  Path.GetExtension(filename));
                break;
            }
            return(coll);
        }
Beispiel #6
0
        public static void X509CertificateCollectionAsIList()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            {
                IList il = new X509CertificateCollection();
                il.Add(c1);
                il.Add(c2);

                Assert.Throws<ArgumentNullException>(() => il[0] = null);

                string bogus = "Bogus";
                Assert.Throws<ArgumentException>(() => il[0] = bogus);
                Assert.Throws<ArgumentException>(() => il.Add(bogus));
                Assert.Throws<ArgumentException>(() => il.Insert(0, bogus));
            }
        }
Beispiel #7
0
 static void ProvideClientCertificatesCallback(X509CertificateCollection clientCerts)
 {
     clientCerts.Add(new X509Certificate2("/certs/client.root.pk12"));
 }
Beispiel #8
0
        /// <summary>
        /// Delegete handler to process SSL Communications over LDAP.
        /// This allows the user to accept or reject a certificate chain
        /// Thus the certificate Auth Authority does not have to pre-exist in the truststore
        /// </summary>
        /// <param name="certificate">
        /// A <see cref="Syscert.X509Certificate"/>
        /// </param>
        /// <param name="certificateErrors">
        /// A <see cref="System.Int32[]"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.Boolean"/>
        /// </returns>
        private bool MySSLHandler(Syscert.X509Certificate certificate, int[] certificateErrors)
        {
            Logger.Debug("calling MySSLHandler()");
            X509Store store = null;
            X509Stores stores = X509StoreManager.CurrentUser;
            String input;
            store = stores.TrustedRoot;

            //Import the details of the certificate from the server.

            X509Certificate x509 = null;
            X509CertificateCollection coll = new X509CertificateCollection ();
            Logger.Debug("calling GetRawCertData()");
            byte[] data = certificate.GetRawCertData();
            if (data != null)
                x509 = new X509Certificate (data);

            //List the details of the Server

            //check for ceritficate in store
            X509CertificateCollection check = store.Certificates;
            if(!check.Contains(x509))
            {
                if(bindCount == 1)
                {
                    Console.WriteLine ( " \n\nCERTIFICATE DETAILS: \n" );
                    Console.WriteLine ( " {0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " :
                                                                       String.Empty), x509.Version);
                    Console.WriteLine ( "  Serial Number: {0}", CryptoConvert.ToHex (x509.SerialNumber));
                    Console.WriteLine ( "  Issuer Name:   {0}", x509.IssuerName);
                    Console.WriteLine ( "  Subject Name:  {0}", x509.SubjectName);
                    Console.WriteLine ( "  Valid From:    {0}", x509.ValidFrom);
                    Console.WriteLine ( "  Valid Until:   {0}", x509.ValidUntil);
                    Console.WriteLine ( "  Unique Hash:   {0}", CryptoConvert.ToHex (x509.Hash));

                }

                //Get the response from the Client
                do
                {
                    Console.WriteLine("\nDo you want to proceed with the connection (y/n)?");
                    input = Console.ReadLine();

                    if(input=="y" || input == "Y")
                        bHowToProceed = true;

                    if(input=="n" || input == "N")
                        bHowToProceed = false;

                }while(input!="y" && input != "Y" && input !="n" && input != "N");
            }
            else
            {
                if(bHowToProceed == true)
                {
                    //Add the certificate to the store.

                    if (x509 != null)
                        coll.Add (x509);
                    store.Import (x509);
                    if(bindCount == 1)
                        removeFlag = true;
                }
            }

            if(bHowToProceed == false)
            {
                //Remove the certificate added from the store.

                if(removeFlag == true && bindCount > 1)
                {
                    foreach (X509Certificate xt509 in store.Certificates) {
                        if (CryptoConvert.ToHex (xt509.Hash) == CryptoConvert.ToHex (x509.Hash)) {
                            store.Remove (x509);
                        }
                    }
                }
                Console.WriteLine("SSL Bind Failed.");
            }
            return bHowToProceed;
        }
Beispiel #9
0
        public static void X509CertificateCollectionInsertAndClear()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection();
                cc.Insert(0, c1);
                cc.Insert(1, c2);
                cc.Insert(2, c3);
                Assert.Equal(3, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c3, cc[2]);

                cc.Clear();
                Assert.Equal(0, cc.Count);

                cc.Add(c1);
                cc.Add(c3);
                Assert.Equal(2, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c3, cc[1]);

                cc.Insert(1, c2);
                Assert.Equal(3, cc.Count);
                Assert.Same(c1, cc[0]);
                Assert.Same(c2, cc[1]);
                Assert.Same(c3, cc[2]);

                cc.Clear();
                Assert.Equal(0, cc.Count);

                IList il = cc;
                il.Insert(0, c1);
                il.Insert(1, c2);
                il.Insert(2, c3);
                Assert.Equal(3, il.Count);
                Assert.Same(c1, il[0]);
                Assert.Same(c2, il[1]);
                Assert.Same(c3, il[2]);

                il.Clear();
                Assert.Equal(0, il.Count);

                il.Add(c1);
                il.Add(c3);
                Assert.Equal(2, il.Count);
                Assert.Same(c1, il[0]);
                Assert.Same(c3, il[1]);

                il.Insert(1, c2);
                Assert.Equal(3, il.Count);
                Assert.Same(c1, il[0]);
                Assert.Same(c2, il[1]);
                Assert.Same(c3, il[2]);

                il.Clear();
                Assert.Equal(0, il.Count);
            }
        }
Beispiel #10
0
        protected override bool Connect()
        {
            var destinationPublicIdentity = scheduler.LookupPublicKey(destinationPublicKey);

            if (destinationPublicIdentity == null)
            {
                if (scheduler.Verbose)
                {
                    Console.Error.WriteLine("Could not connect to destination public key {0} because we don't know its address.",
                                            IoScheduler.PublicKeyToString(destinationPublicKey));
                }
                return(false);
            }

            if (scheduler.Verbose)
            {
                Console.WriteLine("Starting connection to {0}", IoScheduler.PublicIdentityToString(destinationPublicIdentity));
            }

            TcpClient client;

            try
            {
                client = new TcpClient(destinationPublicIdentity.HostNameOrAddress, destinationPublicIdentity.Port);
            }
            catch (Exception e)
            {
                scheduler.ReportException(e, "connecting to " + IoScheduler.PublicIdentityToString(destinationPublicIdentity));
                return(false);
            }

            var myCertificateCollection = new X509CertificateCollection();

            myCertificateCollection.Add(scheduler.MyCert);
            var myValidator = new CertificateValidator(scheduler, destinationPublicIdentity);

            try {
                stream = new SslStream(client.GetStream(), leaveInnerStreamOpen: false, myValidator.ValidateSSLCertificate);
                stream.AuthenticateAsClient(destinationPublicIdentity.FriendlyName, myCertificateCollection,
                                            checkCertificateRevocation: false);
            }
            catch (Exception e) {
                scheduler.ReportException(e, "authenticating connection to " + IoScheduler.PublicIdentityToString(destinationPublicIdentity));
                return(false);
            }

            remoteCert = stream.RemoteCertificate as X509Certificate2;

            if (!ByteArrayComparer.Default().Equals(IoScheduler.GetCertificatePublicKey(remoteCert), destinationPublicKey))
            {
                Console.Error.WriteLine("Connected to {0} expecting public key {1} but found public key {2}, so disconnecting.",
                                        IoScheduler.PublicIdentityToString(destinationPublicIdentity),
                                        IoScheduler.PublicKeyToString(destinationPublicKey),
                                        IoScheduler.PublicKeyToString(IoScheduler.GetCertificatePublicKey(remoteCert)));
                return(false);
            }

            if (scheduler.Verbose)
            {
                Console.WriteLine("Successfully connected to {0} and got certificate identifying it as {1}",
                                  IoScheduler.PublicIdentityToString(destinationPublicIdentity),
                                  IoScheduler.CertificateToString(remoteCert));
            }

            // Now that the connection is successful, create a thread to
            // receive packets on it.

            ReceiverThread receiverThread = ReceiverThread.Create(scheduler, stream);

            return(true);
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            StringBuilder builder = new StringBuilder();

            //Get the stream from the document.
            Stream docStream = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SignedDocument.pdf");

            //Load the PDF document into the loaded document object.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream);

            //Get signature field
            PdfLoadedSignatureField lSigFld = loadedDocument.Form.Fields[0] as PdfLoadedSignatureField;

            //Get the certificate stream from .pfx file.
            Stream certificateStream = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx");

            byte[] data = new byte[certificateStream.Length];
            certificateStream.Read(data, 0, data.Length);

            //Create new X509Certificate2 with the root certificate
            X509Certificate2 certificate = new X509Certificate2(data, "password123");

            //X509Certificate2Collection to check the signer's identity using root certificates
            X509CertificateCollection collection = new X509CertificateCollection();

            //Add the certificate to the collection
            collection.Add(certificate);

            //Validate signature and get the validation result
            PdfSignatureValidationResult result = lSigFld.ValidateSignature(collection);

            builder.AppendLine("Signature is " + result.SignatureStatus);
            builder.AppendLine();
            builder.AppendLine("--------Validation Summary--------");
            builder.AppendLine();

            //Checks whether the document is modified or not
            bool isModified = result.IsDocumentModified;

            if (isModified)
            {
                builder.AppendLine("The document has been altered or corrupted since the signature was applied.");
            }
            else
            {
                builder.AppendLine("The document has not been modified since the signature was applied.");
            }

            //Signature details
            builder.AppendLine("Digitally signed by " + lSigFld.Signature.Certificate.IssuerName);
            builder.AppendLine("Valid From : " + lSigFld.Signature.Certificate.ValidFrom);
            builder.AppendLine("Valid To : " + lSigFld.Signature.Certificate.ValidTo);
            builder.AppendLine("Signature Algorithm : " + result.SignatureAlgorithm);
            builder.AppendLine("Hash Algorithm : " + result.DigestAlgorithm);

            //Revocation validation details
            builder.AppendLine("OCSP revocation status : " + result.RevocationResult.OcspRevocationStatus);
            if (result.RevocationResult.OcspRevocationStatus == RevocationStatus.None && result.RevocationResult.IsRevokedCRL)
            {
                builder.AppendLine("CRL is revoked.");
            }

            this.resultView.Text = builder.ToString();

            //Close the document
            loadedDocument.Close(true);
        }
Beispiel #12
0
        /// <summary>
        /// Initiates the Connection to the Feedback Server and receives all Feedback data then closes the connection
        /// </summary>
        public void Run()
        {
            disposing = false;

            encoding = Encoding.ASCII;

            // certificate will already be set if one of the constructors that takes a byte array was used.
            if (certificate == null)
            {
                // Fixed by [email protected] :
                //      The default is UserKeySet, which has caused internal encryption errors,
                //      Because of lack of permissions on most hosting services.
                //      So MachineKeySet should be used instead.
                certificate = new X509Certificate2(System.IO.File.ReadAllBytes(P12File), P12FilePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            }

            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            if (ensureConnected() && !disposing)
            {
                //Set up
                byte[]   buffer       = new byte[38];
                int      recd         = 0;
                DateTime minTimestamp = DateTime.Now.AddYears(-1);

                //Get the first feedback
                recd = apnsStream.Read(buffer, 0, buffer.Length);

                //Continue while we have results and are not disposing
                while (recd > 0 && !disposing)
                {
                    try
                    {
                        Feedback fb = new Feedback();

                        //Get our seconds since 1970 ?
                        byte[] bSeconds     = new byte[4];
                        byte[] bDeviceToken = new byte[32];

                        Array.Copy(buffer, 0, bSeconds, 0, 4);

                        //Check endianness
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(bSeconds);
                        }

                        int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                        //Add seconds since 1970 to that date, in UTC and then get it locally
                        fb.Timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds).ToLocalTime();


                        //Now copy out the device token
                        Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                        fb.DeviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                        //Make sure we have a good feedback tuple
                        if (fb.DeviceToken.Length == 64 &&
                            fb.Timestamp > minTimestamp &&
                            this.Feedback != null)
                        {
                            //Raise event
                            this.Feedback(this, fb);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (this.Error != null)
                        {
                            this.Error(this, ex);
                        }
                    }

                    //Clear our array to reuse it
                    Array.Clear(buffer, 0, buffer.Length);

                    //Read the next feedback
                    recd = apnsStream.Read(buffer, 0, buffer.Length);
                }
            }

            ensureDisconnected();
        }
Beispiel #13
0
        /// <summary>
        /// Get the response from the RIS server.
        /// </summary>
        /// <param name="validate">default value is TRUE. If FALSE validate silently doesn't throw exception.</param>
        /// <returns>Kount.Ris.Response populated object.</returns>
        public Kount.Ris.Response GetResponse(bool validate = true)
        {
            logger.Debug($"Kount.Ris.Request.GetResponse() - RIS endpoint URL: {this.url}");
            logger.Debug($"PTOK [{this.SafeGet("PTOK")}]");
            string ptok = this.Data.ContainsKey("PTOK") ? (string)this.Data["PTOK"] : "";

            if (ptok.Equals("") && "KHASH".Equals((string)this.Data["PENC"]))
            {
                this.Data["PENC"] = "";
            }

            IList errors = this.Validate(this.data);

            if (errors.Count > 0)
            {
                string errorMsg = "";
                foreach (ValidationError error in errors)
                {
                    errorMsg += error.ToString() + "\n";
                }

                logger.Error("The following data validation errors occurred: " + errorMsg);
                if (validate)
                {
                    throw new Kount.Ris.ValidationException(errorMsg);
                }
            }

            string post = "";

            foreach (DictionaryEntry param in this.Data)
            {
                string value = (param.Value != null) ? param.Value.ToString() : string.Empty;

                post = post + HttpUtility.UrlEncode(param.Key.ToString()) +
                       "=" + HttpUtility.UrlEncode(value) + "&";

                if (param.Key.ToString().Equals("PTOK"))
                {
                    value = "payment token hidden";
                }
                ;

                logger.Debug("[" + param.Key + "]=" + value);
            }

            post = post.TrimEnd('&');
            byte[] buffer = Encoding.ASCII.GetBytes(post);

            // Set up the request object
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(this.url);

            // Force using TLS 1.2 in case is not default - per request framework 4.5, 4, 3.5
            //System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768;
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

            webReq.Timeout       = this.connectTimeout;
            webReq.Method        = "POST";
            webReq.ContentType   = "application/x-www-form-urlencoded";
            webReq.ContentLength = buffer.Length;

            logger.Debug("Setting merchant ID header.");
            webReq.Headers[CUSTOM_HEADER_MERCHANT_ID] = this.GetParam("MERC");

            if (null != this.apiKey)
            {
                logger.Debug("Setting API key header.");
                webReq.Headers[CUSTOM_HEADER_API_KEY] = this.apiKey;
            }
            else
            {
                logger.Debug("API key header not found, setting certificate");
                //// Add the RIS signed authentication certificate to the payload
                //// See Kount Technical Specifications Guide for details on
                //// requesting and exporting
                //// from your browser
                X509Certificate2 cert = new X509Certificate2();
                cert.Import(
                    this.GetCertificateFile(),
                    this.GetPrivateKeyPassword(),
                    X509KeyStorageFlags.MachineKeySet);
                X509CertificateCollection certs = webReq.ClientCertificates;
                certs.Add(cert);
                webReq.ClientCertificates.Add(cert);
            }


            string risString = String.Empty;
            var    stopwatch = new Stopwatch();

            // start measure elapsed time between request and response
            stopwatch.Start();
            try
            {
                // Call the RIS server and pass in the payload
                using (Stream postData = webReq.GetRequestStream())
                {
                    postData.Write(buffer, 0, buffer.Length);
                }
            }
            catch (WebException ex)
            {
                string error = String.Empty;
                if (ex.Status == WebExceptionStatus.Timeout)
                {
                    error = $"TIMEOUT = {webReq.Timeout}.";
                }
                else
                {
                    if (ex.Response == null)
                    {
                        error = $"Unable to contact server {this.url}. WebEXCEPTION Status = {ex.Status}.";
                    }
                    else
                    {
                        error = this.GetWebError(ex.Response);
                    }
                }
                logger.Debug("ERROR - The following web error occurred: " + error);
                throw new Kount.Ris.RequestException(error);
            }

            // stop measure request time
            stopwatch.Stop();

            using (HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse())
            {
                // Read the RIS response string
                using (Stream answer = webResp.GetResponseStream())
                {
                    using (StreamReader risResponse = new StreamReader(answer))
                    {
                        risString = risResponse.ReadToEnd();
                    }
                }
            }

            var elapsed = stopwatch.ElapsedMilliseconds;

            if (logTimeElapsed)
            {
                var builder = new StringBuilder();
                builder.Append("MERC = ").Append(GetParam("MERC"));
                builder.Append(" SESS = ").Append(GetParam("SESS"));
                builder.Append(" SDK_ELAPSED = ").Append(elapsed).Append(" ms.");

                logger.Debug(builder.ToString());
            }

            logger.Debug("End GetResponse()");
            return(new Kount.Ris.Response(risString));
        }
        public void Add_Null()
        {
            X509CertificateCollection c = new X509CertificateCollection();

            c.Add(null);
        }
Beispiel #15
0
        /// <summary>
        /// Connects the user to the hub and creates Reader and Writer for communication.
        /// </summary>
        /// <param name="ip">Hub IP</param>
        /// <param name="port">Hub Port</param>
        ///
        private bool ConnectToHub(short tries)
        {
            this.Status = NodeStatus.Idle;
            Console.WriteLine("ConnectToHub() hascert=" + hasCertificate);
            Logger.Append(Severity.INFO, "Connecting to Hub (attempt " + tries + ")...");
            tries++;
            try{
                hubSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                hubSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, (int)1);
                hubSocket.Connect(ConfigManager.GetValue("Hub.IP"), int.Parse(ConfigManager.GetValue("Hub.Port")));
                underlyingHubStream = new NetworkStream(hubSocket);


                X509CertificateCollection certs = new X509CertificateCollection();
                //HubWrite(new NodeMessage{Context = MessageContext.Authentication, Action = "HELLO"});
                HubNoSslWrite("lilutelilutelilutelilutelilutelilutelilutelilutelilutelilutelilutelilutelilutelilutelilute"); // Why the hell do we need to send initial dummy data????
                if (!hasCertificate)                                                                                         //we should immediately receive a certificate from hub
                {
                    cert = new X509Certificate2(Convert.FromBase64String(Client.DefaultPubKey), "");
                    CertificateGeneratedEvent = new ManualResetEvent(false);
                }
                else
                {
                    cert = new X509Certificate2(ConfigManager.GetValue("Security.CertificateFile"), "" /*, X509KeyStorageFlags.Exportable*/);
                }
                certs.Add(cert);
                Console.WriteLine("creating ssl stream...");
                if (hubStream != null)
                {
                    hubStream.Close();
                }
                hubStream = new SslStream(underlyingHubStream, false, new RemoteCertificateValidationCallback(CheckHubCertificate), LocalSelectionCallback);
                hubStream.WriteTimeout = 30000;                 // Timeout after 30s : hub is probably disconnected.
                Console.WriteLine("creating ssl stream2...");

                //certs.Add(rootCert); // TODO : see if we really need to add root cert
                Console.WriteLine("creating ssl stream3...");
                hubStream.AuthenticateAsClient("hub" /*ConfigManager.GetValue("Hub.IP")*/, certs, SslProtocols.Default, false);
                Console.WriteLine("creating ssl stream4...");
                Logger.Append(Severity.TRIVIA, "SSL authentication done");
            }
            catch (SocketException e) {
                Logger.Append(Severity.ERROR, "Can't connect to hub (" + tries + " attempts)... will retry indefinitely every 30s (error : " + e.Message + ")");
                Thread.Sleep(30000);
                ConnectToHub(tries);
            }
            catch (ObjectDisposedException ode) {
                // if the user, for some reason, has been logged out and the user is logging in again
                // create a new socket aund call ConnectToHub again
                Console.WriteLine("WARN: User.ConnectToHub : re-connecting because of : " + ode.Message);
                hubSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ConnectToHub(tries);
            }
            catch (Exception ex) {           // probably SSL error
                Logger.Append(Severity.ERROR, ex.Message + " : " + ex.StackTrace);
                Logger.Append(Severity.ERROR, ex.InnerException.Message + " : " + ex.InnerException.StackTrace);
                return(false);
            }
            StartListening();
            return(true);
        }
Beispiel #16
0
		private X509CertificateCollection BuildCertificatesCollection (string storeName) 
		{
			X509CertificateCollection coll = new X509CertificateCollection ();
			string path = Path.Combine (_storePath, storeName);
			if (!CheckStore (path, false))
				return coll;	// empty collection

			string[] files = Directory.GetFiles (path, "*.cer");
			if ((files != null) && (files.Length > 0)) {
				foreach (string file in files) {
					try {
						X509Certificate cert = LoadCertificate (file);
						coll.Add (cert);
					}
					catch {
						// in case someone is dumb enough
						// (like me) to include a base64
						// encoded certs (or other junk 
						// into the store).
					}
				}
			}
			return coll;
		}
		static X509CertificateCollection LoadCertificates (string filename) 
		{
			X509Certificate x509 = null;
			X509CertificateCollection coll = new X509CertificateCollection ();
			switch (Path.GetExtension (filename).ToUpper ()) {
				case ".P7B":
				case ".SPC":
					SoftwarePublisherCertificate spc = SoftwarePublisherCertificate.CreateFromFile (filename);
					coll.AddRange (spc.Certificates);
					spc = null;
					break;
				case ".CER":
				case ".CRT":
					using (FileStream fs = File.OpenRead (filename)) {
						byte[] data = new byte [fs.Length];
						fs.Read (data, 0, data.Length);
						if (data [0] != 0x30) {
							// maybe it's ASCII PEM base64 encoded ?
							data = PEM ("CERTIFICATE", data);
						}
						if (data != null)
							x509 = new X509Certificate (data);
					}
					if (x509 != null)
						coll.Add (x509);
					break;
				case ".P12":
				case ".PFX":
					// TODO - support PKCS12 with passwords
					PKCS12 p12 = PKCS12.LoadFromFile (filename);
					coll.AddRange (p12.Certificates);
					p12 = null;
					break;
				default:
					Console.WriteLine ("Unknown file extension: {0}", 
						Path.GetExtension (filename));
					break;
			}
			return coll;
		}
Beispiel #18
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();

            certificates.Add(certificate);


            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                                       (sender, cert, chain, sslErrs) => { return(true); },
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return(certificate); });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);


            //Set up
            byte[]   buffer       = new byte[38];
            int      recd         = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                try
                {
                    //Get our seconds since 1970 ?
                    byte[] bSeconds     = new byte[4];
                    byte[] bDeviceToken = new byte[32];

                    Array.Copy(buffer, 0, bSeconds, 0, 4);

                    //Check endianness
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(bSeconds);
                    }

                    int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                    //Add seconds since 1970 to that date, in UTC and then get it locally
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds).ToLocalTime();

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!settings.FeedbackTimeIsUTC)
                    {
                        timestamp = timestamp.ToLocalTime();
                    }

                    //Now copy out the device token
                    Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                    var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                    //Make sure we have a good feedback tuple
                    if (deviceToken.Length == 64 &&
                        timestamp > minTimestamp)
                    {
                        //Raise event
                        RaiseFeedbackReceived(deviceToken, timestamp);
                    }
                }
                catch { }

                //Clear our array to reuse it
                Array.Clear(buffer, 0, buffer.Length);

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }
        }
Beispiel #19
0
		protected override void ProcessAsTls1()
		{
			this.certificates = new X509CertificateCollection();
			
			int readed	= 0;
			int length	= this.ReadInt24();

			while (readed < length)
			{
				// Read certificate length
				int certLength = ReadInt24();

				// Increment readed
				readed += 3;

				if (certLength > 0)
				{
					// Read certificate data
					byte[] buffer = this.ReadBytes(certLength);

					// Create a new X509 Certificate
					X509Certificate certificate = new X509Certificate(buffer);
					certificates.Add(certificate);

					readed += certLength;

					DebugHelper.WriteLine(
						String.Format("Server Certificate {0}", certificates.Count),
						buffer);
				}
			}

			this.validateCertificates(certificates);
		}
Beispiel #20
0
        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();

            certificates.Add(certificate);


            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                                       (sender, cert, chain, sslErrs) => { return(true); },
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return(certificate); });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Tls, false);


            //Set up
            byte[]   buffer             = new byte[1482];
            int      bufferIndex        = 0;
            int      bufferLevel        = 0;
            int      completePacketSize = 4 + 2 + 32;
            int      recd         = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                //Update how much data is in the buffer, and reset the position to the beginning
                bufferLevel += recd;
                bufferIndex  = 0;

                try
                {
                    //Process each complete notification "packet" available in the buffer
                    while (bufferLevel - bufferIndex >= completePacketSize)
                    {
                        //Get our seconds since 1970 ?
                        byte[] bSeconds     = new byte[4];
                        byte[] bDeviceToken = new byte[32];

                        Array.Copy(buffer, bufferIndex, bSeconds, 0, 4);

                        //Check endianness
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(bSeconds);
                        }

                        int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                        //Add seconds since 1970 to that date, in UTC
                        var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

                        //flag to allow feedback times in UTC or local, but default is local
                        if (!settings.FeedbackTimeIsUTC)
                        {
                            timestamp = timestamp.ToLocalTime();
                        }

                        //Now copy out the device token
                        Array.Copy(buffer, bufferIndex + 6, bDeviceToken, 0, 32);

                        var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                        //Make sure we have a good feedback tuple
                        if (deviceToken.Length == 64 &&
                            timestamp > minTimestamp)
                        {
                            //Raise event
                            try
                            {
                                RaiseFeedbackReceived(deviceToken, timestamp);
                            }
                            catch { }
                        }

                        //Keep track of where we are in the received data buffer
                        bufferIndex += completePacketSize;
                    }
                }
                catch { }

                //Figure out how much data we have left over in the buffer still
                bufferLevel -= bufferIndex;

                //Copy any leftover data in the buffer to the start of the buffer
                if (bufferLevel > 0)
                {
                    Array.Copy(buffer, bufferIndex, buffer, 0, bufferLevel);
                }

                //Read the next feedback
                recd = stream.Read(buffer, bufferLevel, buffer.Length - bufferLevel);
            }

            try
            {
                stream.Close();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown(SocketShutdown.Both);
                client.Client.Dispose();
            }
            catch { }

            try { client.Close(); }
            catch { }
        }
		internal bool ValidateClientCertificate (X509Certificate certificate, MonoSslPolicyErrors errors)
		{
			var certs = new X509CertificateCollection ();
			certs.Add (new X509Certificate2 (certificate.GetRawCertData ()));

			var result = ValidateChain (string.Empty, true, certificate, null, certs, (SslPolicyErrors)errors);
			if (result == null)
				return false;

			return result.Trusted && !result.UserDenied;
		}
Beispiel #22
0
        static int Process()
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
                if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
                {
                    Console.WriteLine("WARNING: Downloading the trusted certificate list couldn't be done securely (error: {0}), continuing anyway. If you're using mozroots to bootstrap Mono's trust store on a clean system this might be OK, otherwise it could indicate a network intrusion. Please ensure you're using a trusted network or move to cert-sync.", sslPolicyErrors);
                }

                // this is very bad, but on a clean system without an existing trust store we don't really have a better option
                return(true);
            };

            X509CertificateCollection roots = DecodeCollection();

            if (roots == null)
            {
                return(1);
            }
            else if (roots.Count == 0)
            {
                WriteLine("No certificates were found.");
                return(0);
            }

            if (pkcs7filename != null)
            {
                SoftwarePublisherCertificate pkcs7 = new SoftwarePublisherCertificate();
                pkcs7.Certificates.AddRange(roots);

                WriteLine("Saving root certificates into '{0}' file...", pkcs7filename);
                using (FileStream fs = File.OpenWrite(pkcs7filename)) {
                    byte[] data = pkcs7.GetBytes();
                    fs.Write(data, 0, data.Length);
                    fs.Close();
                }
            }

            if (import)
            {
                WriteLine("Importing certificates into {0} store...",
                          machine ? "machine" : "user");

                X509Stores stores = (machine ? X509StoreManager.LocalMachine : X509StoreManager.CurrentUser);
                X509CertificateCollection trusted = stores.TrustedRoot.Certificates;
                int additions = 0;
                foreach (X509Certificate root in roots)
                {
                    if (!trusted.Contains(root))
                    {
                        if (!confirmAddition || AskConfirmation("add", root))
                        {
                            stores.TrustedRoot.Import(root);
                            if (confirmAddition)
                            {
                                WriteLine("Certificate added.{0}", Environment.NewLine);
                            }
                            additions++;
                        }
                    }
                }
                if (additions > 0)
                {
                    WriteLine("{0} new root certificates were added to your trust store.", additions);
                }

                X509CertificateCollection removed = new X509CertificateCollection();
                foreach (X509Certificate trust in trusted)
                {
                    if (!roots.Contains(trust))
                    {
                        removed.Add(trust);
                    }
                }
                if (removed.Count > 0)
                {
                    if (confirmRemoval)
                    {
                        WriteLine("{0} previously trusted certificates were not part of the update.", removed.Count);
                    }
                    else
                    {
                        WriteLine("{0} previously trusted certificates were removed.", removed.Count);
                    }

                    foreach (X509Certificate old in removed)
                    {
                        if (!confirmRemoval || AskConfirmation("remove", old))
                        {
                            stores.TrustedRoot.Remove(old);
                            if (confirmRemoval)
                            {
                                WriteLine("Certificate removed.{0}", Environment.NewLine);
                            }
                        }
                    }
                }
                WriteLine("Import process completed.{0}", Environment.NewLine);
            }
            return(0);
        }
Beispiel #23
0
        public static void X509CertificateCollectionEnumeratorModification()
        {
            using (X509Certificate c1 = new X509Certificate())
            using (X509Certificate c2 = new X509Certificate())
            using (X509Certificate c3 = new X509Certificate())
            {
                X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 });
                X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator();

                cc.Add(c1);

                // Collection changed.
                Assert.Throws<InvalidOperationException>(() => e.MoveNext());
                Assert.Throws<InvalidOperationException>(() => e.Reset());
            }
        }
Beispiel #24
0
        public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback)
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
            var        server   = new TcpListener(endPoint);

            server.Start();

            using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
            {
                IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;

                Task             clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
                Task <TcpClient> serverAccept  = server.AcceptTcpClientAsync();

                Assert.True(
                    Task.WaitAll(
                        new Task[] { clientConnect, serverAccept },
                        TestConfiguration.PassingTestTimeoutMilliseconds),
                    "Client/Server TCP Connect timed out.");

                LocalCertificateSelectionCallback clientCertCallback = null;

                if (useClientSelectionCallback)
                {
                    clientCertCallback = ClientCertSelectionCallback;
                }

                using (TcpClient serverConnection = await serverAccept)
                    using (SslStream sslClientStream = new SslStream(
                               clientConnection.GetStream(),
                               false,
                               ClientSideRemoteServerCertificateValidation,
                               clientCertCallback))
                        using (SslStream sslServerStream = new SslStream(
                                   serverConnection.GetStream(),
                                   false,
                                   ServerSideRemoteClientCertificateValidation))

                        {
                            string serverName  = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                            var    clientCerts = new X509CertificateCollection();

                            if (!useClientSelectionCallback)
                            {
                                clientCerts.Add(_clientCertificate);
                            }

                            Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
                                serverName,
                                clientCerts,
                                SslProtocolSupport.DefaultSslProtocols,
                                false);

                            Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
                                _serverCertificate,
                                true,
                                SslProtocolSupport.DefaultSslProtocols,
                                false);

                            Assert.True(
                                Task.WaitAll(
                                    new Task[] { clientAuthentication, serverAuthentication },
                                    TestConfiguration.PassingTestTimeoutMilliseconds),
                                "Client/Server Authentication timed out.");

                            Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
                            Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");

                            Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject);
                            Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject);
                        }
            }
        }
Beispiel #25
0
        public static void X509CertificateCollectionAsIListBogusEntry()
        {
            using (X509Certificate2 c = new X509Certificate2())
            {
                IList il = new X509CertificateCollection();
                il.Add(c);

                string bogus = "Bogus";

                Assert.Throws<ArgumentException>(() => il[0] = bogus);
                Assert.Throws<ArgumentException>(() => il.Add(bogus));
                Assert.Throws<ArgumentException>(() => il.Remove(bogus));
                Assert.Throws<ArgumentException>(() => il.Insert(0, bogus));
            }
        }
Beispiel #26
0
        private static int Process()
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
                if (sslPolicyErrors != SslPolicyErrors.None)
                {
                    //Console.WriteLine("WARNING: Downloading the trusted certificate list couldn't be done securely (error: {0}), continuing anyway. If you're using mozroots to bootstrap Mono's trust store on a clean system this might be OK, otherwise it could indicate a network intrusion. Please ensure you're using a trusted network or move to cert-sync.", sslPolicyErrors);
                }

                // this is very bad, but on a clean system without an existing trust store we don't really have a better option
                return(true);
            };

            var roots = DecodeCollection();

            if (roots == null)
            {
                return(1);
            }
            else if (roots.Count == 0)
            {
                return(0);
            }

            var stores    = X509StoreManager.CurrentUser;
            var trusted   = stores.TrustedRoot.Certificates;
            var additions = 0;

            foreach (var root in roots)
            {
                if (!trusted.Contains(root))
                {
                    stores.TrustedRoot.Import(root);
                    additions++;
                }
            }

            if (additions > 0)
            {
                //WriteLine("{0} new root certificates were added to your trust store.", additions);
            }

            var removed = new X509CertificateCollection();

            foreach (var trust in trusted)
            {
                if (!roots.Contains(trust))
                {
                    removed.Add(trust);
                }
            }

            if (removed.Count > 0)
            {
                //WriteLine("{0} previously trusted certificates were removed.", removed.Count);

                foreach (var old in removed)
                {
                    stores.TrustedRoot.Remove(old);
                }
            }

            //WriteLine("Import process completed.{0}", Environment.NewLine);
            return(0);
        }
        public static bool MySSLHandler(Syscert.X509Certificate certificate,
                                        int[] certificateErrors)
        {
            X509Store  store  = null;
            X509Stores stores = X509StoreManager.CurrentUser;
            String     input;

            store = stores.TrustedRoot;


            //Import the details of the certificate from the server.

            X509Certificate           x509 = null;
            X509CertificateCollection coll = new X509CertificateCollection();

            byte[] data = certificate.GetRawCertData();
            if (data != null)
            {
                x509 = new X509Certificate(data);
            }

            //List the details of the Server

            //check for ceritficate in store
            X509CertificateCollection check = store.Certificates;

            if (!check.Contains(x509))
            {
                if (bindCount == 1)
                {
                    Console.WriteLine(" \n\nCERTIFICATE DETAILS: \n");
                    Console.WriteLine(" {0}X.509 v{1} Certificate", (x509.IsSelfSigned ? "Self-signed " : String.Empty), x509.Version);
                    Console.WriteLine("  Serial Number: {0}", CryptoConvert.ToHex(x509.SerialNumber));
                    Console.WriteLine("  Issuer Name:   {0}", x509.IssuerName);
                    Console.WriteLine("  Subject Name:  {0}", x509.SubjectName);
                    Console.WriteLine("  Valid From:    {0}", x509.ValidFrom);
                    Console.WriteLine("  Valid Until:   {0}", x509.ValidUntil);
                    Console.WriteLine("  Unique Hash:   {0}", CryptoConvert.ToHex(x509.Hash));
                    Console.WriteLine();
                }

                //Get the response from the Client
                do
                {
                    Console.WriteLine("\nDo you want to proceed with the connection (y/n)?");
                    input = Console.ReadLine();
                    if (input == "y" || input == "Y")
                    {
                        bHowToProceed = true;
                    }
                    if (input == "n" || input == "N")
                    {
                        bHowToProceed = false;
                    }
                }while(input != "y" && input != "Y" && input != "n" && input != "N");
            }
            else
            {
                if (bHowToProceed == true)
                {
                    //Add the certificate to the store.

                    if (x509 != null)
                    {
                        coll.Add(x509);
                    }
                    store.Import(x509);
                    if (bindCount == 1)
                    {
                        removeFlag = true;
                    }
                }
            }
            if (bHowToProceed == false)
            {
                //Remove the certificate added from the store.

                if (removeFlag == true && bindCount > 1)
                {
                    foreach (X509Certificate xt509 in store.Certificates)
                    {
                        if (CryptoConvert.ToHex(xt509.Hash) == CryptoConvert.ToHex(x509.Hash))
                        {
                            store.Remove(x509);
                        }
                    }
                }
                Console.WriteLine("SSL Bind Failed.");
            }
            return(bHowToProceed);
        }
Beispiel #28
0
        static int Process()
        {
            X509CertificateCollection roots = DecodeCollection();

            if (roots == null)
            {
                return(1);
            }
            else if (roots.Count == 0)
            {
                WriteLine("No certificates were found.");
                return(0);
            }

            if (pkcs7filename != null)
            {
                SoftwarePublisherCertificate pkcs7 = new SoftwarePublisherCertificate();
                pkcs7.Certificates.AddRange(roots);

                WriteLine("Saving root certificates into '{0}' file...", pkcs7filename);
                using (FileStream fs = File.OpenWrite(pkcs7filename)) {
                    byte[] data = pkcs7.GetBytes();
                    fs.Write(data, 0, data.Length);
                    fs.Close();
                }
            }

            if (import)
            {
                WriteLine("Importing certificates into {0} store...",
                          machine ? "machine" : "user");

                X509Stores stores = (machine ? X509StoreManager.LocalMachine : X509StoreManager.CurrentUser);
                X509CertificateCollection trusted = stores.TrustedRoot.Certificates;
                int additions = 0;
                foreach (X509Certificate root in roots)
                {
                    if (!trusted.Contains(root))
                    {
                        if (!confirmAddition || AskConfirmation("add", root))
                        {
                            stores.TrustedRoot.Import(root);
                            if (confirmAddition)
                            {
                                WriteLine("Certificate added.{0}", Environment.NewLine);
                            }
                            additions++;
                        }
                    }
                }
                if (additions > 0)
                {
                    WriteLine("{0} new root certificates were added to your trust store.", additions);
                }

                X509CertificateCollection removed = new X509CertificateCollection();
                foreach (X509Certificate trust in trusted)
                {
                    if (!roots.Contains(trust))
                    {
                        removed.Add(trust);
                    }
                }
                if (removed.Count > 0)
                {
                    if (confirmRemoval)
                    {
                        WriteLine("{0} previously trusted certificates were not part of the update.", removed.Count);
                    }
                    else
                    {
                        WriteLine("{0} previously trusted certificates were removed.", removed.Count);
                    }

                    foreach (X509Certificate old in removed)
                    {
                        if (!confirmRemoval || AskConfirmation("remove", old))
                        {
                            stores.TrustedRoot.Remove(old);
                            if (confirmRemoval)
                            {
                                WriteLine("Certificate removed.{0}", Environment.NewLine);
                            }
                        }
                    }
                }
                WriteLine("Import process completed.{0}", Environment.NewLine);
            }
            return(0);
        }
        public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback)
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 0);
            var        server   = new TcpListener(endPoint);

            server.Start();

            _clientCertificateRemovedByFilter = false;

            if (PlatformDetection.IsWindows7 &&
                !useClientSelectionCallback &&
                !Capability.IsTrustedRootCertificateInstalled())
            {
                // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2
                // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed:
                // The behavior to send the Trusted Issuers List by default is off.
                //
                // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built
                // by the server using certificates from the Trusted Root Authorities certificate store.
                // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates.
                _clientCertificateRemovedByFilter = true;
            }

            using (var clientConnection = new TcpClient())
            {
                IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;

                Task             clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
                Task <TcpClient> serverAccept  = server.AcceptTcpClientAsync();

                await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientConnect, serverAccept);

                LocalCertificateSelectionCallback clientCertCallback = null;

                if (useClientSelectionCallback)
                {
                    clientCertCallback = ClientCertSelectionCallback;
                }

                using (TcpClient serverConnection = await serverAccept)
                    using (SslStream sslClientStream = new SslStream(
                               clientConnection.GetStream(),
                               false,
                               ClientSideRemoteServerCertificateValidation,
                               clientCertCallback))
                        using (SslStream sslServerStream = new SslStream(
                                   serverConnection.GetStream(),
                                   false,
                                   ServerSideRemoteClientCertificateValidation))
                        {
                            string serverName  = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
                            var    clientCerts = new X509CertificateCollection();

                            if (!useClientSelectionCallback)
                            {
                                clientCerts.Add(_clientCertificate);
                            }

                            Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
                                serverName,
                                clientCerts,
                                SslProtocolSupport.DefaultSslProtocols,
                                false);

                            Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
                                _serverCertificate,
                                true,
                                SslProtocolSupport.DefaultSslProtocols,
                                false);

                            await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientAuthentication, serverAuthentication);

                            using (sslServerStream.RemoteCertificate)
                            {
                                if (!_clientCertificateRemovedByFilter)
                                {
                                    Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
                                    Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");

                                    Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject);
                                }
                                else
                                {
                                    Assert.False(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
                                    Assert.False(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");

                                    Assert.Null(sslServerStream.RemoteCertificate);
                                }

                                Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject);
                            }
                        }
            }
        }
Beispiel #30
0
        public void Check()
        {
            var encoding = Encoding.ASCII;

            var certificate = Configuration.Certificate;

            var certificates = new X509CertificateCollection();

            certificates.Add(certificate);

            var client = new TcpClient(Configuration.FeedbackHost, Configuration.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                                       (sender, cert, chain, sslErrs) => { return(true); },
                                       (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return(certificate); });

            var tls = System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12;

            stream.AuthenticateAsClient(Configuration.FeedbackHost, certificates, tls, false);

            //Set up
            byte[] buffer = new byte[4096];
            int    recd   = 0;
            var    data   = new List <byte>();

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0)
            {
                // Add the received data to a list buffer to work with (easier to manipulate)
                for (int i = 0; i < recd; i++)
                {
                    data.Add(buffer[i]);
                }

                //Process each complete notification "packet" available in the buffer
                while (data.Count >= (4 + 2 + 32)) // Minimum size for a valid packet
                {
                    var secondsBuffer     = data.GetRange(0, 4).ToArray();
                    var tokenLengthBuffer = data.GetRange(4, 2).ToArray();

                    // Get our seconds since epoch
                    // Check endianness and reverse if needed
                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(secondsBuffer);
                    }
                    var seconds = BitConverter.ToInt32(secondsBuffer, 0);

                    //Add seconds since 1970 to that date, in UTC
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds);

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!Configuration.FeedbackTimeIsUTC)
                    {
                        timestamp = timestamp.ToLocalTime();
                    }

                    if (BitConverter.IsLittleEndian)
                    {
                        Array.Reverse(tokenLengthBuffer);
                    }
                    var tokenLength = BitConverter.ToInt16(tokenLengthBuffer, 0);

                    if (data.Count >= 4 + 2 + tokenLength)
                    {
                        var tokenBuffer = data.GetRange(6, tokenLength).ToArray();
                        // Strings shouldn't care about endian-ness... this shouldn't be reversed
                        //if (BitConverter.IsLittleEndian)
                        //    Array.Reverse (tokenBuffer);
                        var token = BitConverter.ToString(tokenBuffer).Replace("-", "").ToLower().Trim();

                        // Remove what we parsed from the buffer
                        data.RemoveRange(0, 4 + 2 + tokenLength);

                        // Raise the event to the consumer
                        var evt = FeedbackReceived;
                        if (evt != null)
                        {
                            evt(token, timestamp);
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }

            try
            {
                stream.Close();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown(SocketShutdown.Both);
                client.Client.Dispose();
            }
            catch { }

            try { client.Close(); } catch { }
        }
Beispiel #31
0
        //</snippet5>
        //<snippet7>
        public static int Main(string[] args)
        {
            string serverName = null;

            if (args == null || args.Length < 2)
            {
                Console.WriteLine(
                    "To start the client specify the host name and" +
                    " one or more client certificate file names.");
                return(1);
            }
            //<snippet6>
            // Server name must match the host name and the name on the host's certificate.
            serverName = args[0];
            // Create a TCP/IP client socket.
            TcpClient client = new TcpClient(serverName, 80);

            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                new LocalCertificateSelectionCallback(SelectLocalCertificate)
                );
            //</snippet6>
            // Create the certificate collection to hold the client's certificate.
            X509CertificateCollection clientCertificates = new X509CertificateCollection();

            for (int i = 1; i < args.Length; i++)
            {
                X509Certificate certificate = X509Certificate.CreateFromCertFile(args[i]);
                clientCertificates.Add(certificate);
            }
            // Begin authentication.
            // The server name must match the name on the server certificate.

            sslStream.BeginAuthenticateAsClient(
                serverName,
                clientCertificates,
                SslProtocols.Ssl3,
                true,
                new AsyncCallback(AuthenticateCallback),
                sslStream);
            // User can press a key to exit application, or let the
            // asynchronous calls continue until they complete.
            Console.WriteLine("To quit, press the enter key.");
            do
            {
                // Real world applications would do work here
                // while waiting for the asynchronous calls to complete.
                System.Threading.Thread.Sleep(100);
            } while (complete != true && Console.KeyAvailable == false);

            if (Console.KeyAvailable)
            {
                Console.ReadLine();
                Console.WriteLine("Quitting.");
                client.Close();
                sslStream.Close();
                return(1);
            }
            if (e != null)
            {
                Console.WriteLine("An exception was thrown: {0}", e.ToString());
            }
            sslStream.Close();
            client.Close();
            Console.WriteLine("Good bye.");
            return(0);
        }
Beispiel #32
0
        void EvaluateTrust()
        {
            InitializeSession ();

            /*
             * We're using .NET's SslStream semantics here.
             *
             * A server must always provide a valid certificate.
             *
             * However, in server mode, "ask for client certificate" means that
             * we ask the client to provide a certificate, then invoke the client
             * certificate validator - passing 'null' if the client didn't provide
             * any.
             *
             */

            var trust = GetPeerTrust (!IsServer);
            X509CertificateCollection certificates;

            if (trust == null || trust.Count == 0) {
                remoteCertificate = null;
                if (!serverMode)
                    throw new TlsException (AlertDescription.CertificateUnknown);
                certificates = null;
            } else {
                if (trust.Count > 1)
                    Debug ("WARNING: Got multiple certificates in SecTrust!");

                certificates = new X509CertificateCollection ();
                for (int i = 0; i < trust.Count; i++)
                    certificates.Add (trust [i].ToX509Certificate ());

                remoteCertificate = certificates [0];
                Debug ("Got peer trust: {0}", remoteCertificate);
            }

            bool ok;
            try {
                ok = MobileCertificateHelper.Validate (targetHost, IsServer, certificateValidator, certificates);
            } catch (Exception ex) {
                Debug ("Certificate validation failed: {0}", ex);
                throw new TlsException (AlertDescription.CertificateUnknown, "Certificate validation threw exception.");
            }

            if (!ok)
                throw new TlsException (AlertDescription.CertificateUnknown);
        }
Beispiel #33
0
        public async Task ConnectAsync(CancellationToken cancellationToken)
        {
            var uri = _webSocketOptions.Uri;

            if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
            {
                if (_webSocketOptions.TlsOptions?.UseTls == false)
                {
                    uri = "ws://" + uri;
                }
                else
                {
                    uri = "wss://" + uri;
                }
            }

            var sslProtocols = _webSocketOptions?.TlsOptions?.SslProtocol ?? SslProtocols.None;
            var subProtocol  = _webSocketOptions.SubProtocols.FirstOrDefault() ?? string.Empty;

            var cookies = new List <KeyValuePair <string, string> >();

            if (_webSocketOptions.CookieContainer != null)
            {
                throw new NotSupportedException("Cookies are not supported.");
            }

            List <KeyValuePair <string, string> > customHeaders = null;

            if (_webSocketOptions.RequestHeaders != null)
            {
                customHeaders = _webSocketOptions.RequestHeaders.Select(i => new KeyValuePair <string, string>(i.Key, i.Value)).ToList();
            }

            EndPoint proxy = null;

            if (_webSocketOptions.ProxyOptions != null)
            {
                throw new NotSupportedException("Proxies are not supported.");
            }

            // The user agent can be empty always because it is just added to the custom headers as "User-Agent".
            var userAgent = string.Empty;

            var origin            = string.Empty;
            var webSocketVersion  = WebSocketVersion.None;
            var receiveBufferSize = 0;

            var certificates = new X509CertificateCollection();

            if (_webSocketOptions?.TlsOptions?.Certificates != null)
            {
                foreach (var certificate in _webSocketOptions.TlsOptions.Certificates)
                {
#if WINDOWS_UWP
                    certificates.Add(new X509Certificate(certificate));
#else
                    certificates.Add(certificate);
#endif
                }
            }

            _webSocket = new WebSocket(uri, subProtocol, cookies, customHeaders, userAgent, origin, webSocketVersion, proxy, sslProtocols, receiveBufferSize)
            {
                NoDelay  = true,
                Security =
                {
                    AllowUnstrustedCertificate  = _webSocketOptions?.TlsOptions?.AllowUntrustedCertificates == true,
                    AllowCertificateChainErrors = _webSocketOptions?.TlsOptions?.IgnoreCertificateChainErrors == true,
                    Certificates                = certificates
                }
            };

            await ConnectInternalAsync(cancellationToken).ConfigureAwait(false);

            IsSecureConnection = uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase);
        }
Beispiel #34
0
        public int Connect(int socket, IntPtr szTargetHost, int sslContextHandle)
        {
            SslStreamData ssd;

            if (GetSslData(socket, out ssd))
            {
                switch (ssd.m_state)
                {
                case SslStreamData.SslAsyncState.Processing:
                    return((int)SocketError.WouldBlock);

                case SslStreamData.SslAsyncState.Finished:
                    ssd.m_state = SslStreamData.SslAsyncState.InUse;
                    _socketsDriver.SetSslSocket(socket);
                    return((int)SocketError.Success);

                case SslStreamData.SslAsyncState.Failed:
                    ssd.m_state = SslStreamData.SslAsyncState.Init;
                    Console.Error.WriteLine("Connect Failed...");
                    return((int)SocketError.SocketError);

                case SslStreamData.SslAsyncState.InUse:
                    Console.Error.WriteLine("Connect InUse...");
                    return((int)SocketError.Success);
                }
            }
            else
            {
                ssd = new SslStreamData();

                lock (_sslStreams)
                {
                    _sslStreams[socket] = ssd;
                }
            }

            ssd.m_state = SslStreamData.SslAsyncState.Processing;

            try
            {
                Socket sock = null;

                if (!_socketsDriver.GetSocket(socket, out sock))
                {
                    return((int)SocketError.SocketError);
                }

                NetworkStream ns     = new NetworkStream(sock);
                SslStream     stream = new SslStream(ns, true);

                ssd.m_stream = stream;

                SslData sd = _sslDataCollection[sslContextHandle];

                string targHost = Marshal.PtrToStringAnsi(szTargetHost);

                X509CertificateCollection certs = new X509CertificateCollection();

                if (sd.m_cert != null)
                {
                    certs.Add(sd.m_cert);
                }

                IAsyncResult iar = stream.BeginAuthenticateAsClient(targHost, certs, sd.m_sslVersion, false, new AsyncCallback(EndSslConnect), socket);
            }
            catch (Exception ae)
            {
                ssd.m_state = SslStreamData.SslAsyncState.Init;
                Console.Error.WriteLine("BeginAuthenticateAsClient " + ae.Message);
                return((int)SocketError.SocketError);
            }

            return((int)SocketError.WouldBlock);
        }
Beispiel #35
0
        public async Task HttpsRequestAsync(Func <string, Task <string> > httpConversation = null)
        {
            _log.WriteLine("[Client] Disabling SslPolicyErrors: {0}", _options.IgnoreSslPolicyErrors.ToString());

            if (httpConversation == null)
            {
                httpConversation = DefaultHttpConversation;
            }

            using (var certValidationPolicy = new SslStreamCertificatePolicy(_options.IgnoreSslPolicyErrors))
                using (var tcp = new TcpClient())
                {
                    await ConnectToHostAsync(tcp);

                    using (Stream = new SslStream(tcp.GetStream(), false, certValidationPolicy.SslStreamCallback))
                    {
                        X509CertificateCollection clientCerts = null;

                        if (_options.ClientCertificate != null)
                        {
                            clientCerts = new X509CertificateCollection();
                            clientCerts.Add(_options.ClientCertificate);
                        }

                        _log.WriteLine(
                            "[Client] Connected. Authenticating: server={0}; clientCert={1}",
                            _options.ServerName,
                            _options.ClientCertificate != null ? _options.ClientCertificate.Subject : "<null>");

                        try
                        {
                            await Stream.AuthenticateAsClientAsync(
                                _options.ServerName,
                                clientCerts,
                                _options.AllowedProtocols,
                                checkCertificateRevocation : false).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _log.WriteLine("[Client] Exception : {0}", ex);
                            throw ex;
                        }

                        _log.WriteLine("[Client] Authenticated protocol {0}", Stream.SslProtocol);

                        int    bytesRead      = 0;
                        string responseString = null;

                        while (true)
                        {
                            string requestString = await httpConversation(responseString).ConfigureAwait(false);

                            if (requestString == null)
                            {
                                return;
                            }

                            if (requestString.Length > 0)
                            {
                                byte[] requestBuffer = Encoding.UTF8.GetBytes(requestString);

                                _log.WriteLine("[Client] Sending request ({0} Bytes)", requestBuffer.Length);
                                await Stream.WriteAsync(requestBuffer, 0, requestBuffer.Length).ConfigureAwait(false);
                            }

                            _log.WriteLine("[Client] Waiting for reply...");

                            byte[] responseBuffer = new byte[2048];
                            bytesRead = await Stream.ReadAsync(responseBuffer, 0, responseBuffer.Length).ConfigureAwait(false);

                            responseString = Encoding.UTF8.GetString(responseBuffer, 0, bytesRead);
                            _log.WriteLine("[Client] {0} Bytes, Response: <{1}>", bytesRead, responseString);
                        }
                    }
                }
        }
 /// <summary>
 /// Adds a client side certificate. The certificate is used for client side authentication
 /// </summary>
 /// <param name="pathToCertificate">Path to the local .pfx file</param>
 /// <param name="password">Password of the certificate</param>
 public void AddCertificate(string pathToCertificate, string password)
 {
     cCollection.Add(new X509Certificate(pathToCertificate, password));
 }
Beispiel #37
0
        /*
        public string iOSAPNS(String DeviceTokenlistString, String content)
        {

            APNSSender test = new APNSSender();

            return test.SendAPNS(DeviceTokenlistString, content);
        }
         */


        /// <summary>  
        ///  傳入 DeviceToken  與 要傳的訊息
        /// </summary>  
        /// 手機上方 最多五則
        /// 警報日期:2015/03/04 11:55:00 \n類型/嚴重度:超速 / [嚴重]\n名稱:連續超速70km  3分鐘\n車號/駕駛人:kw-car03 / 易大師
        /// APNS 限制 payload 256bytes 超過就不發了 不过由于aps,alert等会占用部分长度,所以一般剩余140-200之间。
        /// 實測560個字都傳的出去 只是手機顯示最多4行而已
        /// <param name="inDeviceToken ID"> 手機端 Registration ID</param>  
        /// <param name="inMessage">訊息內容</param>  
        public String SendAPNS(String inDeviceToken, String inMessage)
        {
            //http://blog.sina.com.cn/s/blog_6f9a9718010128hi.html
            //太連續用單一個發送 會被蘋果認為是 dos 攻擊 而中斷連線   用單一個多次發送 遇到錯誤的token會中斷發送 接下來的都會無法發送
            System.Threading.Thread.Sleep(50);

        //    str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}";
            // badge 設為 0 就不會出現數字
            mAPNSMessage = "{\"aps\":{\"alert\":\"" + inMessage + "\",\"badge\":0,\"sound\":\"default\"}}";
          
            int port = 2195;
       //     string certificatepath = ConfigurationManager.AppSettings["p12FilePath"];
       //     string certificatepath = "D:\\VisualStudioProject\\Fleet\\new_aps_developer.p12";
            //string certificatepath = "D:\\VisualStudioProject\\Fleet\\distribution_aps_developer.p12";
        //    string certificatepath = "D:\\VisualStudioProject\\Fleet\\fleetivity_aps_developer.p12";
         //   string certificatepath = "C:\\inetpub\\DotNetNuke\\fleetivity_aps_developer.p12";

            string certificatepath = HttpContext.Current.Server.MapPath("/") + "certificate\\fleetivity_aps_developer.p12";

            

            string password = "******";

            // Apple development server address
            string hostIP = "gateway.sandbox.push.apple.com";//

           

            string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certificatepath);
            certificate = new X509Certificate2(System.IO.File.ReadAllBytes(p12Filename), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            if (certificate.ToString().Contains("Production"))
            {
                hostIP = "gateway.push.apple.com";
            }
            else
            {
                hostIP = "gateway.sandbox.push.apple.com";
            }

            TcpClient apnsClient = new TcpClient();
            apnsClient.Connect(hostIP, port);
            SslStream apnsStream = new SslStream(apnsClient.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), new LocalCertificateSelectionCallback(selectLocalCertificate));
            try
            {
                apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false);
            }
            catch (System.Security.Authentication.AuthenticationException ex)
            {
                Console.WriteLine("error:" + ex.Message);
            }

            if (!apnsStream.IsMutuallyAuthenticated)
            {
                Console.WriteLine("error:" + "Ssl Stream Failed to Authenticate");
            }

            if (!apnsStream.CanWrite)
            {
                Console.WriteLine("error:" + "Ssl Stream is not Writable");
            }
            Byte[] message = ToBytes(inDeviceToken);
            apnsStream.Write(message);
            return System.Text.Encoding.UTF8.GetString(message);
        }
Beispiel #38
0
        public static void Main(string[] args)
        {
            Console.WriteLine("BrokerDB authenticated Consumer test");

            if (args.Length == 0)
            {
                System.Console.WriteLine(CommandLineArguments.Usage());
                return;
            }

            CommandLineArguments cliArgs = new CommandLineArguments();
            Parser parser = new Parser(System.Environment.CommandLine, cliArgs);

            parser.Parse();

            BasicConfigurator.Configure();

            X509CertificateCollection certCollection = null;

            if (cliArgs.CertificatePath != null)
            {
                X509Certificate cert = X509Certificate.CreateFromCertFile(cliArgs.CertificatePath);

                certCollection = new X509CertificateCollection();
                certCollection.Add(cert);
            }

            List <HostInfo> hosts = new List <HostInfo>();

            hosts.Add(new HostInfo(cliArgs.Hostname, cliArgs.SslPortNumber));


            SslBrokerClient brokerClient = new SslBrokerClient(hosts, certCollection);

            brokerClient.OnFault += (f) =>
            {
                Console.WriteLine("Error");
                Console.WriteLine(String.Format("Code: {0}, Message: {1}, Detail: {2}", f.Code, f.Message, f.Detail));
            };

            ICredentialsProvider provider = new BrokerDbProvider("luis", "luis");

            Console.WriteLine("Authenticating");
            if (!brokerClient.Authenticate(provider))
            {
                Console.WriteLine("Authentication failed");
                return;
            }

            Subscription subscription = new Subscription(cliArgs.DestinationName, cliArgs.DestinationType);

            subscription.OnMessage += delegate(NetNotification notification)
            {
                System.Console.WriteLine("Message received: {0}",
                                         System.Text.Encoding.UTF8.GetString(notification.Message.Payload));
                if (notification.DestinationType != NetAction.DestinationType.TOPIC)
                {
                    brokerClient.Acknowledge(notification.Subscription, notification.Message.MessageId);
                }
            };

            brokerClient.Subscribe(subscription);

            Console.WriteLine("Write X to unsbscribe and exit");
            while (!System.Console.Read().Equals('X'))
            {
                ;
            }
            Console.WriteLine();
            Console.WriteLine("Unsubscribe...");


            // Note Subscription instance could other than the one used for subscription as long as it was equivelent (same destination type and subscription pattern). Since the application is ending and therefor the socket will be closed agent's will discard the previous subscription.
            brokerClient.Unsubscribe(subscription);

            Console.WriteLine("Good bye");
        }
Beispiel #39
0
        public static void X509CertificateCollectionAsIList()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            {
                X509CertificateCollection cc = new X509CertificateCollection();
                cc.Add(c1);
                cc.Add(c2);

                IList il = cc;
                Assert.Throws<ArgumentNullException>(() => il[0] = null);

                il[0] = "Bogus";
                Assert.Equal("Bogus", il[0]);

                object ignored;
                Assert.Throws<InvalidCastException>(() => ignored = cc[0]);
            }
        }
Beispiel #40
0
 static void ProvideClientCertificatesCallback(X509CertificateCollection clientCerts)
 {
     clientCerts.Add(new X509Certificate2("node.pfx"));
 }
            public void ConnectTLS()
            {   //TextRead();
                ClearRawTextData();
                lock (Client)
                {
                    byte[] nullbuff;
                    if (Client.Available > 0)
                    {
                        nullbuff = new byte[Client.Available];
                        int BytesRead = Client.GetStream().Read(nullbuff, 0, nullbuff.Length);
                        TotalDataReceivedForTlsConnection.Add(BytesRead);
                    }

                    RemoteCertificateValidationCallback CertValidationCallback = null;
                    if (AllowSelfSignedServerCertificate)
                    {
                        CertValidationCallback = new RemoteCertificateValidationCallback(ServerValidationCallbackNoVerifcation);
                    }
                    else
                    {
                        CertValidationCallback = new RemoteCertificateValidationCallback(ServerValidationCallback);
                    }

                    LocalCertificateSelectionCallback MycertCallback =
                        new LocalCertificateSelectionCallback(LocalCertificateSelectionCallback);


                    try
                    {
                        Console.WriteLine("Connecting with TLS");
                        if (Certificate != null)
                        {
                            TLSStream = new SslStream(ActiveStream, true, CertValidationCallback, MycertCallback);
                            TLSStream.WriteTimeout = SendTimeout;

                            X509CertificateCollection Certificates = new X509CertificateCollection();
                            Certificates.Add(Certificate);

                            TLSStream.AuthenticateAsClient(Hostname,
                                                           Certificates,
                                                           SslProtocols.Tls,
                                                           false);
                        }
                        else
                        {
                            TLSStream = new SslStream(ActiveStream, true, CertValidationCallback);
                            TLSStream.WriteTimeout = SendTimeout;

                            TLSStream.AuthenticateAsClient(Hostname);
                        }

                        //TLSStream.AuthenticateAsClient(Hostname);
                        ActiveStream = TLSStream;
                        if (Client.Available > 0)
                        {
                            nullbuff = new byte[Client.Available];
                            int BytesRead = Client.GetStream().Read(nullbuff, 0, nullbuff.Length);
                            TotalDataReceivedForTlsConnection.Add(BytesRead);
                        }
                        IsConnectedViaTLS = true;
                        Console.WriteLine("Connected with TLS");
                    }
                    catch (System.Exception ex)
                    {
                        Log(0, "TLS Error(s): {0}", ex.ToString());
                        throw new Exception("Connection failed due to TLS errors: " + ex.ToString());
                    }
                }
            }
Beispiel #42
0
        //
        // Acquire Server Side Certificate information and set it on the class.
        //
        private bool AcquireServerCredentials(ref byte[] thumbPrint)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials");

            X509Certificate localCertificate = null;
            bool            cachedCred       = false;

            if (_certSelectionDelegate != null)
            {
                X509CertificateCollection tempCollection = new X509CertificateCollection();
                tempCollection.Add(_serverCertificate);
                localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty <string>());
                GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert");
            }
            else
            {
                localCertificate = _serverCertificate;
            }

            if (localCertificate == null)
            {
                throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
            }

            // SECURITY: Accessing X509 cert Credential is disabled for semitrust.
            // We no longer need to demand for unmanaged code permissions.
            // EnsurePrivateKey should do the right demand for us.
            X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);

            if (selectedCert == null)
            {
                throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
            }

            GlobalLog.Assert(localCertificate.Equals(selectedCert), "AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");

            //
            // Note selectedCert is a safe ref possibly cloned from the user passed Cert object
            //
            byte[] guessedThumbPrint = selectedCert.GetCertHash();
            try
            {
                SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);

                if (cachedCredentialHandle != null)
                {
                    _credentialsHandle = cachedCredentialHandle;
                    _serverCertificate = localCertificate;
                    cachedCred         = true;
                }
                else
                {
                    _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);
                    thumbPrint         = guessedThumbPrint;
                    _serverCertificate = localCertificate;
                }
            }
            finally
            {
                // An extra cert could have been created, dispose it now.
                if ((object)localCertificate != (object)selectedCert)
                {
                    selectedCert.Dispose();
                }
            }

            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle));
            return(cachedCred);
        }
Beispiel #43
0
		protected virtual X509CertificateCollection GetCertificates ()
		{
			var certificates = new X509CertificateCollection ();

			var certificate = Config.Certificate;
			if (certificate == null)
				return certificates;

			var verifyVertificate = true;
			#if INSTRUMENTATION
			if (Context.HasInstrument (HandshakeInstrumentType.OverrideClientCertificateSelection))
				verifyVertificate = false;
			#endif

			var exchangeAlgorithm = PendingCrypto.Cipher.ExchangeAlgorithmType;
			if (verifyVertificate && !CertificateManager.VerifyClientCertificate (Context, certificate, exchangeAlgorithm))
				throw new TlsException (AlertDescription.UnsupportedCertificate);

			certificates.Add (certificate);
			return certificates;
		}
Beispiel #44
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TcpClient client = new TcpClient("127.0.0.1", 6000);
                Console.WriteLine("Client connected.");
                _sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );


                X509CertificateCollection certs = new X509CertificateCollection();
                X509Certificate           cert  = X509Certificate.CreateFromCertFile(System.Environment.CurrentDirectory + @"\" + "client.cer");
                certs.Add(cert);
                //验证证书
                try
                {
/*
 * 注意事项
 *
 * 1.服务端验证方法AuthenticateAsServer的参数clientCertificateRequired如果为true,那在客户端也要安装server.pfx.
 *
 * 2.客户端验证方法AuthenticateAsClient的参数targetHost对应证书中Common Name,也就是受颁发者.
 */
                    _sslStream.AuthenticateAsClient("test", certs, SslProtocols.Tls, false);
                }
                catch (AuthenticationException)
                {
                    client.Close();

                    //Console.WriteLine("Exception: {0}", e.Message);
                    //if (e.InnerException != null)
                    //{
                    //    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                    //}
                    //Console.WriteLine("Authentication failed - closing the connection.");
                    //client.Close();
                    //Console.ReadLine();
                    return;
                }

                //开始读取消息
                Task.Factory.StartNew(() =>
                {
                    ReadMessage(_sslStream);
                });

                Console.WriteLine("按Q退出程序");
                string message = "";
                message = Console.ReadLine() + "<EOF>";
                while (message != "Q")
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(message);
                    _sslStream.Write(bytes);
                    _sslStream.Flush();
                    Console.WriteLine("send:" + message);
                    message = Console.ReadLine() + "<EOF>";
                }

                client.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
            }
        }
Beispiel #45
0
        public static void X509CertificateCollectionThrowsArgumentNullException()
        {
            using (X509Certificate certificate = new X509Certificate())
            {
                Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509Certificate[])null));
                Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509CertificateCollection)null));

                X509CertificateCollection collection = new X509CertificateCollection { certificate };

                Assert.Throws<ArgumentNullException>(() => collection[0] = null);
                Assert.Throws<ArgumentNullException>(() => collection.Add(null));
                Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null));
                Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null));
                Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0));
                Assert.Throws<ArgumentNullException>(() => collection.Insert(0, null));
                Assert.Throws<ArgumentNullException>(() => collection.Remove(null));

                IList ilist = (IList)collection;
                Assert.Throws<ArgumentNullException>(() => ilist[0] = null);
                Assert.Throws<ArgumentNullException>(() => ilist.Add(null));
                Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0));
                Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null));
                Assert.Throws<ArgumentNullException>(() => ilist.Remove(null));
            }

            Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection.X509CertificateEnumerator(null));
        }
Beispiel #46
0
        public HttpWebResponse executeRequest(object data, String url, bool isAuth, string method, SymConfig symConfig, bool isAgent)
        {
            if (method == WebRequestMethods.Http.Post && isAuth != true)
            {
                HttpWebResponse response = null;
                response = postApi(symConfig, url, data, isAgent);
                return(response);
            }

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

            if (symConfig.sessionProxyURL.Length > 0 && url.Contains("sessionauth"))
            {
                WebProxy sessionProxy    = new WebProxy();
                Uri      sessionProxyUri = new Uri(symConfig.sessionProxyURL);
                sessionProxy.Address     = sessionProxyUri;
                sessionProxy.Credentials = new NetworkCredential(symConfig.sessionProxyUsername, symConfig.sessionProxyPassword);
                req.Proxy = sessionProxy;
            }
            else if (symConfig.proxyURL.Length > 0 && (url.Contains("pod") || url.Contains("sessionauth")))
            {
                WebProxy proxy    = new WebProxy();
                Uri      proxyUri = new Uri(symConfig.proxyURL);
                proxy.Address     = proxyUri;
                proxy.Credentials = new NetworkCredential(symConfig.proxyUsername, symConfig.proxyPassword);
                req.Proxy         = proxy;
            }
            req.Credentials = CredentialCache.DefaultCredentials;
            req.Method      = method;
            if (isAuth)
            {
                Certificates = new X509CertificateCollection();
                byte[] cert = File.ReadAllBytes(symConfig.botCertPath + symConfig.botCertName + ".p12");
                Certificates.Add(new X509Certificate2(cert, symConfig.botCertPassword));
                req.ClientCertificates.AddRange(Certificates);
                if (symConfig.authTokens != null)
                {
                    req.Headers.Add("sessionToken", symConfig.authTokens.sessionToken);
                }
            }
            else if (isAgent)
            {
                req.Headers.Add("sessionToken", symConfig.authTokens.sessionToken);
                req.Headers.Add("keyManagerToken", symConfig.authTokens.keyManagerToken);
            }
            else if (!isAgent)
            {
                req.Headers.Add("sessionToken", symConfig.authTokens.sessionToken);
            }



            //req.Proxy = Proxy;

            HttpWebResponse resp = null;

            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode != HttpStatusCode.OK)
                {
                    ErrorHandler errorHandler = new ErrorHandler();
                    errorHandler.handleError(resp);
                }

                return(resp);
            }
            catch (WebException we)
            {
                resp = we.Response as HttpWebResponse;
                Console.Write(resp);
            }
            return(null);
        }
Beispiel #47
0
        public static void X509CertificateCollectionAdd()
        {
            using (X509Certificate2 c1 = new X509Certificate2())
            using (X509Certificate2 c2 = new X509Certificate2())
            {
                X509CertificateCollection cc = new X509CertificateCollection();
                int idx = cc.Add(c1);
                Assert.Equal(0, idx);
                Assert.Same(c1, cc[0]);

                idx = cc.Add(c2);
                Assert.Equal(1, idx);
                Assert.Same(c2, cc[1]);

                Assert.Throws<ArgumentNullException>(() => cc.Add(null));


                IList il = new X509CertificateCollection();
                idx = il.Add(c1);
                Assert.Equal(0, idx);
                Assert.Same(c1, il[0]);

                idx = il.Add(c2);
                Assert.Equal(1, idx);
                Assert.Same(c2, il[1]);

                Assert.Throws<ArgumentNullException>(() => il.Add(null));
            }
        }
Beispiel #48
0
        void EvaluateTrust()
        {
            InitializeSession();

            /*
             * We're using .NET's SslStream semantics here.
             *
             * A server must always provide a valid certificate.
             *
             * However, in server mode, "ask for client certificate" means that
             * we ask the client to provide a certificate, then invoke the client
             * certificate validator - passing 'null' if the client didn't provide
             * any.
             *
             */

            bool     ok;
            SecTrust trust = null;
            X509CertificateCollection certificates = null;

            try {
                trust = GetPeerTrust(!IsServer);

                if (trust == null || trust.Count == 0)
                {
                    remoteCertificate = null;
                    if (!IsServer)
                    {
                        throw new TlsException(AlertDescription.CertificateUnknown);
                    }
                    certificates = null;
                }
                else
                {
                    if (trust.Count > 1)
                    {
                        Debug("WARNING: Got multiple certificates in SecTrust!");
                    }

                    certificates = new X509CertificateCollection();
                    for (int i = 0; i < trust.Count; i++)
                    {
                        certificates.Add(trust.GetCertificate(i));
                    }

                    remoteCertificate = new X509Certificate(certificates [0]);
                    Debug("Got peer trust: {0}", remoteCertificate);
                }

                ok = ValidateCertificate(certificates);
            } catch (Exception ex) {
                Debug("Certificate validation failed: {0}", ex);
                throw;
            } finally {
                if (trust != null)
                {
                    trust.Dispose();
                }
                if (certificates != null)
                {
                    for (int i = 0; i < certificates.Count; i++)
                    {
                        certificates [i].Dispose();
                    }
                }
            }

            if (!ok)
            {
                throw new TlsException(AlertDescription.CertificateUnknown);
            }
        }
Beispiel #49
0
	private void StartSession()
	{
		Global.Log("Starting SSL session with lockdownd... ");

		MemoryStream MS = new MemoryStream();
		XmlWriter XTW = XmlWriter.Create(MS, XWS);
		XTW.WriteStartDocument();
		XTW.WriteDocType("plist", sApplePubID, sAppleSysID, null);
		XTW.WriteStartElement("plist");
		XTW.WriteAttributeString("version", "1.0");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "HostID");
		XTW.WriteElementString("string", iPhone.sHostID);
		XTW.WriteElementString("key", "Request");
		XTW.WriteElementString("string", "StartSession");

		XTW.WriteEndElement(); // dict
		XTW.WriteEndElement(); // plist
		XTW.WriteEndDocument();
		XTW.Flush();

		byte[] bXMLData = MS.GetBuffer();
		XTW.Close(); // Closes MS, too.

		PListSend(bXMLData);
		bXMLData = PListReceive();

		MS = new MemoryStream(bXMLData);
		XmlDocument XD = new XmlDocument();
		XD.XmlResolver = null; // Don't fetch DTD from web. Speeds things up tremendously.
		XD.Load(MS);
		MS.Close();

		if (XD["plist"]["dict"].SelectSingleNode("key[text()='Result']") != null
			&& XD["plist"]["dict"].SelectSingleNode("key[text()='Result']").NextSibling.InnerText == "Success")
			sSessionID = XD["plist"]["dict"].SelectSingleNode("key[text()='SessionID']").NextSibling.InnerText;
		else
		{
			Global.Log("failed!\n", true);
			throw new Exception("StartSession command was rejected.");
		}

		// Start the SSL session.
		try
		{
			SSLInOutStream = new SSLHelperStream(this.LockdownReceiveSSLCallback, this.LockdownSendSSLCallback);
			SSLConnection = new System.Net.Security.SslStream(SSLInOutStream, false,
											(s, c, ch, e) => { return true; },
											(s, t, L, r, a) => { if (L != null && L.Count > 0) return L[0]; return null; });

			X509CertificateCollection CC = new X509CertificateCollection();
			X509Certificate2 RootCertWithPrivKey = new X509Certificate2(iPhone.RootCertificate.GetEncoded());
			RootCertWithPrivKey.PrivateKey = Org.BouncyCastle.Security.DotNetUtilities.ToRSA((Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)iPhone.RootKey.Private);
			CC.Add(RootCertWithPrivKey);
			SSLConnection.AuthenticateAsClient(string.Empty, CC, System.Security.Authentication.SslProtocols.Ssl3, false);
		}
		catch (Exception e)
		{
			Global.Log("failed!\n", true);
			throw e;
		}

		if (!SSLConnection.IsAuthenticated)
		{
			Global.Log("failed!\n", true);
			SSLConnection = null;
			throw new Exception("AuthenticateAsClient succeeds but IsAuthenticated is false.");
		}

		Global.Log("success!\n", true);
	}
Beispiel #50
0
		static X509CertificateCollection LoadCertificates (string filename, string password, bool verbose) 
		{
			X509Certificate x509 = null;
			X509CertificateCollection coll = new X509CertificateCollection ();
			switch (Path.GetExtension (filename).ToUpper ()) {
				case ".P7B":
				case ".SPC":
					SoftwarePublisherCertificate spc = SoftwarePublisherCertificate.CreateFromFile (filename);
					coll.AddRange (spc.Certificates);
					spc = null;
					break;
				case ".CER":
				case ".CRT":
					using (FileStream fs = File.OpenRead (filename)) {
						byte[] data = new byte [fs.Length];
						fs.Read (data, 0, data.Length);
						if (data [0] != 0x30) {
							// maybe it's ASCII PEM base64 encoded ?
							data = PEM ("CERTIFICATE", data);
						}
						if (data != null)
							x509 = new X509Certificate (data);
					}
					if (x509 != null)
						coll.Add (x509);
					break;
				case ".P12":
				case ".PFX":
					PKCS12 p12 = password == null ? PKCS12.LoadFromFile (filename)
						: PKCS12.LoadFromFile (filename, password);
					X509CertificateCollection tmp = new X509CertificateCollection (p12.Certificates);

					for (int i = 0; i != p12.Keys.Count; i++) {
						X509Certificate cert = p12.Certificates[i];
						RSACryptoServiceProvider pk = p12.Keys[i] as RSACryptoServiceProvider;

						if (pk == null || pk.PublicOnly)
							continue;

						if (verbose)
							Console.WriteLine ("Found key for certificate: {0}", cert.SubjectName);

						tmp[0].RSA = pk;
					}
					coll.AddRange(tmp);
					p12 = null;
					break;
				default:
					Console.WriteLine ("Unknown file extension: {0}", 
						Path.GetExtension (filename));
					break;
			}
			return coll;
		}