/// <summary>
        /// Connect to a group to start streaming
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="simulator"></param>
        /// <returns></returns>
        public async Task Connect(Guid entertainmentAreaId, bool simulator = false)
        {
            _simulator = simulator;
            var enableResult = await _localHueClient.SetStreamingAsync(entertainmentAreaId).ConfigureAwait(false);

            entConfigIdBytes = Encoding.ASCII.GetBytes(entertainmentAreaId.ToString().ToLowerInvariant());

            byte[] psk = FromHex(_clientKey);
            BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(_appKey, psk);

            var dtlsClient = new DtlsClient(null !, pskIdentity);

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom());

#if NET461
            _socket.Connect(IPAddress.Parse(_ip), 2100);
#else
            await _socket.ConnectAsync(IPAddress.Parse(_ip), 2100).ConfigureAwait(false);
#endif
            _udp = new UdpTransport(_socket);

            if (!simulator)
            {
                _dtlsTransport = clientProtocol.Connect(dtlsClient, _udp);
            }
        }
Esempio n. 2
0
 public DtlsClient(DatagramTransport datagramTransport, CertificateInfo certificateInfo, DtlsClientProtocol dtlsClientProtocol = null)
 {
     this.datagramTransport  = datagramTransport;
     this.dtlsClientProtocol = dtlsClientProtocol ?? new DtlsClientProtocol(new SecureRandom());
     tlsClient = new TlsClientImpl(certificateInfo);
     tlsClient.ServerCertificateInfoAvailable += TlsClient_ServerCertificateInfoAvailable;
 }
Esempio n. 3
0
        public void Connect(IPEndPoint remoteEP)
        {
            _socket.Connect(remoteEP);
            var udpTransport = new UdpTransport(_socket);
            var random       = new SecureRandom();
            var protocol     = new DtlsClientProtocol(random);
            var client       = new TlsClientImpl();

            _dtlsTransport = protocol.Connect(client, udpTransport);
        }
Esempio n. 4
0
        public Task ConnectAsync(CoapTransportLayerConnectOptions connectOptions, CancellationToken cancellationToken)
        {
            _udpTransport = new UdpTransport(connectOptions);

            var clientProtocol = new DtlsClientProtocol(new SecureRandom());
            var client         = new DtlsClient(ConvertProtocolVersion(DtlsVersion), (PreSharedKey)Credentials);

            _dtlsTransport = clientProtocol.Connect(client, _udpTransport);

            return(Task.FromResult(0));
        }
