private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor)
 {
     byte[] plain = new byte[16384];
     byte[] cipher = new byte[plain.Length + 16];
     byte[] plain2 = new byte[plain.Length + 16];
     int outLen = 0;
     int outLen2 = 0;
     var random = new Random();
     random.NextBytes(plain);
     encryptor.Encrypt(plain, plain.Length, cipher, out outLen);
     decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
     Assert.AreEqual(plain.Length, outLen2);
     for (int j = 0; j < plain.Length; j++)
     {
         Assert.AreEqual(plain[j], plain2[j]);
     }
     encryptor.Encrypt(plain, 1000, cipher, out outLen);
     decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
     Assert.AreEqual(1000, outLen2);
     for (int j = 0; j < outLen2; j++)
     {
         Assert.AreEqual(plain[j], plain2[j]);
     }
     encryptor.Encrypt(plain, 12333, cipher, out outLen);
     decryptor.Decrypt(cipher, outLen, plain2, out outLen2);
     Assert.AreEqual(12333, outLen2);
     for (int j = 0; j < outLen2; j++)
     {
         Assert.AreEqual(plain[j], plain2[j]);
     }
 }
        public static string EncryptLargeBytesToBase64String(IEncryptor encryptor, byte[] cfgData)
        {
            var       cfgEncrypt = new byte[cfgData.Length + 128];
            var       dataLen    = 0;
            const int bufferSize = 32768;
            var       input      = new byte[bufferSize];
            var       output     = new byte[bufferSize + 128];

            for (var startPos = 0; startPos < cfgData.Length; startPos += bufferSize)
            {
                var len = Math.Min(cfgData.Length - startPos, bufferSize);
                Buffer.BlockCopy(cfgData, startPos, input, 0, len);
                encryptor.Encrypt(input, len, output, out var outLen);
                Buffer.BlockCopy(output, 0, cfgEncrypt, dataLen, outLen);
                dataLen += outLen;
            }

            return(Convert.ToBase64String(cfgEncrypt, 0, dataLen));
        }
Exemple #3
0
        private async Task TestEncryptDecrypt(IEncryptor encr, Stream input, string inputData)
        {
            using (var encrOutput = new MemoryStream())
            {
                await encr.Encrypt(input, encrOutput);

                Assert.AreNotEqual(0, encrOutput.Length);
                Assert.IsTrue(encr.Policy.IsReadOnly);

                using (var decrOutput = new MemoryStream())
                {
                    await encr.Decrypt(encrOutput, decrOutput);

                    var decrResult = await decrOutput.ReadStringAsync();

                    Assert.AreEqual(inputData, decrResult);
                }
            }
        }
Exemple #4
0
        private void PipeConnectionReceiveCallback(IAsyncResult ar)
        {
            if (closed)
            {
                return;
            }
            try
            {
                int bytesRead = connection.EndReceive(ar);
                totalWrite += bytesRead;

                if (bytesRead > 0)
                {
                    int bytesToSend;
                    lock (encryptionLock)
                    {
                        if (closed)
                        {
                            return;
                        }
                        encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
                    }
                    remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);

                    IStrategy strategy = controller.GetCurrentStrategy();
                    if (strategy != null)
                    {
                        strategy.UpdateLastWrite(this.server);
                    }
                }
                else
                {
                    remote.Shutdown(SocketShutdown.Send);
                    remoteShutdown = true;
                    CheckClose();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                this.Close();
            }
        }
