Example #1
1
 public static void Main()
 {
     using (Socket clientSocket = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Stream,
                                             ProtocolType.Tcp))
     {
         // Addressing
         IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress);
         IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port);
         // Connecting
         Debug.Print("Connecting to server " + serverEndPoint + ".");
         clientSocket.Connect(serverEndPoint);
         Debug.Print("Connected to server.");
         using (SslStream sslStream = new SslStream(clientSocket))
         {
             X509Certificate rootCA =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
             X509Certificate clientCert =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
             sslStream.AuthenticateAsClient("MyServerName", // Hostname needs to match CN of server cert
                                            clientCert, // Authenticate client
                                            new X509Certificate[] { rootCA }, // CA certs for verification
                                            SslVerification.CertificateRequired, // Verify server
                                            SslProtocols.Default // Protocols that may be required
                                            );
             // Sending
             byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!");
             sslStream.Write(messageBytes, 0, messageBytes.Length);
         }
     }// the socket will be closed here
 }
Example #2
0
        // Initialize all of the default certificates and protocols
        public SslServer()
        {
            // Initialize the Socket
            serverSocketType = SocketType.Stream;
            serverProtocolType = ProtocolType.Tcp;

            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                cert = new X509Certificate(CertificatesAndCAs.emuCert, "NetMF");
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caEmuCert) };
            }
            else
            {
                // Initialize the SslStream
                cert = new X509Certificate(CertificatesAndCAs.newCert);
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caCert) };
            }
            verify = SslVerification.NoVerification;
            sslProtocols = new SslProtocols[] { SslProtocols.Default };

            // Create a TCP/IP (IPv4) socket and listen for incoming connections.
            serverSocket = new Socket(AddressFamily.InterNetwork, serverSocketType, serverProtocolType);
            serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, false);

            serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            serverEp = (IPEndPoint)serverSocket.LocalEndPoint;

            Log.Comment("Listening for a client to connect...");
            serverSocket.Listen(1);
        }