Esempio n. 5
0
        public bool DoHandshakeAsClient()
        {
            logger.LogDebug("DTLS commencing handshake as client.");

            if (!handshaking && !handshakeComplete)
            {
                this.startTime   = DateTime.Now;
                this.handshaking = true;
                SecureRandom       secureRandom   = new SecureRandom();
                DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
                try
                {
                    var client = (DtlsSrtpClient)connection;
                    // Perform the handshake in a non-blocking fashion
                    Transport = clientProtocol.Connect(client, this);

                    // Prepare the shared key to be used in RTP streaming
                    //client.PrepareSrtpSharedSecret();
                    // Generate encoders for DTLS traffic
                    if (client.GetSrtpPolicy() != null)
                    {
                        srtpDecoder  = GenerateRtpDecoder();
                        srtpEncoder  = GenerateRtpEncoder();
                        srtcpDecoder = GenerateRtcpDecoder();
                        srtcpEncoder = GenerateRtcpEncoder();
                    }

                    // Declare handshake as complete
                    handshakeComplete = true;
                    handshakeFailed   = false;
                    handshaking       = false;
                    // Warn listeners handshake completed
                    //UnityEngine.Debug.Log("DTLS Handshake Completed");

                    return(true);
                }
                catch (Exception excp)
                {
                    logger.LogWarning($"DTLS handshake as client failed. {excp.Message}");

                    // Declare handshake as failed
                    handshakeComplete = false;
                    handshakeFailed   = true;
                    handshaking       = false;
                    // Warn listeners handshake completed
                    //UnityEngine.Debug.Log("DTLS Handshake failed\n" + e);
                }
            }

            return(false);
        }
        private void EnsureConnected()
        {
            lock (_ensureConnectedLock)
            {
                if (_isConnected)
                {
                    return;
                }

                var udpClient = new UdpClient(Server, Port);

                var dtlsClientProtocol = new DtlsClientProtocol(new SecureRandom());
                _datagramTransport = dtlsClientProtocol.Connect(_tlsClient, new UdpDatagramTransport(udpClient, NetworkMtu));
                _isConnected       = true;
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Create the DTLS connection over a specific UDP channel.
        /// We already know what address we are going to use
        /// </summary>
        /// <param name="udpChannel">UDP channel to use</param>
        public void Connect(UDPChannel udpChannel)
        {
#if SUPPORT_TLS_CWT
            if (CwtTrustKeySet != null)
            {
                _client = new DtlsClient(null, _userKey, CwtTrustKeySet);
            }
            else
            {
#endif
            if (_userKey.PrivateKey.HasKeyType((int)GeneralValuesInt.KeyType_Octet))
            {
                CBORObject kid = _userKey.PrivateKey[CoseKeyKeys.KeyIdentifier];

                BasicTlsPskIdentity pskIdentity;
                pskIdentity = new BasicTlsPskIdentity(kid != null ? kid.GetByteString() : new byte[0],
                                                      _userKey.PrivateKey[CoseKeyParameterKeys.Octet_k].GetByteString());
                _client = new DtlsClient(null, pskIdentity);
            }
            else if (_userKey.PrivateKey.HasKeyType((int)GeneralValuesInt.KeyType_EC2))
            {
                _client = new DtlsClient(null, _userKey);
            }
#if SUPPORT_TLS_CWT
        }
#endif

            _client.TlsEventHandler += OnTlsEvent;

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom());

            _transport.UDPChannel = udpChannel;
            AuthenticationKey     = _userKey.PrivateKey;

            _listening = 1;
            DtlsTransport dtlsClient = clientProtocol.Connect(_client, _transport);
            _listening   = 0;
            _dtlsSession = dtlsClient;

            //  We are now in the world of a connected system -
            //  We need to do the receive calls

            new Thread(StartListen).Start();
        }
Esempio n. 8
0
        public async Task ConnectAsync(CoapTransportLayerConnectOptions connectOptions, CancellationToken cancellationToken)
        {
            if (connectOptions == null)
            {
                throw new ArgumentNullException(nameof(connectOptions));
            }

            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                _udpTransport = new UdpTransport(connectOptions);
                var clientProtocol = new DtlsClientProtocol(_secureRandom);
                _dtlsClient = new DtlsClient(ConvertProtocolVersion(DtlsVersion), (PreSharedKey)Credentials);

                using (cancellationToken.Register(() =>
                {
                    _udpTransport.Close();
                }))
                {
                    _dtlsTransport = await Task.Run(() => clientProtocol.Connect(_dtlsClient, _udpTransport), cancellationToken).ConfigureAwait(false);
                }
            }
            catch
            {
                _udpTransport?.Dispose();

                if (cancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                if (_dtlsClient.ReceivedAlert != 0)
                {
                    throw new DtlsException($"Received alert {AlertDescription.GetText(_dtlsClient.ReceivedAlert)}.", null)
                          {
                              ReceivedAlert = _dtlsClient.ReceivedAlert
                          };
                }

                throw;
            }
        }
Esempio n. 9
0
        public void TestClientServer()
        {
            SecureRandom secureRandom = new SecureRandom();

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
            DtlsServerProtocol serverProtocol = new DtlsServerProtocol(secureRandom);

            MockDatagramAssociation network = new MockDatagramAssociation(1500);

            Server server = new Server(serverProtocol, network.Server);

            Thread serverThread = new Thread(new ThreadStart(server.Run));

            serverThread.Start();

            DatagramTransport clientTransport = network.Client;

            clientTransport = new UnreliableDatagramTransport(clientTransport, secureRandom, 0, 0);

            clientTransport = new LoggingDatagramTransport(clientTransport, Console.Out);

            MockDtlsClient client = new MockDtlsClient(null);

            DtlsTransport dtlsClient = clientProtocol.Connect(client, clientTransport);

            for (int i = 1; i <= 10; ++i)
            {
                byte[] data = new byte[i];
                Arrays.Fill(data, (byte)i);
                dtlsClient.Send(data, 0, data.Length);
            }

            byte[] buf = new byte[dtlsClient.GetReceiveLimit()];
            while (dtlsClient.Receive(buf, 0, buf.Length, 100) >= 0)
            {
            }

            dtlsClient.Close();

            server.Shutdown(serverThread);
        }
Esempio n. 10
0
        /// <summary>
        /// Connect to a group to start streaming
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="simulator"></param>
        /// <returns></returns>
        public async Task Connect(string groupId, bool simulator = false)
        {
            _simulator = simulator;
            var enableResult = await _localHueClient.SetStreamingAsync(groupId).ConfigureAwait(false);

            byte[] psk = FromHex(_clientKey);
            BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(_appKey, psk);

            var dtlsClient = new DtlsClient(null !, pskIdentity);

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom());

            await _socket.ConnectAsync(IPAddress.Parse(_ip), 2100).ConfigureAwait(false);

            _udp = new UdpTransport(_socket);

            if (!simulator)
            {
                _dtlsTransport = clientProtocol.Connect(dtlsClient, _udp);
            }
        }
