Ejemplo n.º 1
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            // put this here just in case the user hasn't selected the file path
            CookiesFile cookiesFile = CookiesFile.GetInstance();
            if (cookiesFile.StoreLocation != null)
            {
                certificateStore = CertificateStore<CodeSigningCertificate>.GetInstance(cookiesFile.StoreLocation);
            }

            CodeSigningCertificateGenerator cert = new CodeSigningCertificateGenerator();
            cert.SignatureAlgorithm = (string)lstAlgorithms.SelectedItem;
            cert.StartDate = dtpStartDate.Value;
            cert.EndDate = dtpEndDate.Value;
            cert.IssuerDistinguishedName = txtIssuerDN.Text;
            cert.SubjectDistinguishedName = txtSubjectDN.Text;
            if (chkCodeSigning.Checked)
            {
                cert.AddCodeSigningOid();
            }
            if (chkBasicConstraints.Checked)
            {
                if (txtPathLen.Text.Length != 0 && (!Char.IsNumber(txtPathLen.Text.ToCharArray()[0])))
                {
                    throw new ApplicationException("The PathLen field must be a number value");
                }

                cert.AddBasicContraintsOid(chkIsCA.Checked, int.Parse(txtPathLen.Text));
            }
            statusAlgorithm.Text = "Generating certificate at store location " + cookiesFile.StoreLocation;
            gen = new CompleteCertGeneration(cert.GenerateCertificate);

            gen.BeginInvoke(new AsyncCallback(CallbackStatusCertUpdate), cert);
        }
Ejemplo n.º 2
0
        public static Certificate GetSignedCertificate(Uri apiUri, CertificateStore certStore)
        {
            using (WebClient client = new WebClient())
            {
                client.Headers.Add("User-Agent", GetUserAgent());

                byte[] data = client.DownloadData(apiUri.AbsoluteUri + "?cmd=dlc&email=" + certStore.Certificate.IssuedTo.EmailAddress.Address);

                using (BinaryReader bR = new BinaryReader(new MemoryStream(data)))
                {
                    int errorCode = bR.ReadInt32();
                    if (errorCode != 0)
                    {
                        string message = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32()));
                        string remoteStackTrace = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadInt32()));

                        throw new BitChatException(message);
                    }

                    Certificate cert = new Certificate(bR);

                    if (!cert.IssuedTo.EmailAddress.Equals(certStore.Certificate.IssuedTo.EmailAddress) || (cert.PublicKeyEncryptionAlgorithm != certStore.PrivateKey.Algorithm) || (cert.PublicKeyXML != certStore.PrivateKey.GetPublicKey()))
                        throw new BitChatException("Invalid signed certificate received. Please try again.");

                    return cert;
                }
            }
        }
Ejemplo n.º 3
0
 public void BeforeEachTest()
 {
     _authority = new CertificateAuthority("MyAuthority");
     _mockPersonalStore = new Mock<ICertificateStore>();
     _mockRootStore = new Mock<ICertificateStore>();
     _certStore = new CertificateStore(_mockPersonalStore.Object, _mockRootStore.Object);
 }
Ejemplo n.º 4
0
 public BitChatProfile(CertificateStore localCertStore, IPEndPoint localEP, string downloadFolder, Uri[] trackerURIs)
 {
     _localCertStore = localCertStore;
     _localEP = localEP;
     _downloadFolder = downloadFolder;
     _bitChatInfoList = new BitChatInfo[] { };
     _trackerURIs = trackerURIs;
     _checkCertificateRevocationList = true;
 }