Example #3
0
 public static void Main()
 {
     using (Socket listeningSocket = new Socket(AddressFamily.InterNetwork,
                                                SocketType.Stream,
                                                ProtocolType.Tcp))
     {
         listeningSocket.Bind(new IPEndPoint(IPAddress.Any, port));
         Debug.Print("Listening for a client...");
         listeningSocket.Listen(1);
         using (Socket communicationSocket = listeningSocket.Accept())
         {
             Debug.Print("Connected to client.");
             using (SslStream sslStream = new SslStream(communicationSocket))
             {
                 X509Certificate serverCert =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyServer));
                 X509Certificate rootCA =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
                 sslStream.AuthenticateAsServer(serverCert, // To authenticate the server
                                                new X509Certificate[] { rootCA }, // CA certificates
                                                SslVerification.CertificateRequired, // Verify client
                                                SslProtocols.Default // Protocols that may be used
                                                );
                 //wait infinitely to get a response
                 sslStream.ReadTimeout = -1;
                 byte[] inBuffer = new byte[1000];
                 int count = sslStream.Read(inBuffer, 0, inBuffer.Length);
                 string message = new string(Encoding.UTF8.GetChars(inBuffer));
                 Debug.Print("Received '" + message + "'.");
             }
         }
     }
 }
        public MFTestResults AddThenGetCACertificate()
        {
            bool testResult = true;

            try
            {
                Log.Comment("Add Certificates, then Get those that were added");
                X509Certificate cert1a = new X509Certificate(CertificatesAndCAs.caCert);
                X509Certificate cert2a = new X509Certificate(CertificatesAndCAs.newCert);

                CertificateStore.AddCACertificate("cert1", cert1a);
                CertificateStore.AddCACertificate("cert2", cert2a);

                Log.Comment("Get the certificates and make sure they are what we put in");
                X509Certificate cert1 = CertificateStore.GetCACertificate("cert1");
                X509Certificate cert2 = CertificateStore.GetCACertificate("cert2");

                testResult &= Tools.CertificateCompare(cert1, cert1a);
                testResult &= Tools.CertificateCompare(cert2, cert2a);

                Log.Comment("clean up the cert that was added.");
                CertificateStore.RemoveCACertificate("cert1");
                CertificateStore.RemoveCACertificate("cert2");
            }
            finally
            {
                CertificateStore.ClearAllCertificates();
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
        /// <summary>
        /// Retrieves a page from a Web server, using a simple GET request.
        /// </summary>
        public static void Main()
        {
            // Root CA Certificate needed to validate HTTPS servers.
            byte[] ca = Resource1.GetBytes(
                Resource1.BinaryResources.VerisignCA);

            X509Certificate[] caCerts = 
                new X509Certificate[] { new X509Certificate(ca) };

            // Initialize the default webproxy to be used by all 
            // HttpWebRequests.
            // Change the proxy address to fit your environment.
            HttpWebRequest.DefaultWebProxy = 
                new WebProxy("itgproxy.dns.microsoft.com", true);

            // Print the HTTP data from each of the following pages.
            PrintHttpData("http://autos.msn.com/default.aspx", null);
            PrintHttpData("http://www.nytimes.com/", null);

            // Test SSL connection with no certificate verification
            PrintHttpData("https://www.google.com/accounts/ManageAccount/", null);

            // Read from secure webpages by using the Verisign Root CA 
            // certificate that is stored in the Resource1.resx file.
            PrintHttpData("https://www.google.com/accounts/ManageAccount/", 
                caCerts);
        }
Example #6
0
        static public bool CertificateCompare(X509Certificate cert1, X509Certificate cert2)
        {
            if( cert1 == null || cert2 == null )
            {
                Log.Comment("One of the certificates is null");
                return false;
            }

            byte [] cert1Bytes = cert1.GetRawCertData();
            byte [] cert2Bytes = cert2.GetRawCertData();

            return CertificateCompare(cert1Bytes, cert2Bytes);
        }
Example #7
0
            internal bool Update(string certName, X509Certificate cert)
            {
                int idx = m_names.IndexOf(certName);

                if (-1 == idx) return false;

                ExtendedWeakReference ewr = ExtendedWeakReference.Recover(typeof(_CertStore_), (uint)m_values[idx]);

                if (ewr == null) return false;

                ewr.Target = cert;
                ewr.PushBackIntoRecoverList();

                return true;
            }
        public InitializeResult Initialize()
        {
            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.caCert);
            }
            catch (System.NotSupportedException)
            {
                Log.Comment("If this feature throws an exception then it is assumed that it isn't supported on this device type");                
                return InitializeResult.Skip;
            }
            
            CertificateStore.ClearAllCertificates();

            return InitializeResult.ReadyToGo; 
        }
        public SslServer(X509Certificate certificate, X509Certificate[] ca, SslVerification clientCertificateRequired, SslProtocols[] enabledSslProtocols, bool expectedException)
        {
            this.certificate = certificate;
            this.ca = ca;
            this.clientCertificateRequired = clientCertificateRequired;
            this.enabledSslProtocols = enabledSslProtocols;
            this.expectedException = expectedException;

            //Get the IPV4 address on this machine which is all that the MF devices support.
            IPHostEntry hostEntry = Dns.GetHostEntry("");
            ipAddress = hostEntry.AddressList[0];

            if (ipAddress == null)
                throw new Exception("No IPV4 address found.");

        }
Example #10
0
        public SslClient(IPAddress ipAddress, String targetHost, X509Certificate cert, X509Certificate [] ca, SslVerification verify, SslProtocols[] sslProtocols, bool expectedException)
        {
            // Initialize the Socket
            messageSent = MFUtilities.GetRandomSafeString(2000) + TERMINATOR;

            // Initialize the port that communication is using
            port = 11111;
            this.ipAddress = ipAddress;
            this.messageSent = "hello" + TERMINATOR;
            this.targetHost = targetHost;
            this.cert = cert;
            this.ca = ca;
            this.verify = verify;
            this.sslProtocols = sslProtocols;
            this.expectedException = expectedException;
        }