Esempio n. 11
0
        public void TestClientServer()
        {
            SecureRandom secureRandom = new SecureRandom();

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
            DtlsServerProtocol serverProtocol = new DtlsServerProtocol(secureRandom);

            MockDatagramAssociation network = new MockDatagramAssociation(1500);

            Server server = new Server(serverProtocol, network.Server);

            Thread serverThread = new Thread(new ThreadStart(server.Run));
            serverThread.Start();

            DatagramTransport clientTransport = network.Client;

            clientTransport = new UnreliableDatagramTransport(clientTransport, secureRandom, 0, 0);

            clientTransport = new LoggingDatagramTransport(clientTransport, Console.Out);

            MockDtlsClient client = new MockDtlsClient(null);

            DtlsTransport dtlsClient = clientProtocol.Connect(client, clientTransport);

            for (int i = 1; i <= 10; ++i)
            {
                byte[] data = new byte[i];
                Arrays.Fill(data, (byte)i);
                dtlsClient.Send(data, 0, data.Length);
            }

            byte[] buf = new byte[dtlsClient.GetReceiveLimit()];
            while (dtlsClient.Receive(buf, 0, buf.Length, 100) >= 0)
            {
            }

            dtlsClient.Close();

            server.Shutdown(serverThread);
        }
Esempio n. 12
0
        public void RunTest(TlsTestConfig config)
        {
            CheckDtlsVersion(config.clientMinimumVersion);
            CheckDtlsVersion(config.clientOfferVersion);
            CheckDtlsVersion(config.serverMaximumVersion);
            CheckDtlsVersion(config.serverMinimumVersion);

            SecureRandom secureRandom = new SecureRandom();

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
            DtlsServerProtocol serverProtocol = new DtlsServerProtocol(secureRandom);

            MockDatagramAssociation network = new MockDatagramAssociation(1500);

            TlsTestClientImpl clientImpl = new TlsTestClientImpl(config);
            TlsTestServerImpl serverImpl = new TlsTestServerImpl(config);

            Server server = new Server(this, serverProtocol, network.Server, serverImpl);

            Thread serverThread = new Thread(new ThreadStart(server.Run));

            serverThread.Start();

            Exception caught = null;

            try
            {
                DatagramTransport clientTransport = network.Client;

                if (TlsTestConfig.DEBUG)
                {
                    clientTransport = new LoggingDatagramTransport(clientTransport, Console.Out);
                }

                DtlsTransport dtlsClient = clientProtocol.Connect(clientImpl, clientTransport);

                for (int i = 1; i <= 10; ++i)
                {
                    byte[] data = new byte[i];
                    Arrays.Fill(data, (byte)i);
                    dtlsClient.Send(data, 0, data.Length);
                }

                byte[] buf = new byte[dtlsClient.GetReceiveLimit()];
                while (dtlsClient.Receive(buf, 0, buf.Length, 100) >= 0)
                {
                }

                dtlsClient.Close();
            }
            catch (Exception e)
            {
                caught = e;
                LogException(caught);
            }

            server.Shutdown(serverThread);

            // TODO Add checks that the various streams were closed

            Assert.AreEqual(config.expectFatalAlertConnectionEnd, clientImpl.FirstFatalAlertConnectionEnd, "Client fatal alert connection end");
            Assert.AreEqual(config.expectFatalAlertConnectionEnd, serverImpl.FirstFatalAlertConnectionEnd, "Server fatal alert connection end");

            Assert.AreEqual(config.expectFatalAlertDescription, clientImpl.FirstFatalAlertDescription, "Client fatal alert description");
            Assert.AreEqual(config.expectFatalAlertDescription, serverImpl.FirstFatalAlertDescription, "Server fatal alert description");

            if (config.expectFatalAlertConnectionEnd == -1)
            {
                Assert.IsNull(caught, "Unexpected client exception");
                Assert.IsNull(server.mCaught, "Unexpected server exception");
            }
        }
