コード例 #1
0
        private void HandlePacket(object raw)
        {
            EncryptedPacket packet = (EncryptedPacket)raw;

            packet.UnpackHeader();
            HandlePacket(packet);
        }
コード例 #2
0
        public void TestRefuseCreatingSameCID()
        {
            ClosePipeRPC close     = new ClosePipeRPC(100);
            uint         requestId = close.RequestID;
            //create the connection
            ControlPipe     c      = new ControlPipe(tunnel);
            EncryptedPacket packet = new EncryptedPacket(tunnel.ID, 0);

            packet.RPCs.Add(new CreateAnonymousPipe(PipeType.Duplex.ToString(), 100));
            c.HandlePacket(packet);

            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count > 0);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.RefusePipe);
                RefusePipe refuse = (RefusePipe)p.RPCs.First;
                Assert.IsTrue(refuse.Reason == (byte)RefusePipe.RefusalReason.ID_ALREADY_EXISTS);
            });

            tunnel.PipeInterceptor(connection =>
            {
                Assert.Fail("Connection request should never hit the tunnel");
            });

            packet = new EncryptedPacket(tunnel.ID, 0);
            packet.RPCs.Add(new CreateAnonymousPipe(PipeType.Duplex.ToString(), 100));
            c.HandlePacket(packet);
        }
コード例 #3
0
        public async Task <IActionResult> SendNewMessage([FromBody] NewEncryptedPacketModel newMessage)
        {
            if (userRepository.GetById(newMessage.ReceiverId) == null)
            {
                ModelState.AddModelError("error", "Receiver does not exist");
                return(BadRequest(ModelState));
            }

            // convert model to EncryptedPacket
            EncryptedPacket encryptedPacket = new EncryptedPacket
            {
                DataType            = newMessage.DataType,
                EncryptedData       = newMessage.EncryptedData,
                EncryptedSessionKey = newMessage.EncryptedSessionKey,
                Hmac               = newMessage.Hmac,
                Iv                 = newMessage.Iv,
                ReceiverId         = newMessage.ReceiverId,
                Signature          = newMessage.Signature,
                SenderId           = (await GetUserAsync().ConfigureAwait(false)).Id,
                SendDateTime       = DateTime.Now,
                IsMeantForReceiver = newMessage.MeantForReceiver
            };

            // try to add to database
            try
            {
                encryptedPacketRepository.Add(encryptedPacket);
                return(Ok());
            }
            catch (ArgumentException e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #4
0
        public void TestCloseConnection()
        {
            SecureTunnel t = new SecureTunnel(tunnelSocket);

            byte[] privateKey, publicKey;
            privateKey = new byte[0];
            publicKey  = new byte[0];
            this.SetupTunnelComms(t, out privateKey, out publicKey);

            tunnelSocket.InterceptOutgoingPacket(p =>
            {
                //we should recieve a close connection packet
                EncryptedPacket packet = (EncryptedPacket)p;
                packet.DecryptPacket(privateKey, publicKey);
                var x = packet.RPCs.First;
                Assert.IsTrue(x.SerializationTag == (byte)RPCType.ClosePipe);
            });

            DuplexPipe connection = new DuplexPipe(t, 100);

            Assert.IsTrue(t.OpenPipe(connection));
            Assert.IsTrue(t.PipeIDs.Contains((uint)100));

            Assert.IsTrue(t.ClosePipe((uint)100));
            Assert.IsFalse(t.PipeIDs.Contains((uint)100));
        }
コード例 #5
0
        public void HandleClosePipeRequest()
        {
            ClosePipeRPC close     = new ClosePipeRPC(100);
            uint         requestId = close.RequestID;
            //create the connection
            ControlPipe     c      = new ControlPipe(tunnel);
            EncryptedPacket packet = new EncryptedPacket(tunnel.ID, 0);

            packet.RPCs.Add(new CreateAnonymousPipe(PipeType.Duplex.ToString(), 100));
            c.HandlePacket(packet);

            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count > 0);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.Ok);
                OkRPC ok = (OkRPC)p.RPCs.First;
                Assert.IsTrue(ok.RPCID == requestId);
            });

            tunnel.PipeInterceptor(connection =>
            {
                Assert.That(connection.ID == 100);
            });
            packet = new EncryptedPacket(tunnel.ID, 0);
            packet.RPCs.Add(close);
            c.HandlePacket(packet);
        }
