Ejemplo n.º 1
0
        public void Serialize(Guid connectionId, IConnectionEvent eventObject, Stream output)
        {
            var serializer = new JsonSerializer {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            UserConnection user;

            ConnectionManager._connections.TryGetValue(connectionId, out user);
            if (user != null)
            {
                var json = JObject.FromObject(eventObject, serializer);
                json.Add("type", new JValue(eventObject.GetType().Name));
                json.Remove("connectionId");
                var jsonString = json.ToString();
                var utfJson    = Encoding.Default.GetBytes(jsonString);
                jsonString = Encoding.UTF8.GetString(utfJson);
                if (user.AesShook)
                {
                    var keybytes      = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesKey));
                    var iv            = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesIv));
                    var encrpytedJson = UlteriusAes.Encrypt(jsonString, keybytes, iv);
                    using (var writer = new BinaryWriter(output, Encoding.UTF8, true))
                    {
                        writer.Write(encrpytedJson);
                    }
                }
                else
                {
                    using (var writer = new StreamWriter(output, Encoding.UTF8, 4096, true))
                    {
                        writer.Write(jsonString);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public IConnectionRequest Deserialize(Guid connectionId, Stream source, out Type type)
        {
            UserConnection user;
            var            typeName = string.Empty;

            ConnectionManager._connections.TryGetValue(connectionId, out user);
            if (user != null)
            {
                var data = ReadFully(source);
                if (data != null && data.Length > 0)
                {
                    if (user.AesShook)
                    {
                        try
                        {
                            var keybytes   = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesKey));
                            var iv         = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesIv));
                            var packetJson = JObject.Parse(UlteriusAes.Decrypt(data, keybytes, iv));
                            typeName = packetJson.Property("type").Value.ToString();
                            return(Build(typeName, packetJson, out type, user));
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception.Message);
                            return(Build("error", null, out type));
                        }
                    }
                    var json = JObject.Parse(Encoding.UTF8.GetString(data));
                    typeName = json.Property("type").Value.ToString();
                    return(Build(typeName, json, out type, user));
                }
            }
            return(Build("error", null, out type));
        }