Esempio n. 13
0
        private void but_Click(object sender2, EventArgs e)
        {
            if (InputBox.Show("Server", "Server", ref address) != DialogResult.OK)
            {
                return;
            }
            if (InputBox.Show("Server port", "Server port", ref port) != DialogResult.OK)
            {
                return;
            }

            string username = Settings.Instance.GetString("ex_api_username");
            string token    = Settings.Instance.GetString("ex_api_psk");

            if (InputBox.Show("Username", "Username", ref username) != DialogResult.OK)
            {
                return;
            }
            if (InputBox.Show("Token", "Token", ref token) != DialogResult.OK)
            {
                return;
            }

            Settings.Instance["ex_api_address"] = address;
            Settings.Instance["ex_api_port"]    = port.ToString();

            Settings.Instance["ex_api_username"] = username;
            Settings.Instance["ex_api_psk"]      = token;

            Task.Run(() =>
            {
                try
                {
                    var psk       = new BasicTlsPskIdentity(username, token.MakeBytes());
                    var pskclient = new DTLSPsk(psk);

                    DtlsClientProtocol client   = new DtlsClientProtocol(new Org.BouncyCastle.Security.SecureRandom());
                    DatagramTransport transport = new UDPTransport(address, port);
                    var dtlstx = client.Connect(pskclient, transport);

                    MainV2.comPort.OnPacketReceived += (sender, message) =>
                    {
                        dtlstx.Send(message.buffer, 0, message.buffer.Length);
                    };

                    var buf = new byte[dtlstx.GetReceiveLimit()];

                    while (MainV2.comPort.BaseStream.IsOpen)
                    {
                        try
                        {
                            var read = dtlstx.Receive(buf, 0, buf.Length, 1000);
                            lock (MainV2.comPort.objlock)
                            {
                                if (MainV2.comPort.BaseStream.IsOpen)
                                {
                                    MainV2.comPort.BaseStream.Write(buf, 0, read);
                                }
                            }
                        }
                        catch (Exception ex) { }
                    }
                } catch (Exception ex) {
                    CustomMessageBox.Show(Strings.ERROR, ex.ToString());
                }
            });
        }
        private bool DoHandshakeAsClient(out string handshakeError)
        {
            handshakeError = null;

            logger.LogDebug("DTLS commencing handshake as client.");

            if (!_handshaking && !_handshakeComplete)
            {
                this._waitMillis  = RetransmissionMilliseconds;
                this._startTime   = System.DateTime.Now;
                this._handshaking = true;
                SecureRandom       secureRandom   = new SecureRandom();
                DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
                try
                {
                    var client = (DtlsSrtpClient)connection;
                    // Perform the handshake in a non-blocking fashion
                    Transport = clientProtocol.Connect(client, this);

                    // Prepare the shared key to be used in RTP streaming
                    //client.PrepareSrtpSharedSecret();
                    // Generate encoders for DTLS traffic
                    if (client.GetSrtpPolicy() != null)
                    {
                        srtpDecoder  = GenerateRtpDecoder();
                        srtpEncoder  = GenerateRtpEncoder();
                        srtcpDecoder = GenerateRtcpDecoder();
                        srtcpEncoder = GenerateRtcpEncoder();
                    }
                    // Declare handshake as complete
                    _handshakeComplete = true;
                    _handshakeFailed   = false;
                    _handshaking       = false;
                    // Warn listeners handshake completed
                    //UnityEngine.Debug.Log("DTLS Handshake Completed");

                    return(true);
                }
                catch (System.Exception excp)
                {
                    if (excp.InnerException is TimeoutException)
                    {
                        logger.LogWarning(excp, $"DTLS handshake as client timed out waiting for handshake to complete.");
                        handshakeError = "timeout";
                    }
                    else
                    {
                        handshakeError = "unknown";
                        if (excp is Org.BouncyCastle.Crypto.Tls.TlsFatalAlert)
                        {
                            handshakeError = (excp as Org.BouncyCastle.Crypto.Tls.TlsFatalAlert).Message;
                        }

                        logger.LogWarning(excp, $"DTLS handshake as client failed. {excp.Message}");
                    }

                    // Declare handshake as failed
                    _handshakeComplete = false;
                    _handshakeFailed   = true;
                    _handshaking       = false;
                    // Warn listeners handshake completed
                    //UnityEngine.Debug.Log("DTLS Handshake failed\n" + e);
                }
            }
            return(false);
        }