Exemple #5
0
        /// <summary>
        ///     Authenticates the specified user.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public async Task Consume(ConsumeContext <IAuthenticateUser> context)
        {
            var checkResult = await _checkCredentialsRequest.Request(new CheckCredentials(context.Message.UserName, context.Message.Password));

            if (!checkResult.Valid)
            {
                await context.RespondAsync(AuthenticateUserResult.Failed());

                return;
            }

            var user  = checkResult.User;
            var roles = new List <string>();

            // select delegated privileges
            var delegatedRights = _databaseContext.DelegatedRights.Filter(x => x.Grantee == user.UserName);
            var onBehalfOf      = delegatedRights.Select(x => x.Grantor).ToArray();


            // add manager role
            if (user.IsManager || onBehalfOf.Length > 0)
            {
                roles.Add(WellKnownRoles.Manager);
            }

            /* IMPORTANT NOTE:
             * This is a temporary solution. User group name cannot be hardcoded.
             * We should provide a feature that allows to map User Groups to the application roles.
             * But this is postponded, because of time limit.
             */
            var userGroups = user.Groups;

            if (userGroups.Any(x => x.DisplayName == "Access Control Clients"))
            {
                roles.Add(WellKnownRoles.ClientService);
            }

            // create a ticket
            var ticket          = new Ticket(user, roles.ToArray(), onBehalfOf);
            var encryptedTicket = _encryptor.Encrypt(ticket);
            await context.RespondAsync(new AuthenticateUserResult(true, encryptedTicket, user));
        }
Exemple #6
0
            public void Send(byte[] data, int length)
            {
                IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password);

                byte[] dataIn = new byte[length - 3];
                Array.Copy(data, 3, dataIn, 0, length - 3);
                byte[] dataOut = new byte[length - 3 + 16];
                int    outlen;

                if (encryptor != null)
                {
                    encryptor.Encrypt(dataIn, dataIn.Length, dataOut, out outlen);
                }
                else
                {
                    dataOut = dataIn;
                    outlen  = dataIn.Length;
                }
                _remote.SendTo(dataOut, _remoteEndPoint);
            }