Ejemplo n.º 3
0
        //Decrypts a file to be stored on the local computer
        public static bool DecryptFile(string fileKey, byte[] fileData)
        {
            ApprovedFile file;

            //Check if the file is on the white list
            if (Whitelist.TryGetValue(fileKey, out file))
            {
                try
                {
                    //decrypt the file
                    var passwordBytes   = Encoding.UTF8.GetBytes(file.Password.ToUnsecureString());
                    var decryptedFile   = UlteriusAes.DecryptFile(fileData, passwordBytes);
                    var destinationPath = file.DestinationPath;
                    //Write the files data to disk
                    System.IO.File.WriteAllBytes(destinationPath, decryptedFile);
                    //Remove the file from the white list
                    RemoveFile(fileKey);
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
Ejemplo n.º 4
0
        public void ProcessFile(string path, string password, long totalSize)
        {
            var webPath        = config.WebServer.WebFilePath;
            var tempFolderPath = webPath + "temp\\";

            if (!Directory.Exists(tempFolderPath))
            {
                Directory.CreateDirectory(tempFolderPath);
            }
            var file = new FileInfo(path);

            file.Directory?.Create(); // If the directory already exists, this method does nothing.


            var fileName = Path.GetFileName(path);

            var ip   = NetworkService.GetAddress();
            var port = config.WebServer.WebServerPort;

            var passwordBytes = Encoding.UTF8.GetBytes(password);

            if (File.Exists(path))
            {
                try
                {
                    var tempPath = Path.Combine(tempFolderPath, fileName);
                    UlteriusAes.EncryptFile(passwordBytes, path, tempPath);
                    var tempWebPath  = $"http://{ip}:{port}/temp/{fileName}";
                    var downloadData = new
                    {
                        tempWebPath,
                        totalSize
                    };
                    _builder.WriteMessage(downloadData);
                }
                catch (Exception e)
                {
                    var exceptionData = new
                    {
                        error   = true,
                        message = e.Message
                    };

                    _builder.WriteMessage(exceptionData);
                }
            }
            else
            {
                var errorData = new
                {
                    error   = true,
                    message = "Unable to encrypt file"
                };
                _builder.WriteMessage(errorData);
            }
        }
Ejemplo n.º 5
0
 public byte[] SerializeFile(WebSocket client, string password, byte[] data)
 {
     try
     {
         var passwordBytes = Encoding.UTF8.GetBytes(password);
         return(UlteriusAes.EncryptFile(data, passwordBytes));
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         return(null);
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 ///     Encrypt a file with AES using only a password
 /// </summary>
 /// <param name="password"></param>
 /// <param name="data"></param>
 /// <returns>encryptedFile</returns>
 public byte[] PackFile(string password, byte[] data)
 {
     try
     {
         var passwordBytes = Encoding.UTF8.GetBytes(password);
         return(UlteriusAes.EncryptFile(data, passwordBytes));
     }
     catch (Exception e)
     {
         Console.WriteLine($"Console unable to pack file: {e.Message}");
         return(null);
     }
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Decrypt a packet
 /// </summary>
 /// <param name="authClient"></param>
 /// <param name="data"></param>
 public PacketManager(AuthClient authClient, byte[] data)
 {
     _authClient = authClient;
     try
     {
         var keyBytes = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(authClient.AesKey));
         var ivBytes  = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(authClient.AesIv));
         _plainText = UlteriusAes.Decrypt(data, keyBytes, ivBytes);
     }
     catch (Exception e)
     {
         Console.WriteLine($"Packet failed to decrypt: {e.Message}");
         _packetType = PacketTypes.InvalidOrEmptyPacket;
     }
 }
Ejemplo n.º 8
0
        public void Serialize(Guid connectionId, IConnectionEvent eventObject, Stream output)
        {
            var serializer = new JsonSerializer {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            UserConnection user;

            ConnectionManager._connections.TryGetValue(connectionId, out user);
            if (user != null)
            {
                var json = JObject.FromObject(eventObject, serializer);
                json.Add("type", new JValue(eventObject.GetType().Name));
                json.Remove("connectionId");
                var jsonString = json.ToString().UnicodeUtf8();
                Console.WriteLine(jsonString);
                if (user.AesShook)
                {
                    var keybytes      = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesKey));
                    var iv            = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesIv));
                    var encrpytedJson = UlteriusAes.Encrypt(Encoding.UTF8.GetBytes(jsonString), keybytes, iv);

                    using (var memoryStream = new MemoryStream())
                    {
                        using (var binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8))
                        {
                            var Endpoint = "terminal";
                            binaryWriter.Write(Endpoint.Length);
                            binaryWriter.Write(Encoding.UTF8.GetBytes(Endpoint));
                            binaryWriter.Write(Encoding.UTF8.GetBytes(UlteriusAes.EncryptionType.CBC.ToString()));
                            binaryWriter.Write(encrpytedJson);
                        }
                        using (var writer = new BinaryWriter(output, Encoding.UTF8, true))
                        {
                            writer.Write(memoryStream.ToArray());
                        }
                    }
                }
                else
                {
                    using (var writer = new StreamWriter(output, Encoding.UTF8, 4096, true))
                    {
                        writer.Write(jsonString);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public IConnectionRequest Deserialize(Guid connectionId, Stream source, out Type type)
        {
            UserConnection user;
            var            typeName = string.Empty;

            ConnectionManager._connections.TryGetValue(connectionId, out user);
            if (user != null)
            {
                using (var reader = new StreamReader(source, Encoding.UTF8))
                {
                    var data = reader.ReadToEnd();
                    if (data.IsBase64String())
                    {
                        try
                        {
                            var keybytes   = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesKey));
                            var iv         = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesIv));
                            var packet     = Convert.FromBase64String(data);
                            var packetJson = JObject.Parse(UlteriusAes.Decrypt(packet, keybytes, iv));
                            typeName = packetJson.Property("type").Value.ToString();
                            return(Build(typeName, packetJson, out type, user));
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine("Error deserial");
                            Console.WriteLine(exception.Message);
                            return(Build("error", null, out type));
                        }
                    }
                    if (user.AesShook)
                    {
                        return(Build("alreadyshook", null, out type));
                    }
                    var json = JObject.Parse(data);
                    typeName = json.Property("type").Value.ToString();
                    return(Build(typeName, json, out type, user));
                }
            }
            return(Build("error", null, out type));
        }