コード例 #6
0
        public void Update_Should_Throw_ArgumentException_If_Id_Does_Not_Exists()
        {
            EncryptedPacket existingEncryptedPacket = ValidEncryptedPacket;

            existingEncryptedPacket.Id = -5;
            Assert.That(() => encryptedPacketRepository.Update(existingEncryptedPacket), Throws.ArgumentException);
        }
コード例 #7
0
        public void HandlePrepareRekeyRequest()
        {
            byte[]       fake  = new byte[] { 1, 1, 1 };
            PrepareRekey rekey = new PrepareRekey(fake);

            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count > 0);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.RekeyResponse);
                RekeyResponse ok = (RekeyResponse)p.RPCs.First;
                Assert.IsTrue(ok.NextPublicKey.Length == 32);
            });

            tunnel.RekeyInterceptor(k =>
            {
                Assert.That(k[0] == fake[0]);
                Assert.That(k[1] == fake[1]);
                Assert.That(k[2] == fake[2]);
            });
            ControlPipe     c      = new ControlPipe(tunnel);
            EncryptedPacket packet = new EncryptedPacket(tunnel.ID, 0);

            packet.RPCs.Add(rekey);
            c.HandlePacket(packet);
        }
コード例 #8
0
        /// <summary>
        /// Pushes encrypted data packet to ESPlayer.
        /// Decryption is performed prior to packet push.
        /// </summary>
        /// <param name="dataPacket">Packet</param>
        /// <param name="token">CancellationToken</param>
        /// <exception cref="PacketSubmitException">
        /// Exception thrown on submit error
        /// </exception>
        /// <exception cref="OperationCanceledException">
        /// Exception thrown on submit cancellation
        /// </exception>
        private async Task PushEncryptedPacket(EncryptedPacket dataPacket, CancellationToken token)
        {
            using (var decryptedPacket = await dataPacket.Decrypt(token) as DecryptedEMEPacket)
            {
                // Continue pushing packet till success or terminal failure
                for (; ;)
                {
                    var submitStatus = player.Submit(decryptedPacket);

                    logger.Debug(
                        $"{decryptedPacket.StreamType}: ({submitStatus}) PTS: {decryptedPacket.Pts} Duration:" +
                        $"{decryptedPacket.Duration} Handle: {decryptedPacket.HandleSize.handle} " +
                        $"HandleSize: {decryptedPacket.HandleSize.size}");

                    if (submitStatus == ESPlayer.SubmitStatus.Success)
                    {
                        decryptedPacket.CleanHandle();
                        return;
                    }

                    if (!ShouldRetry(submitStatus))
                    {
                        throw new PacketSubmitException("Packet Submit Error", submitStatus);
                    }

                    var delay = CalculateDelay(submitStatus);
                    Wait(delay, token);
                }
            }
        }
コード例 #9
0
        public byte[] DecryptData(EncryptedPacket encryptedPacket, AsymmetricEncryptionHelper.RsaWithRsaParameterKey rsaParams, AsymmetricEncryptionHelper.RsaWithRsaParameterKey digitalSignature)
        {
            // Decrypt AES Key with RSA and then decrypt data with AES.
            var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey);

            using (var hmac = new HMACSHA256(decryptedSessionKey))
            {
                var hmacToCheck = hmac.ComputeHash(encryptedPacket.EncryptedData);

                if (!Compare(encryptedPacket.Hmac, hmacToCheck))
                {
                    throw new CryptographicException("HMAC for decryption does not match encrypted packet.");
                }

                if (!digitalSignature.VerifySignature(encryptedPacket.Hmac,
                                                      encryptedPacket.Signature))
                {
                    throw new CryptographicException(
                              "Digital Signature can not be verified.");
                }
            }

            var decryptedData = SymmetricEncryptionHelper.AesEncryption.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey, encryptedPacket.Iv);

            return(decryptedData);
        }
コード例 #10
0
ファイル: TSCencSession.cs プロジェクト: anomous/JuvoPlayer
        public void OneTimeSetUp()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            savedLoggerManager = LoggerManager.ResetForTests();
            LoggerManager.Configure("JuvoPlayer=Verbose", CreateLoggerFunc);

            var assembly          = Assembly.GetExecutingAssembly();
            var drmInitDataStream = assembly.GetManifestResourceStream("JuvoPlayer.TizenTests.res.drm.google_dash_encrypted_init_data");

            using (var reader = new BinaryReader(drmInitDataStream))
            {
                initData = reader.ReadBytes((int)drmInitDataStream.Length);
            }

            Assert.That(initData, Is.Not.Null);

            var encryptedPacketStream =
                assembly.GetManifestResourceStream(
                    "JuvoPlayer.TizenTests.res.drm.google_dash_encrypted_video_packet_pts_10_01.xml");
            XmlSerializer serializer = new XmlSerializer(typeof(EncryptedPacket));

            encryptedPacket = (EncryptedPacket)serializer.Deserialize(encryptedPacketStream);

            Assert.That(encryptedPacket, Is.Not.Null);
        }
コード例 #11
0
        private void RefusePipe(UInt32 id, RefusePipe.RefusalReason reason)
        {
            var p = new EncryptedPacket(mTunnel.ID, id);

            p.RPCs.Add(new RefusePipe(id, reason));
            mTunnel.EncryptAndSendPacket(p);
        }
コード例 #12
0
        public void HandleOpenPipeRequest()
        {
            //tests that the control pipe both opens a new pipe and sends an ack
            bool trigger1, trigger2;

            trigger1 = trigger2 = false;
            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count >= 1);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.AckPipe);
                trigger1 = true;
            });

            tunnel.PipeInterceptor(connection =>
            {
                Assert.That(connection.ID == 100);
                trigger2 = true;
            });
            ControlPipe     c      = new ControlPipe(tunnel);
            EncryptedPacket packet = new EncryptedPacket(tunnel.ID, 0);

            packet.RPCs.Add(new CreateAnonymousPipe(PipeType.Duplex.ToString(), 100));
            c.HandlePacket(packet);

            Assert.IsTrue(trigger1 && trigger2, "One of the triggers was not called");
        }
コード例 #13
0
        /// <summary>
        ///     Opens a pipe request with the other side of the tunnel.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        private PipeBase OpenPipe(PipeType type, UInt32 id = 0)
        {
            //the connecting party doesn't care about the pipe ID.
            if (id == 0)
            {
                id = BitConverter.ToUInt32(SodiumCore.GetRandomBytes(4), 0);
            }
            IHasSerializationTag c    = new CreateAnonymousPipe(type.ToString(), id);
            PipeBase             pipe = null;

            switch (type)
            {
            case PipeType.Control:
                throw new NotSupportedException(
                          "Cannot create a new control pipe where on a tunnel that already has a control pipe");

            case PipeType.Duplex:
                pipe = new DuplexPipe(this.mTunnel, id);
                break;

            default:
                throw new ArgumentOutOfRangeException("type");
            }
            this.requestedPipes.Add(id, pipe);
            EncryptedPacket packet = new EncryptedPacket(this.mTunnel.ID, this.ID);

            packet.RPCs.Add(c);
            this.mTunnel.EncryptAndSendPacket(packet);
            return(pipe);
        }
コード例 #14
0
ファイル: EsStream.cs プロジェクト: anomous/JuvoPlayer
        private void PushEncryptedPacket(EncryptedPacket dataPacket, CancellationToken token)
        {
            using (var decryptedPacket = dataPacket.Decrypt(token) as DecryptedEMEPacket)
            {
                if (decryptedPacket == null)
                {
                    logger.Error($"{dataPacket.StreamType}: Non an EME Packet!");
                    return;
                }

                var esPacket = decryptedPacket.ESDecryptedPacket();

                // Continue pushing packet till success or terminal failure
                bool doRetry;
                do
                {
                    var res = player.SubmitPacket(esPacket);

                    // reset unmanaged handle on successful submit
                    if (res == ESPlayer.SubmitStatus.Success)
                    {
                        decryptedPacket.CleanHandle();
                    }

                    doRetry = ShouldRetry(res, token);

                    logger.Debug(
                        $"{esPacket.type}: ({!doRetry}/{res}) PTS: {esPacket.pts.FromNano()} Duration: {esPacket.duration.FromNano()} Handle: {esPacket.handle} HandleSize: {esPacket.handleSize}");
                } while (doRetry && !token.IsCancellationRequested);
            }
        }
コード例 #15
0
        public void OnAppendPacket_WhenDrmSessionIsConfigured_CallsPlayerAdapter()
        {
            var codecExtraDataHandlerStub = Substitute.For <ICodecExtraDataHandler>();

            var drmSessionStub = CreateDrmSessionFake();

            var drmManagerStub = CreateDrmManagerFake(drmSessionStub);

            var playerMock = Substitute.For <IPlayer>();

            using (var stream = CreatePacketStream(StreamType.Audio, playerMock, drmManagerStub, codecExtraDataHandlerStub))
            {
                var packet = new EncryptedPacket()
                {
                    StreamType = StreamType.Audio
                };
                var config      = new AudioStreamConfig();
                var drmInitData = new DRMInitData();

                stream.OnStreamConfigChanged(config);
                stream.OnDRMFound(drmInitData);
                stream.OnAppendPacket(packet);

                playerMock.Received().AppendPacket(Arg.Any <Packet>());
            }
        }
コード例 #16
0
        private void OnPacketRecieved(IAsyncResult ar)
        {
            EncryptedPacket p = (EncryptedPacket)ar.AsyncState;

            p.TruncateRaw((UInt16)socket.EndReceiveFrom(ar, ref p.sender));
            ThreadPool.QueueUserWorkItem(new WaitCallback(HandlePacket), p);
            readerEvent.Set();
        }
コード例 #17
0
        private void SendRefuse(UInt32 rpid)
        {
            Refuse          refuse = new Refuse(rpid);
            EncryptedPacket p      = new EncryptedPacket(this.mTunnel.ID, this.ID);

            p.RPCs.Add(refuse);
            this.mTunnel.EncryptAndSendPacket(p);
        }
コード例 #18
0
        private void SendOk(UInt32 rpid)
        {
            OkRPC           ok = new OkRPC(rpid);
            EncryptedPacket p  = new EncryptedPacket(this.mTunnel.ID, this.ID);

            p.RPCs.Add(ok);
            this.mTunnel.EncryptAndSendPacket(p);
        }
コード例 #19
0
        public void Decrypt_Should_Throw_Crypto_Exception_If_Encrypted_Data_Was_Changed()
        {
            EncryptedPacket packet = ValidMessagePacket;

            packet.EncryptedData = new byte[256];

            Assert.That(() => { HybridEncryption.Decrypt(packet, asymmetricPublicKey); }, Throws.InstanceOf(typeof(CryptoException)));
        }
コード例 #20
0
        public void HandleRekey()
        {
            //A rekey cannot happen until a prepare rekey rpc has been sent (note that they can be send together)
            //todo: add a test to send a prepare rekey and rekey together
            bool trigger1, trigger2, trigger3;

            trigger1 = trigger2 = trigger3 = false;
            KeyPair      pair         = Sodium.PublicKeyBox.GenerateKeyPair();
            PrepareRekey prepareRekey = new PrepareRekey(pair.PublicKey);
            RekeyNow     rekey        = new RekeyNow();

            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count > 0);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.Refuse);
                Refuse rpc = (Refuse)p.RPCs.First;
                trigger1   = true;
            });
            ControlPipe     c      = new ControlPipe(tunnel);
            EncryptedPacket packet = new EncryptedPacket(tunnel.ID, 0);

            packet.RPCs.Add(rekey);
            c.HandlePacket(packet);
            Assert.IsTrue(trigger1, "Refuse block never called");

            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count > 0);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.RekeyResponse);
                RekeyResponse ok = (RekeyResponse)p.RPCs.First;
                Assert.IsTrue(ok.NextPublicKey.Length == 32);
                trigger2 = true;
            });


            packet = new EncryptedPacket(tunnel.ID, 0);
            packet.RPCs.Add(new PrepareRekey(new byte[] { 1, 2, 3 }));
            c.HandlePacket(packet);
            Assert.IsTrue(trigger2, "Rekey ack block never called");

            tunnel.PacketInterceptor(p =>
            {
                Assert.That(p.RPCs.Count > 0);
                Assert.That(p.RPCs.First.SerializationTag == (byte)RPCType.Ok);
                OkRPC ok = (OkRPC)p.RPCs.First;
                Assert.IsTrue(ok.RPCID == rekey.RequestID);
                trigger3 = true;
            });

            packet = new EncryptedPacket(tunnel.ID, 0);
            packet.RPCs.Add(rekey);
            c.HandlePacket(packet);



            Assert.IsTrue(trigger1, "Rekey now block never called");
            Assert.IsTrue(trigger3);
        }