Example #11
0
        public InitializeResult Initialize()
        {
            Log.Comment("Adding set up for the tests");
            
            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.caCert);
            }
            catch (NotSupportedException)
            {
                Log.Comment("If this feature throws an exception then it is assumed that it isn't supported on this device type");
                return InitializeResult.Skip;
            }

            return InitializeResult.ReadyToGo;     
        }
        public InitializeResult Initialize()
        {
            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.caCert);
            }
            catch (NotSupportedException)
            {
                Log.Comment("If this feature throws an exception then it is assumed that it isn't supported on this device type");
                return InitializeResult.Skip;
            }
            
            Log.Comment("Adding set up for the tests.");
            Log.Comment("Thus debugging without knowing if there is a cert in flash without starting from scratch is disasterous.");
            CertificateStore.ClearAllCertificates();
            Debug.GC(true);

            return InitializeResult.ReadyToGo; 
        }
        public MFTestResults ConstructorValid()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Create an X509 Certificate.  No Exceptions should be thrown.");

            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.caCert);
                testResult = MFTestResults.Pass;
            }
            catch (Exception e)
            {
                Log.Comment("Failed to create a valid certificate with exception: " + e.ToString());
                testResult = MFTestResults.Fail;
            }

            return testResult;
        }
        public MFTestResults ConstructorInvalidFuzzed()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Create a fuzzed X509 Certificate.  Should throw exception.");

            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.fuzzedCert);
                Log.Comment("Did not throw exception creating fuzzed Cert.");
            }
            catch (Exception e)
            {
                Log.Comment("Correctly threw exception creating fuzzed cert: " + e.ToString());
                testResult = MFTestResults.Pass;
            }

            return testResult;
        }
Example #15
0
            internal bool Add(string certName, X509Certificate cert)
            {
                if (-1 != m_names.IndexOf(certName)) return false;

                m_names.Add(certName);

                uint idx = GetNextFreeIndex();

                m_values.Add(idx);

                ExtendedWeakReference ewr = ExtendedWeakReference.RecoverOrCreate(typeof(_CertStore_), (uint)idx, ExtendedWeakReference.c_SurvivePowerdown);

                ewr.Priority = (int)ExtendedWeakReference.PriorityLevel.Critical;

                ewr.Target = cert;

                ewr.PushBackIntoRecoverList();

                return true;
            }
Example #16
0
        public SslClient()
        {
            // Initialize the Socket
            clientSocketType = SocketType.Stream;
            clientProtocolType = ProtocolType.Tcp;

            if (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3)
            {
                cert = new X509Certificate(CertificatesAndCAs.emuCert, "NetMF");
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caEmuCert) };
                targetHost = "ZACHL-SBA1.redmond.corp.microsoft.com";
            }
            else
            {
                cert = new X509Certificate(CertificatesAndCAs.newCert);
                ca = new X509Certificate[] { new X509Certificate(CertificatesAndCAs.caCert) };
                targetHost = "Device.Microsoft.Com";
            }
            verify = SslVerification.CertificateRequired;
            sslProtocols = new SslProtocols[] { SslProtocols.Default };
        }
Example #17
0
        internal void Authenticate(bool isServer, string targetHost, X509Certificate certificate, X509Certificate[] ca, SslVerification verify, params SslProtocols[] sslProtocols)
        {
            SslProtocols vers = (SslProtocols)0;

            if (-1 != _sslContext) throw new InvalidOperationException();

            for (int i = sslProtocols.Length - 1; i >= 0; i--)
            {
                vers |= sslProtocols[i];
            }

            _isServer = isServer;

            try
            {
                if (isServer)
                {
                    _sslContext = SslNative.SecureServerInit((int)vers, (int)verify, certificate, ca);
                    SslNative.SecureAccept(_sslContext, _socket);
                }
                else
                {
                    _sslContext = SslNative.SecureClientInit((int)vers, (int)verify, certificate, ca);
                    SslNative.SecureConnect(_sslContext, targetHost, _socket);
                }
            }
            catch
            {
                if (_sslContext != -1)
                {
                    SslNative.ExitSecureContext(_sslContext);
                    _sslContext = -1;
                }

                throw;
            }
        }
Example #18
0
 public void UpdateCertificates(X509Certificate cert, X509Certificate[] ca)
 {
     if(_sslContext == -1) throw new InvalidOperationException();
     
     SslNative.UpdateCertificates(_sslContext, cert, ca);
 }
Example #19
0
 public void AuthenticateAsServer(X509Certificate cert, X509Certificate[] ca, SslVerification verify, params SslProtocols[] sslProtocols)
 {
     Authenticate(true, "", cert, ca, verify, sslProtocols);
 }