Ejemplo n.º 10
0
        public static bool DecryptFile(string fileKey, byte[] fileData)
        {
            ApprovedFile file;

            if (Whitelist.TryGetValue(fileKey, out file))
            {
                try
                {
                    var passwordBytes   = Encoding.UTF8.GetBytes(file.Password);
                    var decryptedFile   = UlteriusAes.DecryptFile(fileData, passwordBytes);
                    var destinationPath = file.DestinationPath;
                    System.IO.File.WriteAllBytes(destinationPath, decryptedFile);
                    RemoveFile(fileKey);
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
Ejemplo n.º 11
0
        public void Serialize(WebSocket client, string endpoint, string synckey, object data)
        {
            var serializer = new JavaScriptSerializer {
                MaxJsonLength = int.MaxValue
            };
            var json = serializer.Serialize(new
            {
                endpoint,
                synckey,
                results = data
            });

            //we sanity stuff
            try
            {
                AuthClient authClient;
                TaskManagerServer.AllClients.TryGetValue(client.GetHashCode().ToString(), out authClient);
                if (authClient != null)
                {
                    if (authClient.AesShook)
                    {
                        var keyBytes      = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(authClient.AesKey));
                        var keyIv         = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(authClient.AesIv));
                        var encryptedData = UlteriusAes.Encrypt(json, keyBytes, keyIv);
                        json = Convert.ToBase64String(encryptedData);
                    }
                }
            }
            catch (Exception)
            {
                if (endpoint != null && !endpoint.Equals("aeshandshake"))
                {
                    return;
                }
            }
            Push(client, json);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     Writes a message to the queue.
        /// </summary>
        /// <param name="data"></param>
        public void WriteMessage(object data)
        {
            if (_authClient.Client != null)
            {
                var json = JsonConvert.SerializeObject(new
                {
                    endpoint = Endpoint,
                    synckey,
                    results = data
                });


                try
                {
                    if (_authClient != null)
                    {
                        if (_authClient.AesShook)
                        {
                            var keyBytes      = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(_authClient.AesKey));
                            var keyIv         = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(_authClient.AesIv));
                            var encryptedData = UlteriusAes.Encrypt(json, keyBytes, keyIv);
                            var message       = new Message(_authClient, encryptedData, Message.MessageType.Binary);
                            UlteriusApiServer.MessageQueueManager.SendQueue.Add(message);
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Could not send encrypted message: {e.Message}");
                    return;
                }
                var jsonMessage = new Message(_authClient, json, Message.MessageType.Text);
                UlteriusApiServer.MessageQueueManager.SendQueue.Add(jsonMessage);
            }
        }
Ejemplo n.º 13
0
        public Packets(AuthClient client, string packetData)
        {
            //An entire base64 string is an aes encrypted packet
            if ((bool)Settings.Get("TaskServer").Encryption)
            {
                if (packetData.IsBase64String())
                {
                    try
                    {
                        var keybytes = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(client.AesKey));
                        var iv       = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(client.AesIv));
                        var packet   = Convert.FromBase64String(packetData);
                        packetData = UlteriusAes.Decrypt(packet, keybytes, iv);
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception.Message);

                        PacketType = PacketType.InvalidOrEmptyPacket;
                        return;
                    }
                }
                else
                {
                    //the only non encrypted packet allowed is the first handshake
                    try
                    {
                        var validHandshake = JObject.Parse(packetData);
                        var endpoint       = validHandshake["endpoint"].ToString().Trim().ToLower();
                        if (!endpoint.Equals("aeshandshake"))
                        {
                            PacketType = PacketType.InvalidOrEmptyPacket;
                            return;
                        }
                        //prevent sending a new aes key pair after a handshake has already taken place
                        if (client.AesShook)
                        {
                            PacketType = PacketType.InvalidOrEmptyPacket;
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        PacketType = PacketType.InvalidOrEmptyPacket;
                        return;
                    }
                }
            }


            JObject deserializedPacket = null;

            try
            {
                deserializedPacket = JObject.Parse(packetData);
            }
            catch (Exception)
            {
                PacketType = PacketType.InvalidOrEmptyPacket;
                return;
            }
            if (deserializedPacket != null)
            {
                try
                {
                    Endpoint = deserializedPacket["endpoint"].ToString().Trim().ToLower();
                }
                catch (Exception)
                {
                    PacketType = PacketType.InvalidOrEmptyPacket;
                    return;
                }
                try
                {
                    SyncKey = deserializedPacket["synckey"].ToString().Trim();
                }
                catch (Exception)
                {
                    SyncKey = null;
                }
                try
                {
                    Args.AddRange(JArray.Parse(deserializedPacket["args"].ToString()));
                }
                catch (Exception)
                {
                    // no args
                }
                switch (Endpoint)
                {
                case "authenticate":
                    PacketType = PacketType.Authenticate;
                    break;

                case "requestgpuinformation":
                    PacketType = PacketType.RequestGpuInformation;
                    break;

                case "createfiletree":
                    PacketType = PacketType.CreateFileTree;
                    break;

                case "requestprocessinformation":
                    PacketType = PacketType.RequestProcess;
                    break;

                case "requestcpuinformation":
                    PacketType = PacketType.RequestCpuInformation;
                    break;

                case "requestosinformation":
                    PacketType = PacketType.RequestOsInformation;
                    break;

                case "requestnetworkinformation":
                    PacketType = PacketType.RequestNetworkInformation;
                    break;

                case "requestsysteminformation":
                    PacketType = PacketType.RequestSystemInformation;
                    break;

                case "startprocess":
                    PacketType = PacketType.StartProcess;
                    break;

                case "killprocess":
                    PacketType = PacketType.KillProcess;
                    break;

                case "generatenewkey":
                    PacketType = PacketType.GenerateNewKey;
                    break;

                case "togglewebserver":
                    PacketType = PacketType.UseWebServer;
                    break;

                case "changewebserverport":
                    PacketType = PacketType.ChangeWebServerPort;
                    break;

                case "changewebfilepath":
                    PacketType = PacketType.ChangeWebFilePath;
                    break;

                case "startvncserver":
                    PacketType = PacketType.StartScreenShare;
                    break;

                case "stopvncserver":
                    PacketType = PacketType.StopScreenShare;
                    break;

                case "changevncpass":
                    PacketType = PacketType.ChangeVncPass;
                    break;

                case "changetaskserverport":
                    PacketType = PacketType.ChangeTaskServerPort;
                    break;

                case "changevncport":
                    PacketType = PacketType.ChangeVncPort;
                    break;

                case "changevncproxyport":
                    PacketType = PacketType.ChangeVncProxyPort;
                    break;

                case "changenetworkresolve":
                    PacketType = PacketType.ChangeNetworkResolve;
                    break;

                case "changeloadplugins":
                    PacketType = PacketType.ChangeLoadPlugins;
                    break;

                case "changeuseterminal":
                    PacketType = PacketType.ChangeUseTerminal;
                    break;

                case "getcurrentsettings":
                    PacketType = PacketType.GetCurrentSettings;
                    break;

                case "geteventlogs":
                    PacketType = PacketType.GetEventLogs;
                    break;

                case "checkforupdate":
                    PacketType = PacketType.CheckUpdate;
                    break;

                case "restartserver":
                    PacketType = PacketType.RestartServer;
                    break;

                case "getwindowsdata":
                    PacketType = PacketType.RequestWindowsInformation;
                    break;

                case "getactivewindowssnapshots":
                    PacketType = PacketType.GetActiveWindowsSnapshots;
                    break;

                case "plugin":
                    PacketType = PacketType.Plugin;
                    break;

                case "getplugins":
                    PacketType = PacketType.GetPlugins;
                    break;

                case "getbadplugins":
                    PacketType = PacketType.GetBadPlugins;
                    break;

                case "startcamera":
                    PacketType = PacketType.StartCamera;
                    break;

                case "stopcamera":
                    PacketType = PacketType.StopCamera;
                    break;

                case "pausecamera":
                    PacketType = PacketType.PauseCamera;
                    break;

                case "getcameras":
                    PacketType = PacketType.GetCameras;
                    break;

                case "getcameraframe":
                    PacketType = PacketType.GetCameraFrame;
                    break;

                case "startcamerastream":
                    PacketType = PacketType.StartCameraStream;
                    break;

                case "stopcamerastream":
                    PacketType = PacketType.StopCameraStream;
                    break;

                case "refreshcameras":
                    PacketType = PacketType.RefreshCameras;
                    break;

                case "approvefile":
                    PacketType = PacketType.ApproveFile;
                    break;

                case "requestfile":
                    PacketType = PacketType.RequestFile;
                    break;

                case "aeshandshake":
                    PacketType = PacketType.AesHandshake;
                    break;

                case "approveplugin":
                    PacketType = PacketType.ApprovePlugin;
                    break;

                case "getpendingplugins":
                    PacketType = PacketType.GetPendingPlugins;
                    break;

                case "removefile":
                    PacketType = PacketType.RemoveFile;
                    break;

                case "searchfiles":
                    PacketType = PacketType.SearchFiles;
                    break;

                default:
                    PacketType = PacketType.InvalidOrEmptyPacket;
                    break;
                }
            }
        }