コード例 #21
0
        public void Can_Recover_Encrypted_File()
        {
            byte[]          fileBytes       = Random.GetNumbers(2048);
            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            byte[] decryptedBytes = HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);

            CollectionAssert.AreEqual(fileBytes, decryptedBytes);
        }
コード例 #22
0
        public void Encryption_Generates_Different_Hmac_Each_Time()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            EncryptedPacket encryptedPacket1 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);
            EncryptedPacket encryptedPacket2 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            CollectionAssert.AreNotEqual(encryptedPacket1.Hmac, encryptedPacket2.Hmac);
        }
コード例 #23
0
        public void Add_Should_Throw_ArgumentException_If_Id_Already_Exists()
        {
            EncryptedPacket newEncryptedPacket = ValidEncryptedPacket;

            Context.EncryptedPackets.Add(newEncryptedPacket);
            Context.SaveChanges();

            Assert.That(() => encryptedPacketRepository.Add(newEncryptedPacket), Throws.ArgumentException);
        }
コード例 #24
0
        public override void EncryptAndSendPacket(EncryptedPacket p)
        {
            var handle = this.packetHandle;

            if (handle != null)
            {
                handle.Invoke(p);
            }
        }
コード例 #25
0
        public void Encryption_Generates_New_Aes_Key_Each_Time()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            EncryptedPacket encryptedPacket1 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);
            EncryptedPacket encryptedPacket2 = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            CollectionAssert.AreNotEqual(encryptedPacket1.EncryptedSessionKey, encryptedPacket2.EncryptedSessionKey);
        }
コード例 #26
0
 public new void  HandlePacket(EncryptedPacket p)
 {
     if (mTunnelDirectory.TunnelIDExists(p.TID))
     {
         TunnelBase tunnel;
         mTunnelDirectory.Get(p.TID, out tunnel);
         tunnel.HandleIncomingPacket(p);
     }
 }
コード例 #27
0
        public byte[] DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams)
        {
            var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey);


            var decryptedData = _aes.Decrypt(encryptedPacket.EncryptedData, decryptedSessionKey,
                                             encryptedPacket.Iv, encryptedPacket.Tag, null);

            return(decryptedData);
        }
コード例 #28
0
ファイル: JsonHelpers.cs プロジェクト: solari23/Aegis
        /// <summary>
        /// Decrypts and deserializes an encrypted JSON object.
        /// </summary>
        /// <typeparam name="T">The type of the object to deserialize.</typeparam>
        /// <param name="encryptedData">The encrypted object data.</param>
        /// <param name="key">The archive's decryption key to use.</param>
        /// <param name="securitySettings">The archive's security settings.</param>
        /// <returns>The requested deserialized object.</returns>
        public static T DecryptAndDeserialize <T>(
            EncryptedPacket encryptedData,
            ArchiveKey key,
            SecuritySettings securitySettings)
        {
            var cryptoStrategy = CryptoHelpers.GetCryptoStrategy(securitySettings.EncryptionAlgo);
            var rawData        = key.Decrypt(cryptoStrategy, encryptedData);

            return(JsonSerializer.Deserialize <T>(rawData));
        }
コード例 #29
0
        public byte[] DecryptData(EncryptedPacket encryptedPacket, RSAWithRSAParameterKey rsaParams)
        {
            // Decrypt AES Key with RSA.
            var decryptedSessionKey = rsaParams.DecryptData(encryptedPacket.EncryptedSessionKey);

            // Decrypt our data with  AES using the decrypted session key.
            var decryptedData = _aes.Decrypt(encryptedPacket.EncryptedData,
                                             decryptedSessionKey, encryptedPacket.Iv);

            return(decryptedData);
        }
コード例 #30
0
        /// <inheritdoc />
        public NewEncryptedPacketModel(EncryptedPacket encryptedPacket, int receiverId)
        {
            ReceiverId = receiverId;

            DataType            = encryptedPacket.DataType;
            EncryptedData       = encryptedPacket.EncryptedData;
            EncryptedSessionKey = encryptedPacket.EncryptedSessionKey;
            Hmac      = encryptedPacket.Hmac;
            Iv        = encryptedPacket.Iv;
            Signature = encryptedPacket.Signature;
        }