Ejemplo n.º 5
0
        public void ShouldSaveTheAuthorityCertificate()
        {
            var cert = _authority.ToX509Certificate();
            _mockPersonalStore.Setup(x => x.Find(cert.Thumbprint)).Returns(cert);

            var certStore = new CertificateStore(_mockPersonalStore.Object, _mockRootStore.Object);
            Assert.That(certStore.SaveAuthority(cert));

            _mockPersonalStore.Verify(x => x.Save(cert)); //saved to personalStore first
            _mockRootStore.Verify(x => x.Save(cert)); //saved to rootStore
            _mockPersonalStore.Verify(x => x.Delete(cert)); //removed from personalStore
        }
        public SecureChannelClientStream(Stream stream, IPEndPoint remotePeerEP, CertificateStore clientCredentials, Certificate[] trustedRootCertificates, ISecureChannelSecurityManager manager, SecureChannelCryptoOptionFlags supportedOptions, int reNegotiateOnBytesSent, int reNegotiateAfterSeconds, string preSharedKey = null)
            : base(remotePeerEP, reNegotiateOnBytesSent, reNegotiateAfterSeconds)
        {
            _clientCredentials = clientCredentials;
            _trustedRootCertificates = trustedRootCertificates;
            _manager = manager;
            _supportedOptions = supportedOptions;
            _preSharedKey = preSharedKey;

            try
            {
                //read server protocol version
                _version = stream.ReadByte();

                switch (_version)
                {
                    case 4:
                        //send supported client version
                        stream.WriteByte(4);

                        ProtocolV4(stream, clientCredentials, trustedRootCertificates, manager, preSharedKey, supportedOptions);
                        break;

                    default:
                        throw new SecureChannelException(SecureChannelCode.ProtocolVersionNotSupported, _remotePeerEP, _remotePeerCert, "SecureChannel protocol version '" + _version + "' not supported.");
                }
            }
            catch (SecureChannelException ex)
            {
                try
                {
                    if (_baseStream == null)
                        SecureChannelPacket.WritePacket(stream, ex.Code);
                    else
                        SecureChannelPacket.WritePacket(this, ex.Code);
                }
                catch
                { }

                throw new SecureChannelException(ex.Code, _remotePeerEP, _remotePeerCert, ex.Message, ex.InnerException);
            }
        }
        private void ProtocolV4(Stream stream, CertificateStore clientCredentials, Certificate[] trustedRootCertificates, ISecureChannelSecurityManager manager, string preSharedKey, SecureChannelCryptoOptionFlags supportedOptions)
        {
            #region 1. hello handshake

            //send client hello
            SecureChannelPacket.Hello clientHello = new SecureChannelPacket.Hello(BinaryID.GenerateRandomID256(), supportedOptions);
            SecureChannelPacket.WritePacket(stream, clientHello);

            //read server hello
            SecureChannelPacket.Hello serverHello = (new SecureChannelPacket(stream)).GetHello();

            //read selected crypto option
            _selectedCryptoOption = supportedOptions & serverHello.CryptoOptions;

            if (_selectedCryptoOption == SecureChannelCryptoOptionFlags.None)
                throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);

            #endregion

            #region 2. key exchange

            //read server key exchange data
            SecureChannelPacket.KeyExchange serverKeyExchange = (new SecureChannelPacket(stream)).GetKeyExchange();

            SymmetricEncryptionAlgorithm encAlgo;
            string hashAlgo;
            KeyAgreement keyAgreement;

            switch (_selectedCryptoOption)
            {
                case SecureChannelCryptoOptionFlags.DHE2048_RSA_WITH_AES256_CBC_HMAC_SHA256:
                    encAlgo = SymmetricEncryptionAlgorithm.Rijndael;
                    hashAlgo = "SHA256";
                    keyAgreement = new DiffieHellman(DiffieHellmanGroupType.RFC3526, 2048, KeyAgreementKeyDerivationFunction.Hmac, KeyAgreementKeyDerivationHashAlgorithm.SHA256);
                    break;

                case SecureChannelCryptoOptionFlags.ECDHE256_RSA_WITH_AES256_CBC_HMAC_SHA256:
                    encAlgo = SymmetricEncryptionAlgorithm.Rijndael;
                    hashAlgo = "SHA256";
                    keyAgreement = new TechnitiumLibrary.Security.Cryptography.ECDiffieHellman(256, KeyAgreementKeyDerivationFunction.Hmac, KeyAgreementKeyDerivationHashAlgorithm.SHA256);
                    break;

                default:
                    throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            //send client key exchange data
            SecureChannelPacket.KeyExchange clientKeyExchange = new SecureChannelPacket.KeyExchange(keyAgreement.GetPublicKeyXML(), clientCredentials.PrivateKey, hashAlgo);
            SecureChannelPacket.WritePacket(stream, clientKeyExchange);

            //generate master key
            byte[] masterKey = GenerateMasterKey(clientHello, serverHello, _preSharedKey, keyAgreement, serverKeyExchange.PublicKeyXML);

            //verify master key using HMAC authentication
            {
                SecureChannelPacket.Authentication clientAuthentication = new SecureChannelPacket.Authentication(serverHello, masterKey);
                SecureChannelPacket.WritePacket(stream, clientAuthentication);

                SecureChannelPacket.Authentication serverAuthentication = (new SecureChannelPacket(stream)).GetAuthentication();
                if (!serverAuthentication.IsValid(clientHello, masterKey))
                    throw new SecureChannelException(SecureChannelCode.ProtocolAuthenticationFailed, _remotePeerEP, _remotePeerCert);
            }

            //enable channel encryption
            switch (encAlgo)
            {
                case SymmetricEncryptionAlgorithm.Rijndael:
                    //using MD5 for generating AES IV of 128bit block size
                    HashAlgorithm md5Hash = HashAlgorithm.Create("MD5");
                    byte[] eIV = md5Hash.ComputeHash(clientHello.Nonce.ID);
                    byte[] dIV = md5Hash.ComputeHash(serverHello.Nonce.ID);

                    //create encryption and decryption objects
                    SymmetricCryptoKey encryptionKey = new SymmetricCryptoKey(SymmetricEncryptionAlgorithm.Rijndael, masterKey, eIV, PaddingMode.None);
                    SymmetricCryptoKey decryptionKey = new SymmetricCryptoKey(SymmetricEncryptionAlgorithm.Rijndael, masterKey, dIV, PaddingMode.None);

                    //enable encryption
                    EnableEncryption(stream, encryptionKey, decryptionKey, new HMACSHA256(masterKey), new HMACSHA256(masterKey));
                    break;

                default:
                    throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            //channel encryption is ON!

            #endregion

            #region 3. exchange & verify certificates & signatures

            if (!_reNegotiating)
            {
                //send client certificate
                SecureChannelPacket.WritePacket(this, clientCredentials.Certificate);

                //read server certificate
                _remotePeerCert = (new SecureChannelPacket(this)).GetCertificate();

                //verify server certificate
                try
                {
                    _remotePeerCert.Verify(trustedRootCertificates);
                }
                catch (Exception ex)
                {
                    throw new SecureChannelException(SecureChannelCode.InvalidRemoteCertificate, _remotePeerEP, _remotePeerCert, "Invalid remote certificate.", ex);
                }
            }

            //verify key exchange signature
            switch (_selectedCryptoOption)
            {
                case SecureChannelCryptoOptionFlags.DHE2048_RSA_WITH_AES256_CBC_HMAC_SHA256:
                case SecureChannelCryptoOptionFlags.ECDHE256_RSA_WITH_AES256_CBC_HMAC_SHA256:
                    if (_remotePeerCert.PublicKeyEncryptionAlgorithm != AsymmetricEncryptionAlgorithm.RSA)
                        throw new SecureChannelException(SecureChannelCode.InvalidRemoteCertificateAlgorithm, _remotePeerEP, _remotePeerCert);

                    if (!serverKeyExchange.IsSignatureValid(_remotePeerCert, "SHA256"))
                        throw new SecureChannelException(SecureChannelCode.InvalidRemoteKeyExchangeSignature, _remotePeerEP, _remotePeerCert);

                    break;

                default:
                    throw new SecureChannelException(SecureChannelCode.NoMatchingCryptoAvailable, _remotePeerEP, _remotePeerCert);
            }

            if ((manager != null) && !manager.ProceedConnection(_remotePeerCert))
                throw new SecureChannelException(SecureChannelCode.SecurityManagerDeclinedAccess, _remotePeerEP, _remotePeerCert, "Security manager declined access.");

            #endregion
        }
Ejemplo n.º 8
0
 public BitChatProfile(CertificateStore localCertStore, IPEndPoint localEP, string downloadFolder, Uri[] trackerURIs, string password)
     : base(SymmetricEncryptionAlgorithm.Rijndael, 256, password)
 {
     _localCertStore = localCertStore;
     _localEP = localEP;
     _downloadFolder = downloadFolder;
     _bitChatInfoList = new BitChatInfo[] { };
     _trackerURIs = trackerURIs;
     _checkCertificateRevocationList = true;
 }
Ejemplo n.º 9
0
        protected override void ReadPlainTextFrom(BinaryReader bR)
        {
            if (Encoding.ASCII.GetString(bR.ReadBytes(2)) != "BP")
                throw new BitChatException("Invalid BitChatProfile data format.");

            byte version = bR.ReadByte();

            switch (version)
            {
                case 1:
                    #region version 1

                    //tracker client id
                    TrackerClientID localClientID = new TrackerClientID(bR);

                    //local cert store
                    if (bR.ReadByte() == 1)
                        _localCertStore = new CertificateStore(bR);

                    //bitchat local service end point
                    _localEP = new IPEndPoint(new IPAddress(bR.ReadBytes(bR.ReadByte())), bR.ReadInt32());

                    //default tracker urls
                    _trackerURIs = DefaultTrackerURIs;

                    break;

                    #endregion

                case 2:
                case 3:
                    #region version 2 & 3

                    //local cert store
                    if (bR.ReadByte() == 1)
                        _localCertStore = new CertificateStore(bR);

                    //bitchat local service end point
                    _localEP = new IPEndPoint(new IPAddress(bR.ReadBytes(bR.ReadByte())), bR.ReadInt32());

                    //download folder
                    _downloadFolder = Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadUInt16()));
                    if (_downloadFolder == null)
                        _downloadFolder = @"C:\";

                    //load tracker urls
                    _trackerURIs = new Uri[bR.ReadByte()];
                    for (int i = 0; i < _trackerURIs.Length; i++)
                        _trackerURIs[i] = new Uri(Encoding.UTF8.GetString(bR.ReadBytes(bR.ReadByte())));

                    //load bitchat info
                    _bitChatInfoList = new BitChatInfo[bR.ReadByte()];
                    for (int i = 0; i < _bitChatInfoList.Length; i++)
                        _bitChatInfoList[i] = new BitChatInfo(bR);

                    if (version > 2)
                    {
                        //check CertificateRevocationList
                        _checkCertificateRevocationList = bR.ReadBoolean();
                    }
                    else
                    {
                        _checkCertificateRevocationList = true;
                    }

                    //generic client data
                    int dataCount = bR.ReadInt32();
                    if (dataCount > 0)
                        _clientData = bR.ReadBytes(dataCount);

                    break;

                    #endregion

                default:
                    throw new BitChatException("BitChatProfile data version not supported.");
            }
        }
Ejemplo n.º 10
0
 private void storeDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
 {
     CookiesFile cookiesFile = CookiesFile.GetInstance();
     if (cookiesFile.StoreLocation != null)
     {
         fldBrowserStoreLocation.SelectedPath = cookiesFile.StoreLocation;
     }
     DialogResult result = fldBrowserStoreLocation.ShowDialog();
     if (result != DialogResult.Cancel)
     {
         certificateStore = CertificateStore<CodeSigningCertificate>.GetInstance(fldBrowserStoreLocation.SelectedPath);
         // also persist the setting in a file
         cookiesFile.WriteKeyValue(CookiesFile.key_StoreLocation, fldBrowserStoreLocation.SelectedPath);
     }
 }
Ejemplo n.º 11
0
        private void PopulateTreeView()
        {
            if (certificateStore == null)
            {
                try
                {
                    CookiesFile cookiesFile = CookiesFile.GetInstance();
                    if (cookiesFile.StoreLocation != null)
                    {
                        certificateStore = CertificateStore<CodeSigningCertificate>.GetInstance(cookiesFile.StoreLocation);
                    }
                }
                catch (Exception)
                {
                    certificateStore = CertificateStore<CodeSigningCertificate>.CurrentInstance;
                }
            }

            CodeSigningStoreBuilder builder = new CodeSigningStoreBuilder(certificateStore);
            builder.BuildStore();

            // Load the image list into the treeview if it isn't already present
            if(tvCertificateList.ImageList == null)
            {
                //Icon icon = certificateStore.certificateIcon;
                //ImageList imageList = new ImageList();
                //imageList.Images.Add(icon);
                //tvCertificateList.ImageList = imageList;
            }

            foreach (CodeSigningCertificate cert in certificateStore)
            {
                TreeNode node = new TreeNode(cert.Filename, 0, 0);
                tvCertificateList.Nodes.Add(node);
            }
        }