Example #20
0
 public void AuthenticateAsServer(X509Certificate cert, SslVerification verify, params SslProtocols[] sslProtocols)
 {
     AuthenticateAsServer(cert, CertificateStore.CACertificates, verify, sslProtocols);
 }
Example #21
0
 public void AuthenticateAsClient(string targetHost, X509Certificate cert, X509Certificate[] ca, SslVerification verify, params SslProtocols[] sslProtocols)
 {
     Authenticate(false, targetHost, cert, ca, verify, sslProtocols);
 }
Example #22
0
 public void AuthenticateAsClient(string targetHost, X509Certificate cert, SslVerification verify, params SslProtocols[] sslProtocols)
 {
     AuthenticateAsClient(targetHost, cert, CertificateStore.CACertificates, verify, sslProtocols);
 }
        public MFTestResults GetRawDataNewCert()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Get the raw data from the valid certificate");

            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.newCert);
                byte[] rawCert = cert.GetRawCertData();

                if (Tools.CertificateCompare(CertificatesAndCAs.newCert, rawCert))
                    testResult = MFTestResults.Pass;
            }
            catch (Exception e)
            {
                Log.Comment("Incorrectly threw exception calling GetRawCertData: " + e.ToString());
                testResult = MFTestResults.Fail;
            }

            return testResult;
        }
 internal static extern void UpdateCertificates(int contextHandle, X509Certificate certificate, X509Certificate[] ca);
        public MFTestResults IssuerGetCaCert()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Get the Issuer field of a valid certificate");

            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.caCert);
                string issuer = cert.Issuer;

                Log.Comment("TODO: Validate the issuer here");
                Log.Comment("The issuer is: " + issuer);
                testResult = MFTestResults.Pass;
            }
            catch (Exception e)
            {
                Log.Comment("Incorrectly threw exception calling Issuer: " + e.ToString());
                testResult = MFTestResults.Fail;
            }

            return testResult;
        }
        public MFTestResults ConstructorInvalidNull()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Create a null X509 Certificate.  Should throw exception.");

            try
            {
                X509Certificate cert = new X509Certificate(null);
            }
            catch (Exception e)
            {
                Log.Comment("Correctly threw exception creating null cert: " + e.ToString());
                testResult = MFTestResults.Pass;
            }

            return testResult;
        }
        public MFTestResults SubjectGetNewCert()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Get the Subject field of a valid certificate");

            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.newCert);
                string subject = cert.Subject;

                Log.Comment("TODO: Validate the subject here");
                Log.Comment("The subject is: " + subject);
                testResult = MFTestResults.Pass;
            }
            catch (Exception e)
            {
                Log.Comment("Incorrectly threw exception calling Subject: " + e.ToString());
                testResult = MFTestResults.Fail;
            }

            return testResult;
        }
Example #28
0
        public static bool UpdateCACertificate(string certName, X509Certificate cert)
        {
            int idx = s_CACertData.Names.IndexOf(certName);

            if (-1 == idx) return false;

            s_CACertData.Values[idx] = cert;

            s_ewrCALookup.Target = s_CACertData;
            s_ewrCALookup.PushBackIntoRecoverList();

            if (OnCACertificateChange != null)
            {
                OnCACertificateChange(CertificateNotificationType.Updated, certName);
            }

            return true;
        }
 internal static extern int SecureClientInit(int sslProtocols, int sslCertVerify, X509Certificate certificate, X509Certificate[] ca);
        public MFTestResults GetExpirationDateNewCert()
        {
            MFTestResults testResult = MFTestResults.Fail;

            Log.Comment("Get the Expiration Date field of a valid certificate");

            try
            {
                X509Certificate cert = new X509Certificate(CertificatesAndCAs.newCert);
                DateTime date = cert.GetExpirationDate();

                Log.Comment("TODO: Validate the DateTime here");
                Log.Comment("The DateTime is: " + date.ToString());
                testResult = MFTestResults.Pass;
            }
            catch (Exception e)
            {
                Log.Comment("Incorrectly threw exception calling Date: " + e.ToString());
                testResult = MFTestResults.Fail;
            }

            return testResult;
        }