Exemple #7
0
        private void PipeConnectionReceiveCallback(IAsyncResult ar)
        {
            if (closed)
            {
                return;
            }
            try
            {
                int bytesRead = connection.EndReceive(ar);
                totalWrite += bytesRead;

                if (bytesRead > 0)
                {
                    int bytesToSend;
                    lock (encryptionLock)
                    {
                        if (closed)
                        {
                            return;
                        }
                        encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
                    }
                    Logging.Debug(remote, bytesToSend, "TCP Relay", "@PipeConnectionReceiveCallback() (upload)");
                    tcprelay.UpdateOutboundCounter(relay.server, bytesToSend);
                    _startSendingTime = DateTime.Now;
                    _bytesToSend      = bytesToSend;
                    remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);
                }
                else
                {
                    remote.Shutdown(SocketShutdown.Send);
                    remoteShutdown = true;
                    CheckClose();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
Exemple #8
0
        public void PackData(byte[] data, int datalength, byte[] outdata, out int outlength)
        {
            int rand_len = GetRandLen(datalength);

            outlength  = rand_len + datalength + 2;
            outdata[0] = (byte)(datalength ^ last_client_hash[14]);
            outdata[1] = (byte)((datalength >> 8) ^ last_client_hash[15]);
            {
                byte[] rnd_data = new byte[rand_len];
                random.NextBytes(rnd_data);
                encryptor.Encrypt(data, datalength, data, out datalength);
                if (datalength > 0)
                {
                    if (rand_len > 0)
                    {
                        int start_pos = GetRandStartPos(rand_len, random_client);
                        Array.Copy(data, 0, outdata, 2 + start_pos, datalength);
                        Array.Copy(rnd_data, 0, outdata, 2, start_pos);
                        Array.Copy(rnd_data, start_pos, outdata, 2 + start_pos + datalength, rand_len - start_pos);
                    }
                    else
                    {
                        Array.Copy(data, 0, outdata, 2, datalength);
                    }
                }
                else
                {
                    rnd_data.CopyTo(outdata, 2);
                }
            }

            byte[] key = new byte[user_key.Length + 4];
            user_key.CopyTo(key, 0);
            BitConverter.GetBytes(pack_id).CopyTo(key, key.Length - 4);
            ++pack_id;

            byte[] md5data = MbedTLS.ComputeHash(key, outdata, 0, outlength);
            last_client_hash = md5data;
            Array.Copy(md5data, 0, outdata, outlength, 2);
            outlength += 2;
        }
        internal static XElement Save(this ISettingRecord settingRecord, IEncryptor encryptor)
        {
            var root = new XElement(Xml.SettingRecord.NodeListName);

            var username = new XElement(Xml.SettingRecord.PortalUsername);

            username.SetAttributeValue(Xml.Attributes.Value, settingRecord.PortalUsername);
            root.Add(username);

            var password = new XElement(Xml.SettingRecord.PortalPassword);

            password.SetAttributeValue(Xml.Attributes.Value, encryptor.Encrypt(settingRecord.PortalPassword));
            root.Add(password);

            var useDownloadCDn = new XElement(Xml.SettingRecord.UseDownloadCDN);

            useDownloadCDn.SetAttributeValue(Xml.Attributes.Value, settingRecord.UseDownloadCDN);
            root.Add(useDownloadCDn);

            var sendCrashDetails = new XElement(Xml.SettingRecord.SendCrashDetails);

            sendCrashDetails.SetAttributeValue(Xml.Attributes.Value, settingRecord.SendCrashDetails);
            root.Add(sendCrashDetails);

            var pluginsRepository = new XElement(Xml.SettingRecord.PluginsRepository);

            pluginsRepository.SetAttributeValue(Xml.Attributes.Value, settingRecord.PluginsRepository);
            root.Add(pluginsRepository);

            var customPluginsFolder = new XElement(Xml.SettingRecord.CustomPluginsFolder);

            customPluginsFolder.SetAttributeValue(Xml.Attributes.Value, settingRecord.CustomPluginsFolder);
            root.Add(customPluginsFolder);

            var alignVersions = new XElement(Xml.SettingRecord.AlignVersions);

            alignVersions.SetAttributeValue(Xml.Attributes.Value, settingRecord.AlignVersions);
            root.Add(alignVersions);

            return(root);
        }
Exemple #10
0
        public void numbers_are_numbers()
        {
            var bytes = _encryptor.Encrypt("test");

            foreach (int diff in bytes)
            {
                if (diff == 0 || diff == 1)
                {
                }
                else
                {
                    throw new Exception();
                }
            }
        }
        public void Compile(FileInfo inputFile, FileInfo outputFile)
        {
            if (!inputFile.Exists)
            {
                UnityEngine.Debug.LogErrorFormat("Not found the file \"{0}\"", inputFile.FullName);
                return;
            }

            if (!outputFile.Directory.Exists)
            {
                outputFile.Directory.Create();
            }

            RunCMD(command, string.Format(" -o {0} {1}", outputFile.FullName, inputFile.FullName));

            if (this.encryptor != null && outputFile.Exists)
            {
                byte[] buffer = File.ReadAllBytes(outputFile.FullName);
                File.WriteAllBytes(outputFile.FullName, encryptor.Encrypt(buffer));
            }
        }
Exemple #12
0
        /****************************************************************************/
        /// <summary>
        /// Encrypt a string
        /// </summary>
        /// <param name="data">Data to encrypt</param>
        /// <returns>A base64 encoded string of the encrypted data</returns>
        public static async Task <string> Encrypt(this IEncryptor encryptor, string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return(data);
            }

            // Get encrypted array of bytes.
            var toEncrypt = Encoding.UTF8.GetBytes(data);

            try
            {
                var encrypted = await encryptor.Encrypt(toEncrypt);

                return(Convert.ToBase64String(encrypted));
            }
            finally
            {
                Array.Clear(toEncrypt, 0, toEncrypt.Length);
            }
        }
        /// <summary>
        /// Encrypts the outgoing <see cref="TransportMessage"/> and adds appropriate headers
        /// </summary>
        public async Task Process(OutgoingStepContext context, Func <Task> next)
        {
            var transportMessage = context.Load <TransportMessage>();

            if (transportMessage.Headers.ContainsKey(EncryptionHeaders.DisableEncryptionHeader))
            {
                await next();

                return;
            }

            var headers       = transportMessage.Headers.Clone();
            var bodyBytes     = transportMessage.Body;
            var encryptedData = _encryptor.Encrypt(bodyBytes);

            headers[EncryptionHeaders.ContentEncryption]           = _encryptor.ContentEncryptionValue;
            headers[EncryptionHeaders.ContentInitializationVector] = Convert.ToBase64String(encryptedData.Iv);
            context.Save(new TransportMessage(headers, encryptedData.Bytes));

            await next();
        }
        private async Task TestEncryptDecrypt(IEncryptor encr, Stream input, string inputData)
        {
            using (var encrOutput = new MemoryStream())
            {
                await encr.Encrypt(input, encrOutput);

                var outputData = await encrOutput.ReadStringAsync();

                Assert.IsFalse(string.IsNullOrEmpty(outputData));
                Assert.AreNotEqual(inputData, outputData);

                using (var decrOutput = new MemoryStream())
                {
                    await encr.Decrypt(encrOutput, decrOutput);

                    var decrResult = await decrOutput.ReadStringAsync();

                    Assert.AreEqual(inputData, decrResult);
                }
            }
        }
Exemple #15
0
            /// <summary>
            /// 处理数据,并发送给ss服务器
            /// </summary>
            /// <param name="data"></param>
            /// <param name="length"></param>
            public void Send(byte[] data, int length)
            {
                /*
                 +----+------+------+----------+----------+----------+
                 |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
                 +----+------+------+----------+----------+----------+
                 | 2  |  1   |  1   | Variable |    2     | Variable |
                 +----+------+------+----------+----------+----------+
                 |
                 | trim => (去掉前三位,猜测是无用信息,减小数据大小/网络开销)
                 |
                 +------+----------+----------+----------+
                 | ATYP | DST.ADDR | DST.PORT |   DATA   |
                 +------+----------+----------+----------+
                 |  1   | Variable |    2     | Variable |
                 +------+----------+----------+----------+
                 |
                 | encrypt => (加密)
                 |
                 +-------+--------------+
                 |   IV  |    PAYLOAD   |
                 +-------+--------------+
                 | Fixed |   Variable   |
                 +-------+--------------+
                 */
                // 去掉前三个字节
                IEncryptor encryptor = EncryptorFactory.GetEncryptor(_server.method, _server.password, _server.auth, true);

                byte[] dataIn = new byte[length - 3 + IVEncryptor.ONETIMEAUTH_BYTES];
                Array.Copy(data, 3, dataIn, 0, length - 3);
                byte[] dataOut = new byte[length - 3 + 16 + IVEncryptor.ONETIMEAUTH_BYTES];
                int    outlen;

                // 加密
                encryptor.Encrypt(dataIn, length - 3, dataOut, out outlen);
                Logging.Debug($"++++++Send Server Port, size:" + outlen);
                // 发送给ss服务器
                _remote.SendTo(dataOut, outlen, SocketFlags.None, _remoteEndPoint);
            }
Exemple #16
0
        public void Init()
        {
            conection  = new MSSQLDB(new DBConfiguration());
            _PREP      = new ProfessorRepository(conection);
            _encryptor = new Encryptor();
            handler    = new ProfessorQueryHandler(_PREP);

            var db = conection.GetCon();

            var    cpf      = "357.034.413-40";
            string password = cpf.Replace("-", "").Replace(".", "");

            password = _encryptor.Encrypt(password, out string salt);

            professor = new Professor("Lívia", "Emanuelly Elisa", cpf, "*****@*****.**", "(21) 2682-8370", EDegree.Master, password, salt);
            _PREP.Create(professor);

            commandGet = new ProfessorInputGet()
            {
                ProfessorId = professor.Id
            };
        }
        public async Task <ValidationResult <UpdatePasswordFailure> > UpdatePasswordAsync(Guid id, string password)
        {
            var user = Users.Local.FirstOrDefault(x => x.ID == id) ?? await Users.FirstOrDefaultAsync(x => x.ID == id);

            if (user == null)
            {
                throw new ArgumentException($"User '{id}' does not exist");
            }

            if (!_passwordComplexity.Validate(password))
            {
                return(new ValidationResult <UpdatePasswordFailure>(UpdatePasswordFailure.PasswordNotComplex, _passwordComplexity.ComplexityMessage));
            }

            string passwordHash, salt;

            passwordHash = _encryptor.Encrypt(password, out salt);

            user.PasswordHash = passwordHash;
            user.Salt         = salt;

            return(new ValidationResult <UpdatePasswordFailure>());
        }
Exemple #18
0
        public ICommandResult Handle(ProfessorInputRegister command)
        {
            string password = string.Empty;
            string salt     = string.Empty;

            if (!string.IsNullOrEmpty(command.CPF))
            {
                password = _encryptor.Encrypt(command.CPF.Replace("-", "").Replace(".", ""), out salt);
            }

            var professor = new Professor(command.FirstName, command.LastName, command.CPF,
                                          command.Email, command.Phone, command.Degree, password, salt);

            var result = new StandardResult();

            result.AddRange(professor.Notifications);
            if (result.Notifications.Count == 0)
            {
                _PREP.Create(professor);
                result.Notifications.Add("Success", "O Professor foi salvo");
            }
            return(result);
        }
Exemple #19
0
        private void pipeConnectionReceiveCallback(IAsyncResult ar)
        {
            try
            {
                int bytesRead = connection.EndReceive(ar);

                if (bytesRead > 0)
                {
                    byte[] buf = encryptor.Encrypt(connetionBuffer, bytesRead);
                    remote.BeginSend(buf, 0, buf.Length, 0, new AsyncCallback(pipeRemoteSendCallback), null);
                }
                else
                {
                    Console.WriteLine("bytesRead: " + bytesRead.ToString());
                    this.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                this.Close();
            }
        }
Exemple #20
0
        public async Task SignUp(User model)
        {
            try
            {
                bool isUserEmailExist = await this._unitOfWork.UserRepository.IsEmailExistAsync(model.Email);

                if (isUserEmailExist)
                {
                    throw new BaseCustomException("User email already exists");
                }

                string encryptedPassword = _encryptor.Encrypt(model.Password);
                var    entityModel       = new User()
                {
                    Email           = model.Email,
                    Name            = model.Name,
                    Password        = encryptedPassword,
                    Birthdate       = model.Birthdate,
                    Picture         = model.Picture,
                    PictureMimeType = model.PictureMimeType,
                    PermissionId    = (int)PermissionType.User // default
                };

                this._unitOfWork.UserRepository.Create(entityModel);
                await this._unitOfWork.UserRepository.SaveAsync();
            }
            catch (BaseCustomException ex)
            {
                this._logger.LogInformation(ex, ex.Message);
                throw;
            }
            catch (Exception ex)
            {
                this._logger.LogError(ex, ex.Message);
                throw new BaseCustomException();
            }
        }
Exemple #21
0
        public void Init()
        {
            conection  = new MSSQLDB(new DBConfiguration());
            _PREP      = new ProfessorRepository(conection);
            _encryptor = new Encryptor();
            handler    = new ProfessorCommandHandler(_PREP, _encryptor);

            var db = conection.GetCon();

            var    cpf      = "357.034.413-40";
            string password = cpf.Replace("-", "").Replace(".", "");

            password = _encryptor.Encrypt(password, out string salt);

            professor = new Professor("Lívia", "Emanuelly Elisa", cpf, "*****@*****.**", "(21) 2682-8370", EDegree.Master, password, salt);
            _PREP.Create(professor);

            commandRegister = new ProfessorInputRegister()
            {
                FirstName = "Lívia",
                LastName  = "Emanuelly Elisa",
                CPF       = cpf,
                Email     = "*****@*****.**",
                Phone     = "(21) 2682-8370",
                Degree    = EDegree.Master
            };

            commandUpdate = new ProfessorInputUpdate()
            {
                ProfessorId = professor.Id,
                FirstName   = "Lívia",
                LastName    = "Emanuelly Elisa",
                Email       = "*****@*****.**",
                Phone       = "(21) 2682-8370",
                Degree      = EDegree.Master
            };
        }
        private void SendToServer(AsyncSession session)
        {
            var length = data.Length;

            _totalWrite += length;
            int bytesToSend;

            Array.Copy(data, _connetionRecvBuffer, data.Length);
            lock (_encryptionLock)
            {
                try
                {
                    _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend);
                }
                catch (CryptoErrorException)
                {
                    Close();
                    return;
                }
            }
            _startSendingTime = DateTime.Now;
            session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None,
                                     PipeRemoteSendCallback, new object[] { session, bytesToSend });
        }
Exemple #23
0
        private void SendToServer(int length, AsyncSession session)
        {
            _totalWrite += length;
            int bytesToSend;

            lock (_encryptionLock)
            {
                try
                {
                    _encryptor.Encrypt(_connetionRecvBuffer, length, _connetionSendBuffer, out bytesToSend);
                }
                catch (CryptoErrorException)
                {
                    Logger.Debug("encryption error");
                    Close();
                    return;
                }
            }

            OnOutbound?.Invoke(this, new SSTransmitEventArgs(_server, bytesToSend));
            _startSendingTime = DateTime.Now;
            session.Remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None,
                                     PipeRemoteSendCallback, new object[] { session, bytesToSend });
        }
        private void PipeConnectionReceiveCallback(IAsyncResult ar)
        {
            if (closed)
            {
                return;
            }
            try
            {
                int bytesRead = connection.EndReceive(ar);

                if (bytesRead > 0)
                {
                    int bytesToSend;
                    lock (encryptionLock)
                    {
                        if (closed)
                        {
                            return;
                        }
                        encryptor.Encrypt(connetionRecvBuffer, bytesRead, connetionSendBuffer, out bytesToSend);
                    }
                    remote.BeginSend(connetionSendBuffer, 0, bytesToSend, 0, new AsyncCallback(PipeRemoteSendCallback), null);
                }
                else
                {
                    remote.Shutdown(SocketShutdown.Send);
                    remoteShutdown = true;
                    CheckClose();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                this.Close();
            }
        }
Exemple #25
0
        public string EncodeJson(AuthenticationTicket ticket)
        {
            var value = _encryptor.Encrypt(JsonUtil.ToJson(ticket));

            return(HttpUtility.UrlEncode(value));
        }
        private async Task StartConnect()
        {
            SaeaAwaitable serverSaea = null;

            try
            {
                CreateRemote();

                _serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp);
                _serverSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
                _serverSocket.SetTFO();

                // encrypt and attach encrypted buffer to ConnectAsync
                serverSaea = _argsPool.Rent();
                var realSaea = serverSaea.Saea;

                var encryptedbufLen = -1;
                Logging.Dump("StartConnect(): enc addrBuf", _addrBuf, _addrBufLength);
                lock (_encryptionLock)
                {
                    _encryptor.Encrypt(_addrBuf, _addrBufLength, realSaea.Buffer, out encryptedbufLen);
                }
                Logging.Debug("StartConnect(): addrBuf enc len " + encryptedbufLen);
                if (_remainingBytesLen > 0)
                {
                    Logging.Debug($"StartConnect(): remainingBytesLen: {_remainingBytesLen}");
                    var    encRemainingBufLen = -1;
                    byte[] tmp = new byte[4096];
                    Logging.Dump("StartConnect(): enc remaining", _remainingBytes, _remainingBytesLen);
                    lock (_encryptionLock)
                    {
                        _encryptor.Encrypt(_remainingBytes, _remainingBytesLen, tmp, out encRemainingBufLen);
                    }
                    Logging.Debug("StartConnect(): remaining enc len " + encRemainingBufLen);
                    Buffer.BlockCopy(tmp, 0, realSaea.Buffer, encryptedbufLen, encRemainingBufLen);
                    encryptedbufLen += encRemainingBufLen;
                }
                Logging.Debug("actual enc buf len " + encryptedbufLen);
                realSaea.RemoteEndPoint = SocketUtil.GetEndPoint(_server.server, _server.server_port);
                realSaea.SetBuffer(0, encryptedbufLen);

                var err = await _serverSocket.ConnectAsync(serverSaea);

                if (err != SocketError.Success)
                {
                    Logging.Error($"StartConnect: {err}");
                    Close();
                    return;
                }
                Logging.Debug("remote connected");
                if (serverSaea.Saea.BytesTransferred != encryptedbufLen)
                {
                    // not sent all data, it may caused by TFO, disable it
                    Logging.Info("Disable TCP Fast Open due to initial send failure");
                    Program.DisableTFO();
                    Close();
                    return;
                }

                _argsPool.Return(serverSaea);
                serverSaea = null;

                if (_config.isVerboseLogging)
                {
                    Logging.Info($"Socket connected to ss server: {_server.FriendlyName()}");
                }

                Task.Factory.StartNew(StartPipe, TaskCreationOptions.PreferFairness).Forget();
            }
            catch (AggregateException agex)
            {
                foreach (var ex in agex.InnerExceptions)
                {
                    Logging.LogUsefulException(ex);
                }
                Close();
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
            finally
            {
                _argsPool.Return(serverSaea);
                serverSaea = null;
            }
        }
Exemple #27
0
        /// <summary>
        /// Attempts to acquire the lock synchronously. Usage:
        /// <code>
        ///     using (var handle = myLock.TryAcquire(...))
        ///     {
        ///         if (handle != null) { /* we have the lock! */ }
        ///     }
        ///     // dispose releases the lock if we took it
        /// </code>
        /// </summary>
        /// <param name="lock"></param>
        /// <param name="timeout">How long to wait before giving up on acquiring the lock. Defaults to 0</param>
        /// <returns>An <see cref="IDisposable"/> "handle" which can be used to release the lock, or null if the lock was not taken</returns>
        public LockAcquisitionResult TryAcquire(string @lock, TimeSpan timeout = default(TimeSpan))
        {
            // synchronous mode
            var timeoutMillis = timeout.ToInt32Timeout();

            // calculate safe lock name
            var lockName = ToSafeLockName(@lock, MaxLockNameLength, s => s);

            DbConnection acquireConnection = null;
            var          cleanup           = true;

            try
            {
                acquireConnection = GetConnection();

                if (_connectionString != null)
                {
                    acquireConnection.Open();
                }
                else if (acquireConnection == null)
                {
                    throw new InvalidOperationException("The transaction had been disposed");
                }
                else if (acquireConnection.State != ConnectionState.Open)
                {
                    throw new InvalidOperationException("The connection is not open");
                }

                var checkCommand = SqlHelpers.CreateCheckLockAvailabilityCommand(acquireConnection, timeoutMillis, lockName);
                var exists       = (int)checkCommand.ExecuteScalar() > 0;
                if (exists)
                {
                    return(LockAcquisitionResult.Fail);
                }

                var id = Guid.NewGuid();

                SqlParameter insertReturnValue;
                using (var insertCommand = SqlHelpers.CreateInsertApplicationLockCommand(acquireConnection, id,
                                                                                         timeoutMillis, lockName, Utc, out insertReturnValue))
                {
                    insertCommand.ExecuteNonQuery();
                }

                var ret = (int)insertReturnValue.Value;
                cleanup = ret == 0;
                var success = ret == 0;
                var owner   = string.Empty;

                if (success)
                {
                    // hash owner
                    owner = _encryptor.Encrypt(id.ToString());

                    // check no duplicates.
                    var checkDuplicateCommand = SqlHelpers.CreateCheckLockAvailabilityCommand(acquireConnection, timeoutMillis, lockName);
                    var duplicatesExist       = (int)checkDuplicateCommand.ExecuteScalar() > 1;

                    if (duplicatesExist)
                    {
                        // delete current lock
                        ReleaseLock(lockName, owner);
                        return(LockAcquisitionResult.Fail);
                    }
                }

                return(new LockAcquisitionResult
                {
                    Success = success,
                    LockOwner = owner
                });
            }
            catch
            {
                // in case we fail to create lock scope or something
                cleanup = true;
                throw;
            }
            finally
            {
                if (cleanup)
                {
                    Cleanup(acquireConnection);
                }
            }
        }
        public string CreateUserToken(AccountAuthorizeInfo info)
        {
            string data = $"UAT|{info.LoginId}|{info.Client}|{info.Guid}";

            return(encryptor.Encrypt(data));
        }
 public static string Encrypt(string plainText)
 {
     try
     {
         return(EncryptionCache.GetOrAdd(string.Concat(plainText, "-en-"), s => _encryptor.Encrypt(plainText)));
     }
     catch
     {
         EncryptionCache.Clear();
         throw;
     }
 }
 public string EncryptMessage(string Message)
 {
     return(_encryptor.Encrypt(Message + " alone."));
 }
Exemple #31
0
        private void PipeConnectionReceiveCallback(IAsyncResult ar)
        {
            if (_closed)
            {
                return;
            }
            try
            {
                int bytesRead = _connection.EndReceive(ar);
                _totalWrite += bytesRead;

                var session = (AsyncSession <bool>)ar.AsyncState;
                var remote  = session.Remote;

                if (bytesRead > 0)
                {
                    /*
                     * Only the first packet contains the socks5 header, it doesn't make sense to parse every packets.
                     * Also it's unnecessary to parse these data if we turn off the VerboseLogging.
                     */
                    if (session.State && _config.isVerboseLogging)
                    {
                        int    atyp = _connetionRecvBuffer[0];
                        string dst_addr;
                        int    dst_port;
                        switch (atyp)
                        {
                        case 1:     // IPv4 address, 4 bytes
                            dst_addr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString();
                            dst_port = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6];

                            Logging.Info($"connect to {dst_addr}:{dst_port}");
                            session.State = false;
                            break;

                        case 3:     // domain name, length + str
                            int len = _connetionRecvBuffer[1];
                            dst_addr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len);
                            dst_port = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3];

                            Logging.Info($"connect to {dst_addr}:{dst_port}");
                            session.State = false;
                            break;

                        case 4:     // IPv6 address, 16 bytes
                            dst_addr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray()).ToString();
                            dst_port = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18];

                            Logging.Info($"connect to [{dst_addr}]:{dst_port}");
                            session.State = false;
                            break;
                        }
                    }

                    int bytesToSend;
                    lock (_encryptionLock)
                    {
                        _encryptor.Encrypt(_connetionRecvBuffer, bytesRead, _connetionSendBuffer, out bytesToSend);
                    }
                    _tcprelay.UpdateOutboundCounter(_server, bytesToSend);
                    _startSendingTime = DateTime.Now;
                    remote.BeginSend(_connetionSendBuffer, 0, bytesToSend, SocketFlags.None, new AsyncCallback(PipeRemoteSendCallback), session);
                    IStrategy strategy = _controller.GetCurrentStrategy();
                    strategy?.UpdateLastWrite(_server);
                }
                else
                {
                    remote.Shutdown(SocketShutdown.Send);
                    _remoteShutdown = true;
                    CheckClose();
                }
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }