/// <summary>
        /// Generates the encrypted log event.
        /// </summary>
        /// <param name="source">The source logging event.</param>
        /// <returns>The source logging event with the message encrypted accordingly</returns>
        public virtual LoggingEvent GenerateEncryptedLogEvent(LoggingEvent source)
        {
            LoggingEvent result;

            try
            {
                var encryptedMessage = MessageEncryption.Encrypt(source.RenderedMessage);

                string exceptionString           = source.GetExceptionString();
                string encryptedExceptionMessage = null;

                if (!string.IsNullOrWhiteSpace(exceptionString))
                {
                    encryptedExceptionMessage = MessageEncryption.Encrypt(exceptionString);
                }

                result = LogEventFactory.CreateEncryptedLoggingEvent(source, encryptedMessage, encryptedExceptionMessage);
            }
            catch (Exception ex)
            {
                // Ensure that the logging encryption never fails with an unexpected exception, rather, create an error
                // log event so that can be logged instead. This is to ensure that we aren't inadvertently leaking
                // sensitive data in our logs if an error occurs, better to log nothing than leak data!
                result = LogEventFactory.CreateErrorEvent(ex.Message);
            }

            return(result);
        }
예제 #2
0
        /// <summary>
        /// Obfuscates the data before it is forwarded to <see cref="ProtocolMessage"/>.
        /// </summary>
        public override void SetFinalized(byte[] messageData)
        {
            // obfuscate the data before its being finalized to be sent
            MessageEncryption.Xor(messageData);

            base.SetFinalized(messageData);
        }
예제 #3
0
        public void AuditEventWithNoDataEncryptsAndDecryptsSuccessfully()
        {
            var mockCase       = new MockCase();
            var mockAttachment = new MockAttachment()
            {
                Filename = GetRandomFilename()
            };

            var request = AuditRequest.AsChangeTo(mockCase, c => c.SysRef)
                          .WithNoData()
                          .AsEvent(nameof(this.AuditEventWithNoDataEncryptsAndDecryptsSuccessfully));
            var auditEvent = new AuditEvent(request);

            var key = "IlgY+s8d2q+QVXNx3ULHaUmNmcjgKQGXZFvxysqF5mA=";

            var crypto           = new MessageEncryption();
            var encryptedMessage = crypto.EncryptMessageBody(auditEvent, key);

            var decryptedEvent = crypto.DecryptMessageBody <AuditEvent>(encryptedMessage, key);

            decryptedEvent.TargetType.Should().Be(typeof(MockCase).Name);
            decryptedEvent.TargetId.Should().Be(mockCase.SysRef);

            decryptedEvent.DataType.Should().BeNull();
            decryptedEvent.DataId.Should().BeNull();

            Assert.IsTrue(object.ReferenceEquals(null, decryptedEvent.Data));
        }
예제 #4
0
        public void AuditEventWithDataEncryptsAndDecryptsSuccessfully()
        {
            var mockCase       = new MockCase();
            var mockAttachment = new MockAttachment()
            {
                Filename = GetRandomFilename()
            };

            var request = AuditRequest.AsChangeTo(mockCase, c => c.SysRef)
                          .WithData(mockAttachment, a => a.Id.ToString(CultureInfo.InvariantCulture))
                          .AsEvent(nameof(this.AuditEventWithDataEncryptsAndDecryptsSuccessfully));
            var auditEvent = new AuditEvent(request);

            var key = "IlgY+s8d2q+QVXNx3ULHaUmNmcjgKQGXZFvxysqF5mA=";

            var crypto           = new MessageEncryption();
            var encryptedMessage = crypto.EncryptMessageBody(auditEvent, key);

            var decryptedEvent = crypto.DecryptMessageBody <AuditEvent>(encryptedMessage, key);

            decryptedEvent.TargetType.Should().Be(typeof(MockCase).Name);
            decryptedEvent.TargetId.Should().Be(mockCase.SysRef);

            decryptedEvent.DataType.Should().Be(typeof(MockAttachment).FullName);
            decryptedEvent.DataId.Should().Be(mockAttachment.Id.ToString(CultureInfo.InvariantCulture));

            Assert.IsFalse(object.ReferenceEquals(null, decryptedEvent.Data));

            string dataAsJson       = JsonConvert.SerializeObject(decryptedEvent.Data);
            string attachmentAsJson = JsonConvert.SerializeObject(mockAttachment);

            dataAsJson.Should().Be(attachmentAsJson);
        }
예제 #5
0
        /// <summary>
        /// Deobfuscates the network message before it forwarded to <see cref="ProtocolMessage"/> and protocol implementation.
        /// </summary>
        public override byte[] GetFinalized()
        {
            var data = base.GetFinalized();

            // deobfuscate the data before the finalized packet is being processed
            MessageEncryption.Xor(data);

            return(data);
        }
예제 #6
0
        protected EncryptedMessage encryptMessage(string message, Guid remoteId)
        {
            // encrypt message
            var em = MessageEncryption.Encrypt(Encoding.UTF8.GetBytes(message));

            // encrypt key
            encryptKey(ref em, remoteId);

            return(em);
        }
예제 #7
0
        private byte[] CreateByteArray(byte[] bytes, string header, bool encrypt)
        {
            try
            {
                byte[] messageArray = null;
                byte[] headerArray  = null;

                //Compress message bytes
                //The header is not worth compressing.
                bytes = ByteCompressor.CompressBytes(bytes);

                if (encrypt)
                {
                    //Header
                    byte[] encryptedPrefix = Encoding.UTF8.GetBytes("ENCRYPTED_");
                    byte[] encryptedHeader = MessageEncryption.EncryptStringToBytes(header);

                    headerArray = new byte[encryptedHeader.Length + encryptedPrefix.Length];

                    encryptedPrefix.CopyTo(headerArray, 0);
                    encryptedHeader.CopyTo(headerArray, 10);

                    messageArray = MessageEncryption.EncryptBytes(bytes);
                }
                else
                {
                    headerArray  = Encoding.UTF8.GetBytes(header);
                    messageArray = bytes;
                }


                //Message
                byte[] messageData   = messageArray;
                byte[] headerBytes   = headerArray;
                byte[] headerLen     = BitConverter.GetBytes(headerBytes.Length);
                byte[] messageLength = BitConverter.GetBytes(messageData.Length);


                var data = new byte[4 + 4 + headerBytes.Length + messageData.Length];

                messageLength.CopyTo(data, 0);
                headerLen.CopyTo(data, 4);
                headerBytes.CopyTo(data, 8);
                messageData.CopyTo(data, 8 + headerBytes.Length);

                return(data);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
예제 #8
0
 //Encrypts a file and returns the new file path.
 protected async Task <string> EncryptFileAsync(string path)
 {
     try
     {
         return(await Task.Run(() =>
         {
             MessageEncryption.FileEncrypt(Path.GetFullPath(path));
             path += MessageEncryption.Extension;
             return path;
         }, Token));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message, ex);
     }
 }
예제 #9
0
 //Encrypts a file and returns the new file path.
 protected async Task <string> EncryptFileAsync(string path)
 {
     try
     {
         return(await Task.Run(() =>
         {
             var outPath = path + MessageEncryption.Extension;
             var info = MessageEncryption.FileEncrypt(Path.GetFullPath(path), outPath);
             return info.FullName;
         }, Token));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message, ex);
     }
 }
        protected SocketStateState(ISocketState state, SocketClient client, ServerListener listener)
        {
            State  = state;
            Client = client;
            Server = listener;

            if (client == null)
            {
                Encrypter        = Server.MessageEncryption;
                FileCompressor   = Server.FileCompressor;
                FolderCompressor = Server.FolderCompressor;
            }

            if (Server == null)
            {
                Encrypter        = client.MessageEncryption;
                FileCompressor   = client.FileCompressor;
                FolderCompressor = client.FolderCompressor;
            }
        }