Esempio n. 15
0
        public void RunTest(TlsTestConfig config)
        {
            CheckDtlsVersion(config.clientMinimumVersion);
            CheckDtlsVersion(config.clientOfferVersion);
            CheckDtlsVersion(config.serverMaximumVersion);
            CheckDtlsVersion(config.serverMinimumVersion);

            SecureRandom secureRandom = new SecureRandom();

            DtlsClientProtocol clientProtocol = new DtlsClientProtocol(secureRandom);
            DtlsServerProtocol serverProtocol = new DtlsServerProtocol(secureRandom);

            MockDatagramAssociation network = new MockDatagramAssociation(1500);

            TlsTestClientImpl clientImpl = new TlsTestClientImpl(config);
            TlsTestServerImpl serverImpl = new TlsTestServerImpl(config);

            Server server = new Server(this, serverProtocol, network.Server, serverImpl);

            Thread serverThread = new Thread(new ThreadStart(server.Run));
            serverThread.Start();

            Exception caught = null;
            try
            {
                DatagramTransport clientTransport = network.Client;

                if (TlsTestConfig.DEBUG)
                {
                    clientTransport = new LoggingDatagramTransport(clientTransport, Console.Out);
                }

                DtlsTransport dtlsClient = clientProtocol.Connect(clientImpl, clientTransport);

                for (int i = 1; i <= 10; ++i)
                {
                    byte[] data = new byte[i];
                    Arrays.Fill(data, (byte)i);
                    dtlsClient.Send(data, 0, data.Length);
                }
    
                byte[] buf = new byte[dtlsClient.GetReceiveLimit()];
                while (dtlsClient.Receive(buf, 0, buf.Length, 100) >= 0)
                {
                }
    
                dtlsClient.Close();
            }
            catch (Exception e)
            {
                caught = e;
                LogException(caught);
            }

            server.Shutdown(serverThread);

            // TODO Add checks that the various streams were closed

            Assert.AreEqual(config.expectFatalAlertConnectionEnd, clientImpl.FirstFatalAlertConnectionEnd, "Client fatal alert connection end");
            Assert.AreEqual(config.expectFatalAlertConnectionEnd, serverImpl.FirstFatalAlertConnectionEnd, "Server fatal alert connection end");

            Assert.AreEqual(config.expectFatalAlertDescription, clientImpl.FirstFatalAlertDescription, "Client fatal alert description");
            Assert.AreEqual(config.expectFatalAlertDescription, serverImpl.FirstFatalAlertDescription, "Server fatal alert description");

            if (config.expectFatalAlertConnectionEnd == -1)
            {
                Assert.IsNull(caught, "Unexpected client exception");
                Assert.IsNull(server.mCaught, "Unexpected server exception");
            }
        }