Ejemplo n.º 1
0
 public SslClient(string ip, int port, UserCertificate certificate = null, int bufferSize = 1024) : base(ip, port)
 {
     try
     {
         _bufferSize = bufferSize;
         if (certificate != null)
         {
             _certificate = certificate;
         }
         else
         {
             _certificate = new X509Certificate2();
         }
         _stream = new SslStream(GetStream(), false, ServerCertificateValidation, UserCertificateSelection);
         _stream.AuthenticateAsClient(ip);
     }
     catch (AuthenticationException err)
     {
         ErrorOnAuthentication();
     }
     catch (SocketException)
     {
         ErrorOnAuthentication();
     }
     catch (Win32Exception)
     {
         ErrorOnAuthentication();
     }
 }
Ejemplo n.º 2
0
        /// <param name="ack1SdIsReady">
        /// =true for SD in ACK2
        /// =false for SD in ACK1 (since the SessionDescription is not initialized yet)
        /// </param>
        internal byte[] Encrypt(ICryptoLibrary cryptoLibrary, InviteRequestPacket req, InviteAck1Packet ack1, InviteSession session,
                                bool ack1SdIsReady
                                )
        {
            BinaryProcedures.CreateBinaryWriter(out var ms, out var w);
            w.Write(Flags);
            UserCertificate.Encode(w, false);
            BinaryProcedures.EncodeIPEndPoint(w, DirectChannelEndPoint);
            NatBehaviour.Encode(w);
            DirectChannelToken32.Encode(w);
            w.Write((byte)SessionType);
            UserCertificateSignature.Encode(w);
            var bytesInLastBlock = (int)ms.Position % CryptoLibraries.AesBlockSize;

            if (bytesInLastBlock != 0)
            {
                var bytesRemainingTillFullAesBlock = CryptoLibraries.AesBlockSize - bytesInLastBlock;
                w.Write(cryptoLibrary.GetRandomBytes(bytesRemainingTillFullAesBlock));
            }
            var plainTextSdData = ms.ToArray();
            var encryptedSdData = new byte[plainTextSdData.Length];

            #region key, iv
            BinaryProcedures.CreateBinaryWriter(out var ms2, out var w2);
            req.GetSharedSignedFields(w2);
            ack1.GetSharedSignedFields(w2, ack1SdIsReady);
            var iv = cryptoLibrary.GetHashSHA256(ms2.ToArray()).Take(16).ToArray();
            ms2.Write(session.SharedInviteAckDhSecret, 0, session.SharedInviteAckDhSecret.Length);
            var aesKey = cryptoLibrary.GetHashSHA256(ms2.ToArray()); // here SHA256 is used as KDF, together with common fields from packets, including both ECDH public keys and timestamp
            #endregion

            cryptoLibrary.ProcessAesCbcBlocks(true, aesKey, iv, plainTextSdData, encryptedSdData);

            return(encryptedSdData);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 用户认证
        /// </summary>
        /// <param name="token">sessionId</param>
        /// <returns></returns>
        public static UserCertificate GetCertificate(string sessionKey)
        {
            try
            {
                //如果没有token直接显示未登陆
                if (string.IsNullOrEmpty(sessionKey))
                {
                    return(null);
                }
                UserCertificate cer = null;

                string cerJson = CallTheApi(GetCertificateUrl.FormatWith(sessionKey), "", PublicKey, SecretKey, "POST", (a, r) =>
                {
                    cer = (UserCertificate)a.TryParseEntity <UserCertificate>(r, "Passport",
                                                                              new ExcludePropertiesContractResolver(new List <string> {
                        "Id"
                    }));
                });
                //UserCertificate cer = JsonConvert.DeserializeObject<UserCertificate>(cerJson);
                return(cer != null ? cer : null);
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 4
0
        void SendMessage()
        {
            if (!LocalUser.SendOrEcho)
            {
                return;
            }

            // send msg (with autoRetry=true)   wait for completion
            var userCertificate1 = UserCertificate.GenerateKeyPairsAndSignAtSingleDevice(_userApp.DrpPeerEngine.CryptoLibrary, _userApp.UserId,
                                                                                         _userApp.UserRootPrivateKeys, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddHours(1));
            var sentText = $"echoTest_#{_sentCount}_from_{LocalUser.Name}_to_{RemoteUser.Name}_{_insecureRandom.Next()}";
            var sw       = Stopwatch.StartNew();

            OnSent();
            _userApp.LocalDrpPeer.BeginSendShortSingleMessage(userCertificate1, RemoteUser.RegistrationId, RemoteUser.UserId, sentText, TimeSpan.FromSeconds(60),
                                                              (exc) =>
            {
                if (exc != null)
                {
                    _visionChannel.EmitListOfPeers(_userApp.DrpPeerEngine.Configuration.VisionChannelSourceId, DrpTesterVisionChannelModuleName, AttentionLevel.strongPain,
                                                   $"could not send message: {exc}");

                    if (!ContinueOnFailed())
                    {
                        return;
                    }
                    SendMessage();
                }
                else
                {
                    BeginVerifyReceivedEchoedMessage(sentText, sw, Stopwatch.StartNew());
                }
            });
        }
Ejemplo n.º 5
0
        public async Task SendInvite_AtoX_Async()
        {
            _xUser.ContactBookUsersByRegId.Add(_aLocalDrpPeer.Configuration.LocalPeerRegistrationId, _aUser.UserId);

            var aUserCertificate = UserCertificate.GenerateKeyPairsAndSignAtSingleDevice(_a.CryptoLibrary, _aUser.UserId, _aUser.UserRootPrivateKeys, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddHours(1));


            var message = $"test Dcomms message {new Random().Next()}";

            _a.Configuration.VisionChannel.Emit(_a.Configuration.VisionChannelSourceId, DrpTesterVisionChannelModuleName, AttentionLevel.guiActivity,
                                                $"sending message: {message}");

            _aLocalDrpPeer.BeginSendShortSingleMessage(aUserCertificate, _xLocalDrpPeer.Configuration.LocalPeerRegistrationId, _xUser.UserId, message, null,
                                                       (exc) =>
            {
                if (exc == null)
                {
                    _visionChannel.Emit(_a.Configuration.VisionChannelSourceId, DrpTesterVisionChannelModuleName, AttentionLevel.guiActivity,
                                        $"message was sent successfully");
                }
                else
                {
                    _visionChannel.Emit(_a.Configuration.VisionChannelSourceId, DrpTesterVisionChannelModuleName, AttentionLevel.mediumPain,
                                        $"message was not sent successfully");
                }
            });
        }
Ejemplo n.º 6
0
        public void BeginSendShortSingleMessage(UserCertificate requesterUserCertificate, RegistrationId responderRegistrationId, UserId responderUserId,
                                                string messageText, TimeSpan?retryOnFailureUntilThisTimeout, Action <Exception> cb)
        {
            requesterUserCertificate.AssertHasPrivateKey();
            Engine.EngineThreadQueue.Enqueue(async() =>
            {
                var sw1 = Stopwatch.StartNew();

                _retry:
                Logger logger = null;
                try
                {
                    var sw2     = Stopwatch.StartNew();
                    var session = await SendInviteAsync(requesterUserCertificate, responderRegistrationId, responderUserId, SessionType.asyncShortSingleMessage, null, (logger2) =>
                    {
                        logger = logger2;
                        if (Engine.Configuration.SandboxModeOnly_EnableInsecureLogs)
                        {
                            if (logger.WriteToLog_detail_enabled)
                            {
                                logger.WriteToLog_detail($"creating an invite session to send a message '{messageText}'");
                            }
                        }
                    });
                    if (logger.WriteToLog_detail_enabled)
                    {
                        logger.WriteToLog_detail($"invite session is ready to set up direct channel and send a message");
                    }
                    try
                    {
                        if (logger.WriteToLog_detail_enabled)
                        {
                            logger.WriteToLog_detail($"remote peer accepted invite session in {(int)sw2.Elapsed.TotalMilliseconds}ms: {session.RemoteSessionDescription}");
                        }

                        await session.SetupAEkeysAsync();

                        await session.SendShortSingleMessageAsync(messageText, requesterUserCertificate);
                    }
                    finally
                    {
                        session.Dispose();
                    }

                    cb?.Invoke(null);
                }
                catch (Exception exc)
                {
                    var tryAgain = retryOnFailureUntilThisTimeout.HasValue && sw1.Elapsed < retryOnFailureUntilThisTimeout.Value;
                    logger?.WriteToLog_mediumPain($"sending INVITE failed (tryAgain={tryAgain}): {exc}");
                    logger?.WriteToLog_mediumPain_EmitListOfPeers($"sending INVITE failed (tryAgain={tryAgain}): {exc}");
                    if (tryAgain)
                    {
                        logger?.WriteToLog_higherLevelDetail($"trying again to send message: sw1={sw1.Elapsed.TotalSeconds}s < retryOnFailureUntilThisTimeout={retryOnFailureUntilThisTimeout.Value.TotalSeconds}s");
                        goto _retry;
                    }
                    cb?.Invoke(exc);
                }
            }, "BeginSendShortSingleMessage6342");
        }
Ejemplo n.º 7
0
        public List <User> GetUsers(bool local)
        {
            var query = _db_main.Table <User>();

            if (local)
            {
                query = query.Where(x => x.OwnerLocalUserId == 0);
            }
            else
            {
                query = query.Where(x => x.OwnerLocalUserId != 0);
            }
            var users = query.ToList();

            foreach (var u in users)
            {
                try
                {
                    u.UserID  = UserId.Decode(DecryptAndVerify(u.UserID_encrypted, u.UserID_hmac, u.Id, EncryptedFieldIds.User_UserID));
                    u.AliasID = BinaryProcedures.DecodeString2UTF8(DecryptAndVerify(u.AliasID_encrypted, u.AliasID_hmac, u.Id, EncryptedFieldIds.User_AliasID));
                    u.LocalUserCertificate = UserCertificate.Decode(DecryptAndVerify(u.LocalUserCertificate_encrypted, u.LocalUserCertificate_hmac, u.Id, EncryptedFieldIds.User_LocalUserCertificate));
                    u.Metadata             = UserMetadata.Decode(DecryptAndVerify(u.Metadata_encrypted, u.Metadata_hmac, u.Id, EncryptedFieldIds.User_Metadata));
                    WriteToLog_deepDetail($"decrypted user '{u.AliasID}'");
                }
                catch (Exception exc)
                {
                    HandleException($"can not decrypt/verify user ID={u.UserID}: ", exc);
                }
            }
            return(users);
            //  var user = db.Get<UserId>(5); // primary key id of 5
        }
Ejemplo n.º 8
0
        /// <returns>remote IKE1 data</returns>
        internal async Task <Ike1Data> Ike1Async_AtInviteResponder(UserCertificate localUserCertificateWithPrivateKeys, Ike1Data localIke1Data, UserCertificate remoteUserCertificate)
        {
            var remoteIke1Data = await ReceiveIke1DataAsync(remoteUserCertificate);

            await SendIke1DataAsync(localUserCertificateWithPrivateKeys, localIke1Data);

            return(remoteIke1Data);
        }
Ejemplo n.º 9
0
        protected override void RemoveCertificate(UserCertificate item)
        {
            var removed =
                this.CertificatesCollection.SingleOrDefault(
                    x => x.Thumbprint == item.Thumbprint && x.Subject == item.Subject);

            this.CertificatesCollection.Remove(removed);
        }
Ejemplo n.º 10
0
            public async Task WhenPackageSupportsButDoesNotRequireSigning_AcceptsUnsignedPackages()
            {
                // Arrange
                var user1 = new User()
                {
                    Key = 1
                };
                var user2 = new User()
                {
                    Key = 2
                };
                var packageRegistration = new PackageRegistration()
                {
                    Key = 3,
                    Id  = TestResources.UnsignedPackageId
                };
                var certificate = new Certificate()
                {
                    Key        = 4,
                    Thumbprint = TestResources.Leaf1Thumbprint
                };
                var userCertificate = new UserCertificate()
                {
                    Key            = 5,
                    CertificateKey = certificate.Key,
                    Certificate    = certificate,
                    UserKey        = user1.Key,
                    User           = user1
                };

                user1.UserCertificates.Add(userCertificate);
                certificate.UserCertificates.Add(userCertificate);

                packageRegistration.Owners.Add(user1);
                packageRegistration.Owners.Add(user2);

                _packageStream = TestResources.GetResourceStream(TestResources.UnsignedPackage);
                _corePackageService
                .Setup(x => x.FindPackageRegistrationById(It.Is <string>(id => id == _message.PackageId)))
                .Returns(packageRegistration);
                _message = new SignatureValidationMessage(
                    TestResources.UnsignedPackageId,
                    TestResources.UnsignedPackageVersion,
                    new Uri($"https://unit.test/{TestResources.UnsignedPackage.ToLowerInvariant()}"),
                    Guid.NewGuid());

                // Act
                var result = await _target.ValidateAsync(
                    _packageKey,
                    _packageStream,
                    _message,
                    _cancellationToken);

                // Assert
                Validate(result, ValidationStatus.Succeeded, PackageSigningStatus.Unsigned);
                Assert.Empty(result.Issues);
            }
Ejemplo n.º 11
0
        public void SaveUserContext(string userId, string username)
        {
            var db    = DbConHelper.NewDbCon();
            var model = new UserCertificate();

            model.UserId   = userId;
            model.UserName = username;
            db.Insert(model);
        }
Ejemplo n.º 12
0
        void BeginTestMessage3(MessagesTest test, DrpTesterPeerApp peer1, DrpTesterPeerApp peer2, Stopwatch sw, string text)
        {
            var userCertificate1 = UserCertificate.GenerateKeyPairsAndSignAtSingleDevice(peer1.DrpPeerEngine.CryptoLibrary, peer1.UserId, peer1.UserRootPrivateKeys, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddHours(1));

            peer1.LocalDrpPeer.BeginSendShortSingleMessage(userCertificate1, peer2.LocalDrpPeer.Configuration.LocalPeerRegistrationId, peer2.UserId, text, TimeSpan.FromSeconds(60), (exc) =>
            {
                BeginVerifyReceivedMessage(test, peer1, peer2, text, sw, Stopwatch.StartNew());
            });
        }
Ejemplo n.º 13
0
        protected override void AddCertificate(UserCertificate item)
        {
            var userCertificate = new NhUserCertificate();

            userCertificate.GetType().GetProperty("Thumbprint").SetValue(userCertificate, item.Thumbprint);
            userCertificate.GetType().GetProperty("Subject").SetValue(userCertificate, item.Subject);
            userCertificate.GetType().GetProperty("Account").SetValue(userCertificate, this);
            this.CertificatesCollection.Add(userCertificate);
        }
        public async Task <ActionResult> StarteSealTspFlow([FromQuery(Name = "env_slt")] string envSlt)
        {
            // First step is to get a token with the retrieve friom the query param
            SignatureOAuthUserToken signatureOAuthUserToken;

            try
            {
                signatureOAuthUserToken = await DocuSignService.GetBearerTokenFromEnvSltAsync(_httpClientFactory, _dsConfig, envSlt);
            }
            catch (Exception e)
            {
                // If you ending up in this case, make sure you clientId/clientSecret are good
                // Also make sure you are hitting the right environement
                return(BadRequest(e));
            }


            // Initialize DocuSign ApiClient
            var apiClient = new eSign.Client.ApiClient(signatureOAuthUserToken.user_api + "/restapi");

            apiClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + signatureOAuthUserToken.access_token);

            DocuSign.eSign.Api.SignatureApi signatureApi = new eSign.Api.SignatureApi(apiClient);

            // UserInfo
            var userInfoResult = signatureApi.UserInfo();

            UserCertificate userCertificate = new UserCertificate(userInfoResult.User.DisplayName, userInfoResult.User.Email, userInfoResult.Language.ToUpper(), "DocuSign");

            var SignHashSessionInfoResult = signatureApi.SignHashSessionInfo(new eSign.Model.SignSessionInfoRequest(Convert.ToBase64String(userCertificate.CertContainer.Certificate.GetEncoded())));

            if (SignHashSessionInfoResult.Documents[0] == null || SignHashSessionInfoResult.Documents[0].RemainingSignatures == 0L)
            {
                return(Ok("Nothing to sign"));
            }

            byte[] hashBytes     = System.Convert.FromBase64String(SignHashSessionInfoResult.Documents[0].Data);
            byte[] signedCmsData = SignatureProvider.SignatureProvider.Sign(hashBytes, userCertificate);

            eSign.Model.DocumentUpdateInfo docInfo = new eSign.Model.DocumentUpdateInfo()
            {
                DocumentId   = SignHashSessionInfoResult.Documents[0].DocumentId,
                Data         = Convert.ToBase64String(signedCmsData),
                ReturnFormat = "CMS"
            };
            var CompleteSignHashResult = signatureApi.CompleteSignHash(new eSign.Model.CompleteSignRequest()
            {
                DocumentUpdateInfos = new List <eSign.Model.DocumentUpdateInfo> {
                    docInfo
                }
            });

            ViewBag.CompleteResult = CompleteSignHashResult;

            return(Redirect(CompleteSignHashResult.RedirectionUrl));
        }
Ejemplo n.º 15
0
        private void AddCertificate(UserCertificate cert)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action <UserCertificate>(AddCertificate), new object[] { cert });
                return;
            }

            listCert.Add(cert);
            listBox1.Items.Add("ID: " + cert.Id + " Public Key: " + cert.publicKey.n + cert.publicKey.e);
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Delete([FromRoute] long id)
        {
            var userCertificate = new UserCertificate()
            {
                Id = id
            };

            _context.Remove(userCertificate);
            await _context.SaveChangesAsync();

            return(Ok());
        }
Ejemplo n.º 17
0
        private Package ProcessMessage(Package pck)
        {
            //Console.WriteLine("#Certifiate Client: ");
            //pck.Print();

            Package response = new Package();

            switch (pck.GetHeader("Command"))
            {
            case "Register":
                BigInteger      n        = BigInteger.Parse(pck.GetHeader("Public Key n"));
                BigInteger      e        = BigInteger.Parse(pck.GetHeader("Public Key e"));
                UserCertificate newCertf = new UserCertificate(lastId++);
                newCertf.publicKey = new RSAKey(n, e);
                newCertf.timestamp = GetTimestamp(new DateTime());
                AddCertificate(newCertf);
                response.SetHeader("Public Key n", rsa.Key.n.ToString());
                response.SetHeader("Public Key e", rsa.Key.e.ToString());
                response.SetContent(newCertf.ToString());
                break;

            case "Verify":
                int index = -1;
                for (int i = 0; i < listCert.Count; i++)
                {
                    if (listCert[i].ToString().Equals(pck.GetHeader("Certificate")))
                    {
                        index = 1;
                    }
                }

                if (index != -1)
                {
                    response.SetContent("TRUE");
                }
                else
                {
                    response.SetContent("FALSE");
                }

                break;
            }

            if (response.GetContent() != "")
            {
                string enc = rsa.encrypt(response.GetContent(), rsa.Key.d, rsa.Key.n);
                // string dec = rsa.decrypt(enc, rsa.Key.e, rsa.Key.n);
                // Console.WriteLine(enc + " => " +dec);
                response.SetContent(enc);
            }

            return(response);
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> RegisterCertificateCallback([FromBody] SmartCardAuthorizationResponse smartCardAuthorizationResponse)
        {
            var sub = HttpContext.User.Claims.FirstOrDefault(x => x.Type == "sub")?.Value;

            if (string.IsNullOrEmpty(sub))
            {
                return(Json(new { success = false }));
            }

            var user = await _users.FindByIdAsync(sub);

            if (smartCardAuthorizationResponse == null || string.IsNullOrEmpty(smartCardAuthorizationResponse.Certificate) || string.IsNullOrEmpty(smartCardAuthorizationResponse.Token))
            {
                return(Json(new { success = false }));
            }

            var certificate = CertificateUtilities.GetAndValidateCertificate(smartCardAuthorizationResponse.Certificate);

            if (certificate == null)
            {
                return(Json(new { success = false }));
            }

            if (_authContext.UserCertificates.FirstOrDefault(x => x.Thumbprint == certificate.Thumbprint) != null)
            {
                return(Json(new { success = false }));
            }

            var payload      = HttpContext.Session.GetString("certificateRegister.challenge");
            var verifyResult = JwtUtils.ValidateJWT(
                certificate,
                smartCardAuthorizationResponse.Token,
                smartCardAuthorizationResponse.Algorithm,
                payload);

            if (verifyResult)
            {
                var dbuser   = _authContext.Users.First(u => u.Id == user.Id);
                var userCert = new UserCertificate()
                {
                    Certificate      = Convert.ToBase64String(certificate.RawData),
                    Thumbprint       = certificate.Thumbprint,
                    User             = dbuser,
                    RegistrationDate = DateTime.Now,
                    Subject          = certificate.Subject
                };
                _authContext.UserCertificates.Add(userCert);
                _authContext.SaveChanges();
                return(Json(new { success = true }));
            }
            return(Json(new { success = false }));
        }
 public int Insert(UserCertificate uc)
 {
     try
     {
         db.UserCertificates.Add(uc);
         db.SaveChanges();
         return(uc.ID);
     }
     catch
     {
         return(-1);
     }
 }
Ejemplo n.º 20
0
        private async void connectButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            DisableAll();
            var statusLabel = new ToolStripStatusLabel("Connecting");

            statusBar.Items.Add(statusLabel);
            if (_connected)
            {
                DisconnectUser();
            }
            try
            {
                _certificate = identitiesListBox.SelectedItem as UserCertificate;
                if (await ServerTransaction.Connect(_certificate))
                {
                    await ConnectUser();

                    var login = _certificate.CommonName;
                    loginLabel.Text = login;

                    var message = string.Format("Successfull logged as {0}", login);
                    MessageBox.Show(message, "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    _currentUser = _certificate;
                }
                else
                {
                    MessageBox.Show("Failed to authenticate", "Login failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (AuthenticationError)
            {
                MessageBox.Show("Failed to authenticate", "Login failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (CloudException cloud)
            {
                MessageBox.Show(cloud.Message, "Cloud problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception)
            {
                MessageBox.Show("Unexcepted error occured. Click OK to contiune", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            EnableIdentity();
            if (_connected)
            {
                EnableGroups();
            }
            statusBar.Items.Remove(statusLabel);
            Cursor = Cursors.Arrow;
        }
Ejemplo n.º 21
0
        public async Task OnGetAsync(string authorizationCode)
        {
            // First step is to get a token with the retrieve friom the query param
            try
            {
                SignatureOAuthUserToken = await DocuSignService.GetBearerTokenFromCodeAsync(_httpClientFactory, _dsConfig, authorizationCode);
            }
            catch (Exception e)
            {
                // If you ending up in this case, make sure you clientId/clientSecret are good
                // Also make sure you are hitting the right environement
                ViewData["Error"] = e;
            }


            // Initialize DocuSign ApiClient
            var apiClient = new eSign.Client.ApiClient(SignatureOAuthUserToken.user_api + "/restapi");

            apiClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + SignatureOAuthUserToken.access_token);

            DocuSign.eSign.Api.SignatureApi signatureApi = new eSign.Api.SignatureApi(apiClient);

            // Get UserInfo
            var userInfoResponse = signatureApi.UserInfo();

            ViewData["UserInfo"] = JsonConvert.SerializeObject(userInfoResponse);
            UserCertificate userCertificate = new UserCertificate(UserInfoResponse.User.DisplayName, UserInfoResponse.User.Email, UserInfoResponse.Language.ToUpper(), "DocuSign");


            //var SignHashSessionInfoResult = signatureApi.SignHashSessionInfo(new eSign.Model.SignSessionInfoRequest(Convert.ToBase64String(userCertificate.CertContainer.Certificate.GetEncoded())));

            //if (SignHashSessionInfoResult.Documents[0] == null || SignHashSessionInfoResult.Documents[0].RemainingSignatures == "0")
            //{
            //    return Ok("Nothing to sign");
            //}

            //byte[] hashBytes = System.Convert.FromBase64String(SignHashSessionInfoResult.Documents[0].Data);
            //byte[] signedCmsData = SignatureProvider.SignatureProvider.Sign(hashBytes, userCertificate);

            //eSign.Model.DocumentUpdateInfo docInfo = new eSign.Model.DocumentUpdateInfo()
            //{
            //    DocumentId = SignHashSessionInfoResult.Documents[0].DocumentId,
            //    Data = Convert.ToBase64String(signedCmsData),
            //    ReturnFormat = "CMS"
            //};
            //var CompleteSignHashResult = signatureApi.CompleteSignHash(new eSign.Model.CompleteSignRequest() { DocumentUpdateInfos = new List<eSign.Model.DocumentUpdateInfo> { docInfo } });

            //ViewBag.CompleteResult = CompleteSignHashResult;

            //return Redirect(CompleteSignHashResult.RedirectionUrl);
        }
Ejemplo n.º 22
0
        public void AddLocalUser(string aliasId)
        {
            try
            {
                UserRootPrivateKeys.CreateUserId(1, 1, TimeSpan.FromDays(365 * 3 + 10), _drpPeerEngine.CryptoLibrary, out var userRootPrivateKeys, out var userId);
                var userCertificateWithPrivateKey = UserCertificate.GenerateKeyPairsAndSignAtSingleDevice(_drpPeerEngine.CryptoLibrary, userId, userRootPrivateKeys, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddYears(3));
                userCertificateWithPrivateKey.AssertHasPrivateKey();
                userCertificateWithPrivateKey.AssertIsValidNow(_drpPeerEngine.CryptoLibrary, userId, _drpPeerEngine.DateTimeNowUtc);

                var u = new User
                {
                    AliasID              = aliasId,
                    UserID               = userId,
                    OwnerLocalUserId     = 0,
                    LocalUserCertificate = userCertificateWithPrivateKey,
                };
                _db.InsertUser(u);

                var ruk = new RootUserKeys
                {
                    UserId = u.Id,
                    UserRootPrivateKeys = userRootPrivateKeys
                };
                _db.InsertRootUserKeys(ruk);

                RegistrationId.CreateNew(_drpPeerEngine.CryptoLibrary, out var regPrivateKey, out var registrationId);

                var regId = new UserRegistrationID
                {
                    UserId                 = u.Id,
                    RegistrationId         = registrationId,
                    RegistrationPrivateKey = regPrivateKey
                };
                _db.InsertUserRegistrationID(regId);

                var newLocalUser = new LocalUser
                {
                    User                = u,
                    RootUserKeys        = ruk,
                    UserRegistrationIDs = new List <UserRegistrationID> {
                        regId
                    }
                };
                LocalUsers.Add(u.Id, newLocalUser);
                newLocalUser.CreateLocalDrpPeers(this);
            }
            catch (Exception exc)
            {
                HandleException("error when adding new local user: ", exc);
            }
        }
Ejemplo n.º 23
0
        private async void getCertificatesButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            DisableAll();
            var statusLabel = new ToolStripStatusLabel("Downloadig certificates");

            statusBar.Items.Add(statusLabel);
            var selectedUsers = usersListBox.SelectedItems;

            if (selectedUsers.Count > 0)
            {
                try
                {
                    var certificates = new List <string>();
                    foreach (User user in selectedUsers)
                    {
                        var tempCertificate = Path.GetTempFileName();
                        statusLabel.Text = string.Format("Downloading certificate ({0})", user.CommonName);
                        await _cloud.DownloadCertificateAsync(tempCertificate, user);

                        certificates.Add(tempCertificate);
                    }
                    var certificatesStore = new X509Store(StoreName.AddressBook, StoreLocation.CurrentUser);
                    certificatesStore.Open(OpenFlags.ReadWrite);
                    foreach (var certificate in certificates)
                    {
                        var cert = new UserCertificate(certificate);
                        statusLabel.Text = string.Format("Adding certificate to user store ({0})", cert.CommonName);
                        certificatesStore.Add(cert);
                        File.Delete(certificate);
                    }
                    certificatesStore.Close();
                }
                catch (CloudException cloud)
                {
                    MessageBox.Show(cloud.Message, "Cloud problem", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                catch (Exception)
                {
                    MessageBox.Show("Unexcepted error occured. Click OK to contiune", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("Select users first", "Select users", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            EnableAll();
            statusBar.Items.Remove(statusLabel);
            Cursor = Cursors.Arrow;
        }
            private void ActivateCertificate(User user)
            {
                var userCertificate = new UserCertificate()
                {
                    Key            = _certificate.UserCertificates.Count() + 1,
                    UserKey        = user.Key,
                    User           = user,
                    CertificateKey = _certificate.Key,
                    Certificate    = _certificate
                };

                _certificate.UserCertificates.Add(userCertificate);
                user.UserCertificates.Add(userCertificate);
            }
Ejemplo n.º 25
0
        /// <returns>remote IKE1 data: user ID, reg IDs</returns>
        internal async Task <Ike1Data> Ike1Async_AtInviteRequester(UserCertificate localUserCertificateWithPrivateKeys, Ike1Data localIke1Data, UserCertificate remoteUserCertificate)
        {
            if (!DerivedDirectChannelSharedDhSecretsAE)
            {
                throw new InvalidOperationException("DerivedDirectChannelSharedDhSecretsAE = false");
            }
            if (Logger.WriteToLog_detail_enabled)
            {
                Logger.WriteToLog_detail(">> InviteSession.Ike1Async_AtInviteRequester()");
            }

            await SendIke1DataAsync(localUserCertificateWithPrivateKeys, localIke1Data);

            return(await ReceiveIke1DataAsync(remoteUserCertificate));
        }
Ejemplo n.º 26
0
        public UserCertificate GetUserCertificate(string uid, string cid)
        {
            UserCertificate cert = _context.UserCertificates.FirstOrDefault(cert => cert.CertId == cid && cert.UserId == uid);

            if (cert == null)
            {
                return(cert);
            }

            X509Certificate2 xCert = new X509Certificate2(cert.RawCertBody);

            Log.Information("Verifying obtained cert...");
            _verify_certificate(xCert);
            return(cert);
        }
Ejemplo n.º 27
0
 public DrpTesterPeerApp(DrpPeerEngine drpPeerEngine, LocalDrpPeerConfiguration drpPeerRegistrationConfiguration, UserRootPrivateKeys userRootPrivateKeys = null, UserId userId = null)
 {
     DrpPeerRegistrationConfiguration = drpPeerRegistrationConfiguration;
     DrpPeerEngine = drpPeerEngine;
     if (userRootPrivateKeys == null || userId == null)
     {
         UserRootPrivateKeys.CreateUserId(3, 2, TimeSpan.FromDays(367), DrpPeerEngine.CryptoLibrary, out UserRootPrivateKeys, out UserId);
     }
     else
     {
         UserId = userId;
         UserRootPrivateKeys = userRootPrivateKeys;
     }
     UserCertificateWithPrivateKey = UserCertificate.GenerateKeyPairsAndSignAtSingleDevice(DrpPeerEngine.CryptoLibrary, UserId, UserRootPrivateKeys, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddYears(1));
 }
Ejemplo n.º 28
0
 public async static Task <bool> Connect(UserCertificate certificate)
 {
     try
     {
         using (SslClient stream = new SslClient(_configuration.IP, _configuration.Port, certificate))
         {
             await stream.SendStringAsync("connect");
             await Authenticate(stream, new User(certificate));
         }
     }
     catch (AuthenticationError error)
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 29
0
        void BeginTestInvites(InvitesTest test, Action cb = null)
        {
            var peer1 = test.Peers[_inviteTestsCounter++ % test.Peers.Count];

_retry:
            var peer2 = test.Peers[_rnd.Next(test.Peers.Count)];

            if (peer1 == peer2)
            {
                goto _retry;
            }

            EmitAllPeers(AttentionLevel.guiActivity, $"testing message from {peer1} to {peer2} ({test.counter}/{test.MaxCount}) {DateTime.Now}");

            var userCertificate1 = UserCertificate.GenerateKeyPairsAndSignAtSingleDevice(peer1.DrpPeerEngine.CryptoLibrary, peer1.UserId, peer1.UserRootPrivateKeys, DateTime.UtcNow.AddHours(-1), DateTime.UtcNow.AddHours(1));

            var text = $"test{_rnd.Next()}-{_rnd.Next()}_from_{peer1}_to_{peer2}";

            peer1.LocalDrpPeer.BeginSendShortSingleMessage(userCertificate1, peer2.LocalDrpPeer.Configuration.LocalPeerRegistrationId, peer2.UserId, text, null, (exc) =>
            {
                test.counter++;

                if (peer2.LatestReceivedTextMessage == text)
                {
                    test.successfulCount++;
                    _visionChannel.Emit(peer1.DrpPeerEngine.Configuration.VisionChannelSourceId, DrpTesterVisionChannelModuleName,
                                        AttentionLevel.guiActivity, $"successfully tested message from {peer1} to {peer2}. success rate = {(double)test.successfulCount * 100 / test.counter}% ({test.successfulCount}/{test.counter})");
                }
                else
                {
                    EmitAllPeers(AttentionLevel.mediumPain, $"test message failed from {peer1} to {peer2}: received '{peer2.LatestReceivedTextMessage}', expected '{text}");
                }

                if (test.counter < test.MaxCount)
                {
                    BeginTestInvites(test, cb);
                }
                else
                {
                    var successRatePercents = (double)test.successfulCount * 100 / test.counter;
                    var level = successRatePercents == 100 ? AttentionLevel.guiActivity : (successRatePercents > 99 ? AttentionLevel.lightPain : AttentionLevel.mediumPain);
                    _visionChannel.Emit(peer1.DrpPeerEngine.Configuration.VisionChannelSourceId, DrpTesterVisionChannelModuleName,
                                        level, $"messages test is complete: success rate = {successRatePercents}%");
                    cb?.Invoke();
                }
            });
        }
Ejemplo n.º 30
0
        public void RevokeUserCertificate(string uid, string cid)
        {
            //get root cert
            X509Certificate rootCert = DotNetUtilities.FromX509Certificate(getRootCert());

            //get user cert to be revoked
            UserCertificate userCert     = GetUserCertificate(uid, cid);
            X509Certificate certToRevoke = new X509CertificateParser().ReadCertificate(userCert.RawCertBody);

            //parse the last CRL
            X509CrlParser crlParser  = new X509CrlParser();
            FileStream    fileStream = File.Open(_configuration["CrlPath"], FileMode.Open);
            X509Crl       rootCrl    = crlParser.ReadCrl(fileStream);

            fileStream.Close();

            //extract the CRL number
            Asn1OctetString prevCrlNum    = rootCrl.GetExtensionValue(X509Extensions.CrlNumber);
            Asn1Object      obj           = X509ExtensionUtilities.FromExtensionValue(prevCrlNum);
            BigInteger      prevCrlNumVal = DerInteger.GetInstance(obj).PositiveValue;

            //generate new CRL
            X509V2CrlGenerator crlGenerator = new X509V2CrlGenerator();

            crlGenerator.SetIssuerDN(rootCert.SubjectDN);
            crlGenerator.SetThisUpdate(DateTime.UtcNow);
            crlGenerator.SetNextUpdate(DateTime.UtcNow.AddDays(10));
            crlGenerator.AddCrl(rootCrl); //add the old CRL entries
            //add the newly revoked certificates
            crlGenerator.AddCrlEntry(certToRevoke.SerialNumber, DateTime.UtcNow, CrlReason.PrivilegeWithdrawn);
            //increment CRL Number by 1
            crlGenerator.AddExtension("2.5.29.20", false, new CrlNumber(prevCrlNumVal.Add(BigInteger.One)));
            AsymmetricKeyParameter bouncyCastlePrivateKey = PrivateKeyFactory.CreateKey(getRootPrivateKey().ExportPkcs8PrivateKey());

            var     sigFactory = new Asn1SignatureFactory("SHA256WITHECDSA", bouncyCastlePrivateKey);
            X509Crl nextCrl    = crlGenerator.Generate(sigFactory);

            // writePem(_configuration["CrlOldPath"], rootCrl); // write old CRL as backup
            writePem(_configuration["CrlPath"], nextCrl); //write new CRL

            // sanity check
            nextCrl.Verify(rootCert.GetPublicKey());

            userCert.Revoked = true;
            _context.UserCertificates.Update(userCert);
        }
 protected internal override void RemoveCertificate(UserCertificate item)
 {
     UserCertificateCollection.Remove(item);
 }
 protected internal override void AddCertificate(UserCertificate item)
 {
     UserCertificateCollection.Add(item);
 }
 protected override void AddCertificate(UserCertificate item)
 {
     var userCertificate = new NhUserCertificate();
     userCertificate.GetType().GetProperty("Thumbprint").SetValue(userCertificate, item.Thumbprint);
     userCertificate.GetType().GetProperty("Subject").SetValue(userCertificate, item.Subject);
     userCertificate.GetType().GetProperty("Account").SetValue(userCertificate, this);
     this.CertificatesCollection.Add(userCertificate);
 }
 protected override void RemoveCertificate(UserCertificate item)
 {
     var removed =
         this.CertificatesCollection.SingleOrDefault(
             x => x.Thumbprint == item.Thumbprint && x.Subject == item.Subject);
     this.CertificatesCollection.Remove(removed);
 }
 protected internal override void AddCertificate(UserCertificate item)
 {
     UserCertificateCollection.Add(new RelationalUserCertificate { UserAccountID = this.ID, Thumbprint = item.Thumbprint, Subject = item.Subject });
 }