예제 #11
0
        //Streams the file and constantly sends bytes to server or client.
        //This method is called in createAsyncFileMessage.
        //Id is an optional parameter with default value of -1)
        protected async Task StreamFileAndSendBytesAsync(string location, string remoteSaveLocation, bool encrypt, int id = -1)
        {
            try
            {
                var file   = location;
                var buffer = new byte[4096];                 //Any buffer bigger then 85 000 bytes get allocated in LOH => bad for memory usage!
                //var buffer = new byte[10485760]; //10 MB buffer
                bool         firstRead = true;
                MemoryStream memStream = null;

                //Stream that reads the file and sends bits to the server.
                using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, buffer.Length, true))
                {
                    //How much bytes that have been read
                    int read = 0;

                    while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, Token)) > 0)
                    {
                        //data bytes
                        byte[] data = null;

                        //The message
                        byte[] message = new byte[read];
                        Array.Copy(buffer, 0, message, 0, read);


                        //Checks if it is the first read of the file
                        if (firstRead)
                        {
                            byte[] header = null;

                            if (encrypt)
                            {
                                byte[] prefix     = Encoding.UTF8.GetBytes("ENCRYPTED_");
                                byte[] headerData = MessageEncryption.EncryptStringToBytes(remoteSaveLocation);
                                header = new byte[prefix.Length + headerData.Length];
                                prefix.CopyTo(header, 0);
                                headerData.CopyTo(header, 10);
                            }
                            else
                            {
                                header = Encoding.UTF8.GetBytes(remoteSaveLocation);
                            }

                            //Message
                            byte[] messageData   = message;                                   //Message part
                            byte[] headerBytes   = header;                                    //Header
                            byte[] headerLen     = BitConverter.GetBytes(headerBytes.Length); //Length of the header
                            byte[] messageLength = BitConverter.GetBytes(stream.Length);      //Total bytes in the file

                            data = new byte[4 + 4 + headerBytes.Length + messageData.Length];

                            messageLength.CopyTo(data, 0);
                            headerLen.CopyTo(data, 4);
                            headerBytes.CopyTo(data, 8);
                            messageData.CopyTo(data, 8 + headerBytes.Length);

                            firstRead = false;
                        }
                        else
                        {
                            data = message;
                        }

                        //Use memorystream as temp buffer
                        //otherwise there will be too much separate message sent.
                        //And if buffer is to big the data will end up in the LOH.
                        if (memStream == null)
                        {
                            memStream = new MemoryStream();
                        }

                        memStream.Write(data, 0, data.Length);


                        if (memStream.Length >= buffer.Length * 2560)
                        {
                            SendBytesPartial(memStream.ToArray(), id);
                            memStream.Close();
                            memStream = null;
                        }
                    }
                }

                if (memStream != null)
                {
                    SendBytesPartial(memStream.ToArray(), id);
                    memStream.Close();
                    memStream = null;
                }



                //Delete encrypted file after it has been read.
                if (encrypt)
                {
                    File.Delete(file);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
예제 #12
0
        protected async Task <List <int> > StreamFileAndSendToAllClients(string location, string remoteSaveLocation, bool encrypt)
        {
            try
            {
                var          file      = location;
                var          buffer    = new byte[4096];
                MemoryStream memStream = null;
                bool         firstRead = true;
                List <int>   clientIds = new List <int>();

                foreach (var c in GetClients())
                {
                    clientIds.Add(c.Value.Id);
                }

                //Stream that reads the file and sends bits to the server.
                using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, buffer.Length, true))
                {
                    //How much bytes that have been read
                    int read = 0;


                    while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        //data bytes
                        byte[] data = null;

                        //The message
                        byte[] message = new byte[read];
                        Array.Copy(buffer, 0, message, 0, read);


                        //Checks if it is the first read of the file
                        if (firstRead)
                        {
                            byte[] header = null;

                            if (encrypt)
                            {
                                byte[] prefix     = Encoding.UTF8.GetBytes("ENCRYPTED_");
                                byte[] headerData = MessageEncryption.EncryptStringToBytes(remoteSaveLocation);
                                header = new byte[prefix.Length + headerData.Length];
                                prefix.CopyTo(header, 0);
                                headerData.CopyTo(header, 10);
                            }
                            else
                            {
                                header = Encoding.UTF8.GetBytes(remoteSaveLocation);
                            }

                            //Message
                            byte[] messageData   = message;                                   //Message part
                            byte[] headerBytes   = header;                                    //Header
                            byte[] headerLen     = BitConverter.GetBytes(headerBytes.Length); //Length of the header
                            byte[] messageLength = BitConverter.GetBytes(stream.Length);      //Total bytes in the file

                            data = new byte[4 + 4 + headerBytes.Length + messageData.Length];

                            messageLength.CopyTo(data, 0);
                            headerLen.CopyTo(data, 4);
                            headerBytes.CopyTo(data, 8);
                            messageData.CopyTo(data, 8 + headerBytes.Length);

                            firstRead = false;
                        }
                        else
                        {
                            data = message;
                        }



                        //Use memorystream as temp buffer
                        //otherwise there will be too much separate message sent.
                        //And if buffer is to big the data will end up in the LOH.
                        if (memStream == null)
                        {
                            memStream = new MemoryStream();
                        }

                        memStream.Write(data, 0, data.Length);


                        if (memStream.Length >= buffer.Length * 2560)
                        {
                            foreach (var key in clientIds)
                            {
                                SendBytesPartial(data, key);
                            }
                            memStream.Close();
                            memStream = null;
                        }
                    }
                }

                //Delete encrypted file after it has been read.
                if (encrypt)
                {
                    File.Delete(file);
                }

                return(clientIds);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }