Exemplo n.º 1
0
        public TradfriAuth GenerateAppSecret(string GatewaySecret, string applicationName)
        {
            Response resp = new Response(StatusCode.Valid);

            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(GatewaySecret)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));
            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);

            ep.Start();

            Request r = new Request(Method.POST);

            r.SetUri($"coaps://{_gatewayIp}" + $"/{(int)TradfriConstRoot.Gateway}/{(int)TradfriConstAttr.Auth}/");
            r.EndPoint   = ep;
            r.AckTimeout = 5000;
            r.SetPayload($@"{{""{(int)TradfriConstAttr.Identity}"":""{applicationName}""}}");

            r.Send();
            resp = r.WaitForResponse();

            if ((int)resp.StatusCode != 201)
            {
                RequestException <Response> .ConvertToException(MapToHttpStatusCode(resp.StatusCode), resp.StatusCode.ToString(), resp.UriQuery, "", resp.ResponseText, resp);
            }

            return(Convert <TradfriAuth>(resp.PayloadString));
        }
Exemplo n.º 2
0
        public static TradfriAuth GeneratePsk(string gatwayIp, string appName, string secret)
        {
            try
            {
                var authKey = new OneKey();
                authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(secret)));
                authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));
                var ep = new DTLSClientEndPoint(authKey);
                ep.Start();

                var request = new Request(Method.POST);
                request.SetUri($"coaps://{gatwayIp}" + $"/{(int)TradfriConstRoot.Gateway}/{(int)TradfriConstAttribute.Auth}/");
                request.EndPoint   = ep;
                request.AckTimeout = 5000;
                request.SetPayload($@"{{""{(int)TradfriConstAttribute.Identity}"":""{appName}""}}");

                request.Send();
                var resp = request.WaitForResponse(5000);
                if (resp == null)
                {
                    return(null);
                }

                return(JsonConvert.DeserializeObject <TradfriAuth>(resp.PayloadString));
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 3
0
        public TradFriAuth GeneratePSK(string GatewaySecret, string applicationName)
        {
            Response resp = new Response(StatusCode.Valid);

            try
            {
                OneKey authKey = new OneKey();
                authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(GatewaySecret)));
                authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));
                DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);
                ep.Start();

                Request r = new Request(Method.POST);
                r.SetUri($"coaps://{GatewayIp}" + $"/{(int)TradFriConstRoot.Gateway}/{(int)TradFriConstAttr.Auth}/");
                r.EndPoint   = ep;
                r.AckTimeout = 5000;
                r.SetPayload($@"{{""{(int)TradFriConstAttr.Identity}"":""{applicationName}""}}");

                r.Send();
                resp = r.WaitForResponse(5000);

                return(JsonConvert.DeserializeObject <TradFriAuth>(resp.PayloadString));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);

                var content = JsonConvert.DeserializeObject <dynamic>(resp.PayloadString);
                return(new TradFriAuth());
            }
        }
Exemplo n.º 4
0
            public void GetRpkKey(RawPublicKey rpk)
            {
                AsymmetricKeyParameter key;

                try {
                    key = PublicKeyFactory.CreateKey(rpk.SubjectPublicKeyInfo());
                }
                catch (Exception e) {
                    throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
                }

                if (key is ECPublicKeyParameters)
                {
                    ECPublicKeyParameters ecKey = (ECPublicKeyParameters)key;

                    string s      = ecKey.AlgorithmName;
                    OneKey newKey = new OneKey();
                    newKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_EC);
                    if (ecKey.Parameters.Curve.Equals(NistNamedCurves.GetByName("P-256").Curve))
                    {
                        newKey.Add(CoseKeyParameterKeys.EC_Curve, GeneralValues.P256);
                    }

                    newKey.Add(CoseKeyParameterKeys.EC_X, CBORObject.FromObject(ecKey.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned()));
                    newKey.Add(CoseKeyParameterKeys.EC_Y, CBORObject.FromObject(ecKey.Q.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned()));

                    if (_serverKeys != null)
                    {
                        foreach (OneKey k in _serverKeys)
                        {
                            if (k.Compare(newKey))
                            {
                                AuthenticationKey = k;
                                return;
                            }
                        }
                    }

                    TlsEvent ev = new TlsEvent(TlsEvent.EventCode.ServerCertificate)
                    {
                        KeyValue = newKey
                    };

                    EventHandler <TlsEvent> handler = TlsEventHandler;
                    if (handler != null)
                    {
                        handler(this, ev);
                    }

                    if (!ev.Processed)
                    {
                        //                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                    }
                }
                else
                {
                    // throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }
            }
Exemplo n.º 5
0
        public void OneTimeSetup()
        {
            RpkOneKey = OneKey.GenerateKey(AlgorithmValues.ECDSA_256, GeneralValues.KeyType_EC, "P-256");

            PskOneKey = new OneKey();
            PskOneKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskOneKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[10]));
        }
Exemplo n.º 6
0
        private static OneKey GetKey(string applicationId, string apiKey)
        {
            var authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(apiKey)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(applicationId)));
            return(authKey);
        }
Exemplo n.º 7
0
        public void Setup()
        {
            keyOctet = new OneKey();
            keyOctet.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            keyOctet.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(octetKeyValue));
            keyOctet.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(octetKeyID));

            keyEdDSA = OneKey.GenerateKey(null, GeneralValues.KeyType_EC, "P-256");
            keyDSA   = OneKey.GenerateKey(null, GeneralValues.KeyType_OKP, "Ed25519");
        }
        public static void OneTimeSetup(TestContext ctx)
        {
#if SUPPORT_RPK
            RpkOneKey = OneKey.GenerateKey(AlgorithmValues.ECDSA_256, GeneralValues.KeyType_EC, "P-256");
#endif

            PskOneKey = new OneKey();
            PskOneKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskOneKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[10]));
        }
Exemplo n.º 9
0
        public static void Main(String[] args)
        {
            KeySet keys = new KeySet();

            OneKey key = new OneKey();

            key.Add(CoseKeyKeys.KeyType, COSE.GeneralValues.KeyType_Octet);
            key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("password")));
            key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("sesame")));
            keys.AddKey(key);


            CoapServer server = new CoapServer();

            // server.AddEndPoint(new TcpEndPoint(5683));
            server.AddEndPoint(new DTLSEndPoint(null, keys, 5684));

            server.Add(new HelloWorldResource("hello"));
            server.Add(new FibonacciResource("fibonacci"));
            server.Add(new StorageResource("storage"));
            server.Add(new ImageResource("image"));
            server.Add(new MirrorResource("mirror"));
            server.Add(new LargeResource("large"));
            server.Add(new CarelessResource("careless"));
            server.Add(new SeparateResource("separate"));
            server.Add(new TimeResource("time"));

            try
            {
                server.Start();

                Console.Write("CoAP server [{0}] is listening on", server.Config.Version);

                foreach (var item in server.EndPoints)
                {
                    Console.Write(" ");
                    Console.Write(item.LocalEndPoint);
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
            server.Stop();
        }
Exemplo n.º 10
0
        static void GenerateKeys(string fileName)
        {
            if (fileName == null)
            {
                fileName = "ServerKeys.cbor";
            }

            KeySet keys = new KeySet();
            OneKey key;

            for (int i = 0; i < 4; i++)
            {
                key = new OneKey();
                key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                if (i == 3)
                {
                    key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Key#2")));
                }
                else
                {
                    key.Add(CoseKeyKeys.KeyIdentifier,
                            CBORObject.FromObject(Encoding.UTF8.GetBytes("Key#" + i.ToString())));
                }
                if (i == 3)
                {
                    key.Add(CoseKeyKeys.Algorithm, AlgorithmValues.AES_CCM_64_128_128);
                }
                else
                {
                    key.Add(CoseKeyKeys.Algorithm, AlgorithmValues.AES_CCM_64_64_128);
                }
                key.Add(CBORObject.FromObject("KDF"), AlgorithmValues.dir_kdf);
                key.Add(CBORObject.FromObject("SenderID"), CBORObject.FromObject(Encoding.UTF8.GetBytes("client")));
                key.Add(CBORObject.FromObject("RecipID"), CBORObject.FromObject(Encoding.UTF8.GetBytes("server")));
                byte[] keyValue = new byte[35];
                for (int j = 0; j < keyValue.Length; j++)
                {
                    keyValue[j] = (byte)(((i + 1) * (j + 1)));
                }
                key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(keyValue));

                keys.AddKey(key);
            }

            FileStream fs = new FileStream(fileName, FileMode.Create);

            using (BinaryWriter writer = new BinaryWriter(fs)) {
                writer.Write(keys.EncodeToBytes());
                writer.Close();
            }

            Environment.Exit(0);
        }
        public void ConnectPSK(string GatewaySecret)
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(GatewaySecret)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);

            (Implementation as CoapImplementation)._coapClient = new CoapClient(new Uri($"coaps://{_gatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();
        }
Exemplo n.º 12
0
        public static void OneTimeSetup(TestContext ctx)
        {
            PskOne = new OneKey();
            PskOne.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskOne.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(PskOneName));
            PskOne.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("abcDEFghiJKL")));

            PskTwo = new OneKey();
            PskTwo.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskTwo.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(PskTwoName));
            PskTwo.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("12345678091234")));

            UserKeys = new KeySet();
            // UserKeys.AddKey(PskOne);
            // UserKeys.AddKey(PskTwo);
        }
Exemplo n.º 13
0
        public IGateway Connect(string psk)
        {
            _logger.LogInformation($"Connecting to {_ipAddress} as \"{_clientIdentity}\" with PSK \"{psk}\"");

            var authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(psk)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(_clientIdentity)));

            var clientEndPoint = new DTLSClientEndPoint(authKey);

            clientEndPoint.Start();

            return(new Gateway(clientEndPoint, new Uri($"coaps://{_ipAddress}"), _logger));
        }
Exemplo n.º 14
0
        public void Connect()
        {
            OneKey userKey = new OneKey();

            userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(PreSharedKey)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(userKey);
            CoapClient         cc = new CoapClient(new Uri($"coaps://{GatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();
            Client = cc;
        }
Exemplo n.º 15
0
        public string GeneratePsk(string gatewaySecret)
        {
            try
            {
                _logger.LogInformation($"Connecting to {_ipAddress} as \"{_clientIdentity}\" to generate new PSK");

                var authKey = new OneKey();
                authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(gatewaySecret)));
                authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));
                using (var clientEndPoint = new DTLSClientEndPoint(authKey))
                {
                    clientEndPoint.Start();

                    var authRequest = new AuthRequest {
                        Identity = _clientIdentity
                    };

                    var request = new Request(Method.POST)
                    {
                        EndPoint   = clientEndPoint,
                        AckTimeout = 5000
                    };

                    request.SetUri($"coaps://{_ipAddress}/{(int)RequestRoot.Gateway}/{(int)TradfriAttribute.Auth}/");
                    string json = Json.Serialize(authRequest);
                    request.SetPayload(json);
                    request.Send();

                    Response response = request.WaitForResponse(5000);
                    if (response == null)
                    {
                        throw new TradfriException("No response from gateway");
                    }

                    AuthResponse authResponse = Json.Deserialize <AuthResponse>(response.PayloadString);

                    _logger.LogInformation($"PSK generated: \"{authResponse.Psk}\"");

                    return(authResponse.Psk);
                }
            }
            catch (Exception exception)
            {
                throw new TradfriException("Failed during authentication.", exception);
            }
        }
Exemplo n.º 16
0
        public void ConnectAppKey(string appKey, string applicationName)
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(appKey)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(applicationName)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);
            CoapClient         cc = new CoapClient(new Uri($"coaps://{_gatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();

            _coapClient = cc;
        }
        public Task <TradfriAuth> GenerateAppSecret(string GatewaySecret, string applicationName)
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(GatewaySecret)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));

            return(MakeRequest(new EndPointRequest <TradfriAuth>($"/{(int)TradfriConstRoot.Gateway}/{(int)TradfriConstAttr.Auth}/")
            {
                Content = $"{{\"{(int)TradfriConstAttr.Identity}\":\"{applicationName}\"}}",
                Method = Call.POST,
                DTLSEndPoint = new DTLSClientEndPoint(authKey),
                RequestHandler = (resp) => resp switch
                {
                    CreatedResponse crea => crea.Convert <TradfriAuth>(),
                    var other => throw other.ToException()
                }
            }));
Exemplo n.º 18
0
        public void Create_Test2()
        {
            OneKey key = new OneKey();

            key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_RSA);

            Exception e = Assert.Throws <Exception>(() => new EdhocInitiator(key));

            Assert.That(e.Message, Is.EqualTo("Unknown key type for secret"));
            ;
        }
Exemplo n.º 19
0
        public void Connect()
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(Psk)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(_name)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);
            CoapClient         cc = new CoapClient(new Uri($"coaps://{_gatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();

            GatewayController gc = new GatewayController(cc);

            GatewayInfo = gc.GetGatewayInfo();
            _client     = cc;
        }
Exemplo n.º 20
0
        public void SetupServer()
        {
            psk = new OneKey();
            psk.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            psk.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(new byte[3] {
                1, 2, 3
            }));
            psk.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[16] {
                16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
            }));

            _clientSignKey = OneKey.GenerateKey(null, GeneralValues.KeyType_EC, "P-256");
            _clientSignKey.Add(CoseKeyKeys.Algorithm, AlgorithmValues.ECDSA_256);
            _clientSignKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(new byte[] { 1, 101, 1 }));

            serverSignKey = OneKey.GenerateKey(null, GeneralValues.KeyType_EC, "P-256");
            // serverSignKey = OneKey.GenerateKey(null, GeneralValues.KeyType_OKP, "Ed25519");
            serverSignKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(new byte[] { 101, 1, 101 }));
            // serverSignKey.Add(CoseKeyKeys.Algorithm, AlgorithmValues.EdDSA);
            serverSignKey.Add(CoseKeyKeys.Algorithm, AlgorithmValues.ECDSA_256);
            CreateServer();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes the connection with the LAN controller
        /// </summary>
        /// <param name="endPoint">IP endpoint of the IKEA Tradfri LAN Controller</param>
        /// <param name="securityKey">Private security key found on the bottom of the LAN Controller</param>
        public static void InitializeConnection(IPEndPoint endPoint, string securityKey)
        {
            if (endPoint == null)
            {
                throw new ArgumentNullException(nameof(endPoint));
            }

            if (string.IsNullOrWhiteSpace(securityKey))
            {
                throw new ArgumentNullException(nameof(securityKey));
            }

            try
            {
                _controllerAddress     = endPoint;
                _connectionSecurityKey = securityKey;

                OneKey userKey = new OneKey();
                userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(_connectionSecurityKey)));

                CoAPEndPoint coapEndPoint = new DTLSClientEndPoint(userKey);
                _coapClient = new CoapClient(new Uri($"coaps://{_controllerAddress.Address}:{_controllerAddress.Port}/"))
                {
                    EndPoint = coapEndPoint
                };
                coapEndPoint.Start();

                // there has to be a GET operation to successfully open the connection

                _coapClient.UriPath = CommandConstants.UniqueDevices + "/";
                _coapClient.Get();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 22
0
        public void Derive_C_3_1()
        {
            byte[] salt    = new byte[] { 0x9e, 0x7c, 0xa9, 0x22, 0x23, 0x78, 0x63, 0x40 };
            byte[] groupId = new byte[] { 0x37, 0xcb, 0xf3, 0x21, 0x00, 0x17, 0xa2, 0xd3 };
            OneKey signKey = new OneKey();

            signKey.Add(COSE.CoseKeyKeys.Algorithm, COSE.AlgorithmValues.EdDSA);

            SecurityContext ctx = SecurityContext.DeriveGroupContext(_Doc_Secret, groupId, _Doc_SenderId,
                                                                     signKey[COSE.CoseKeyKeys.Algorithm], signKey,
                                                                     new byte[][] { _Doc_RecipientId }, new OneKey[] { signKey }, salt);

            CollectionAssert.AreEqual(ctx.Sender.Key, new byte[] { 0xaf, 0x2a, 0x13, 0x00, 0xa5, 0xe9, 0x57, 0x88, 0xb3, 0x56, 0x33, 0x6e, 0xee, 0xcd, 0x2b, 0x92 });
            CollectionAssert.AreEqual(ctx.Sender.BaseIV, new byte[] { 0x2c, 0xa5, 0x8f, 0xb8, 0x5f, 0xf1, 0xb8, 0x1c, 0x0b, 0x71, 0x81, 0xb8, 0x5e });
            CollectionAssert.AreEqual(ctx.Recipients[_Doc_RecipientId].Key, new byte[] { 0xe3, 0x9a, 0x0c, 0x7c, 0x77, 0xb4, 0x3f, 0x03, 0xb4, 0xb3, 0x9a, 0xb9, 0xa2, 0x68, 0x69, 0x9f });
            CollectionAssert.AreEqual(ctx.Recipients[_Doc_RecipientId].BaseIV, new byte[] { 0x2d, 0xa5, 0x8f, 0xb8, 0x5f, 0xf1, 0xb8, 0x1d, 0x0b, 0x71, 0x81, 0xb8, 0x5e });
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            Com.AugustCellars.CoAP.Log.LogManager.Level = LogLevel.None;
            ;
            String Server = "192.168.53.55:5684";

            OneKey userKey = new OneKey();

            userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            //userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("sesame")));
            // userKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("password")));

            CoapClient client = new CoapClient(new Uri($"coaps://{Server}/.well-known/core"));



            CoAPEndPoint ep = new DTLSClientEndPoint(userKey);

            client.EndPoint = ep;
            ep.Start();

            //

            Response r1 = client.Get();

            Console.WriteLine("Links = " + r1.PayloadString);

            //
            //           string str = "<//15001/65536>;ct=0;obs,<//15001/65537>;ct=0;obs,<//15004/136834>;ct=0;obs,<//15005/136834/217609>;ct=0;obs,<//15005/136834/218326>;ct=0;obs,<//15005/136834/224384>;ct=0;obs,<//15005/136834>;ct=0;obs,<//15001>;ct=0;obs,<//15001/reset>;ct=0,<//status>;ct=0;obs,<//15005>;ct=0;obs,<//15004>;ct=0;obs,<//15004/add>;ct=0,<//15004/remove>;ct=0,<//15006>;ct=0;obs,<//15011/15012>;ct=0;obs,<//15011/9034>;ct=0,<//15011/9030>;ct=0,<//15011/9031>;ct=0,<//15011/9063>;ct=0,<//15011/9033>;ct=0,<//15010>;ct=0;obs";
            //           IEnumerable<WebLink> links = LinkFormat.Parse(str);
            //           foreach(var item in links) Console.WriteLine(item);
            //

            LogManager.Level = LogLevel.None;


            IEnumerable <WebLink> items = client.Discover();

            foreach (var node in items)
            {
                Console.WriteLine($"Resource = {node}");

                client.UriPath = node.Uri;

                if (false && node.Attributes.Observable)
                {
                    CoapClient c2 = new CoapClient()
                    {
                        EndPoint = client.EndPoint,
                        Uri      = client.Uri,
                        UriPath  = node.Uri
                    };
                    Console.WriteLine("Observe it");
                    CoapObserveRelation relation1 = c2.Observe(r => { EventIn(node.Uri, r); });
                }
                else
                {
                    Response response = client.Get();

                    Console.WriteLine("   Payload: " + response.PayloadString);
                    Console.WriteLine();
                }
            }

            client.Uri     = new Uri($"coaps://{Server}");
            client.UriPath = "/15004/166412";
            client.Get();
            Response rep = client.Put("{ \"5850\":1}");

            Thread.Sleep(3000);

            //rep = client.Get();
            Console.WriteLine(rep.PayloadString);

            client.UriPath = "/15001/65537";
            ;

            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(3000);
                client.Put("{ \"5851\":127}");

                Thread.Sleep(3000);
                client.Put("{ \"3311\":[{ \"5851\":0}]}");

                Thread.Sleep(3000);
                client.Put("{ \"3311\":[{ \"5851\":255}]}");
            }


            ep.Stop();
        }
Exemplo n.º 24
0
        OneKey LoadKey(CBORObject obj)
        {
            OneKey     newKey = new OneKey();
            CBORObject kty;

            switch (obj["kty"].AsString())
            {
            case "oct":
                kty = GeneralValues.KeyType_Octet;
                break;

            case "EC":
                kty = GeneralValues.KeyType_EC;
                break;

            default:
                throw new Exception("Unknown key type " + obj["cty"].AsString());
            }

            foreach (CBORObject key in obj.Keys)
            {
                CBORObject value = obj[key];
                CBORObject key2  = key;

                if (key.AsString().EndsWith("_hex"))
                {
                    value = CBORObject.FromObject(FromHex(value.AsString()));
                    key2  = CBORObject.FromObject(key.AsString().Substring(0, key.AsString().Length - 4));
                }

                key2 = MapKey(key2);
                if (key2.Equals(CoseKeyKeys.KeyType))
                {
                    value = kty;
                }
                else if (key2.Equals(CoseKeyKeys.KeyIdentifier))
                {
                    value = CBORObject.FromObject(Encoding.UTF8.GetBytes(value.AsString()));
                }
                else if (key2.Equals(CoseKeyKeys.Algorithm))
                {
                    value = MapAlgorithm(value.AsString());
                }
                else if (kty.Equals(GeneralValues.KeyType_EC) && key2.Equals(CoseKeyParameterKeys.EC_Curve))
                {
                    switch (value.AsString())
                    {
                    case "P-256":
                        value = GeneralValues.P256;
                        break;

                    default:
                        throw new Exception("Unknown curve " + value.AsString());
                    }
                }

                newKey.Add(key2, value);
            }

            return(newKey);
        }
Exemplo n.º 25
0
        public static void Main(String[] args)
        {
            String             method     = null;
            Uri                uri        = null;
            String             payload    = null;
            Boolean            loop       = false;
            Boolean            byEvent    = false;
            OneKey             authKey    = null;
            SecurityContext    oscoap     = null;
            SecurityContextSet contextSet = null;

            if (args.Length == 0)
            {
                PrintUsage();
            }

            Int32 index = 0;

            foreach (String arg in args)
            {
                if (arg[0] == '-')
                {
                    if (arg.Equals("-l"))
                    {
                        loop = true;
                    }
                    else if (arg.Equals("-e"))
                    {
                        byEvent = true;
                    }
                    else if (arg.StartsWith("-psk="))
                    {
                        if (authKey == null)
                        {
                            authKey = new OneKey();
                            authKey.Add(COSE.CoseKeyKeys.KeyType, COSE.GeneralValues.KeyType_Octet);
                        }
                        authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(arg.Substring(5))));
                    }
                    else if (arg.StartsWith("-psk-id="))
                    {
                        if (authKey == null)
                        {
                            authKey = new OneKey();
                            authKey.Add(COSE.CoseKeyKeys.KeyType, COSE.GeneralValues.KeyType_Octet);
                        }
                        authKey.Add(COSE.CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(arg.Substring(8))));
                    }
                    else if (arg.StartsWith("-oscoap="))
                    {
                        if (contextSet == null)
                        {
                            Console.WriteLine("Must have -oscoap-data before -oscoap");
                            Environment.Exit(1);
                        }

                        byte[] id = Encoding.UTF8.GetBytes(arg.Substring(8));

                        oscoap = contextSet.FindByGroupId(id).First();
                    }
                    else if (arg.StartsWith("-oscoap-data="))
                    {
                        contextSet = LoadContextSet(arg.Substring(13));
                    }
                    else
                    {
                        Console.WriteLine("Unknown option: " + arg);
                    }
                }
                else
                {
                    switch (index)
                    {
                    case 0:
                        method = arg.ToUpper();
                        break;

                    case 1:
                        try
                        {
                            uri = new Uri(arg);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Failed parsing URI: " + ex.Message);
                            Environment.Exit(1);
                        }
                        break;

                    case 2:
                        payload = arg;
                        break;

                    default:
                        Console.WriteLine("Unexpected argument: " + arg);
                        break;
                    }
                    index++;
                }
            }

            if (method == null || uri == null)
            {
                PrintUsage();
            }

            Request request = NewRequest(method);

            if (request == null)
            {
                Console.WriteLine("Unknown method: " + method);
                Environment.Exit(1);
            }

            if ("OBSERVE".Equals(method))
            {
                request.MarkObserve();
                loop = true;
            }
            else if ("DISCOVER".Equals(method) &&
                     (String.IsNullOrEmpty(uri.AbsolutePath) || uri.AbsolutePath.Equals("/")))
            {
                uri = new Uri(uri, "/.well-known/core");
            }

            CoAPEndPoint ep = null;

            if (uri.Scheme == "coaps")
            {
                if (authKey == null)
                {
                    Console.WriteLine("Must use the -psk option to provide an authentication key");
                    return;
                }
                ep = new DTLSClientEndPoint(authKey);
                ep.Start();
                request.EndPoint = ep;
            }

            request.URI = uri;
            if (payload != null)
            {
                request.SetPayload(payload, MediaType.TextPlain);
            }
            if (oscoap != null)
            {
                request.OscoapContext = oscoap;
            }

            // uncomment the next line if you want to specify a draft to use
            // request.EndPoint = CoAP.Net.EndPointManager.Draft13;

            Console.WriteLine(Utils.ToString(request));

            try
            {
                if (byEvent)
                {
                    request.Respond += delegate(Object sender, ResponseEventArgs e)
                    {
                        Response response = e.Response;
                        if (response == null)
                        {
                            Console.WriteLine("Request timeout");
                        }
                        else
                        {
                            Console.WriteLine(Utils.ToString(response));
                            Console.WriteLine("Time (ms): " + response.RTT);
                        }
                        if (!loop)
                        {
                            if (ep != null)
                            {
                                ep.Stop();
                            }
                            Environment.Exit(0);
                        }
                    };
                    request.Send();
                    while (true)
                    {
                        Console.ReadKey();
                    }
                }
                else
                {
                    // uncomment the next line if you need retransmission disabled.
                    // request.AckTimeout = -1;

                    request.Send();

                    do
                    {
                        Console.WriteLine("Receiving response...");

                        Response response = null;
                        response = request.WaitForResponse();

                        if (response == null)
                        {
                            Console.WriteLine("Request timeout");
                            break;
                        }
                        else
                        {
                            Console.WriteLine(Utils.ToString(response));
                            Console.WriteLine("Time elapsed (ms): " + response.RTT);

                            if (response.ContentType == MediaType.ApplicationLinkFormat)
                            {
                                IEnumerable <WebLink> links = LinkFormat.Parse(response.PayloadString);
                                if (links == null)
                                {
                                    Console.WriteLine("Failed parsing link format");
                                    Environment.Exit(1);
                                }
                                else
                                {
                                    Console.WriteLine("Discovered resources:");
                                    foreach (var link in links)
                                    {
                                        Console.WriteLine(link);
                                    }
                                }
                            }
                        }
                    } while (loop);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed executing request: " + ex.Message);
                Console.WriteLine(ex);
                if (ep != null)
                {
                    ep.Stop();
                }
                Environment.Exit(1);
            }
        }
Exemplo n.º 26
0
        static CoapServer SetupServer(ICoapConfig config, EndPoint endPoint, int port, KeySet dtlsSignKeys,
                                      KeySet dtlsValidateKeys)
        {
            //
            //

            CoapServer   server = new CoapServer(config, endPoint, port);
            DTLSEndPoint ep2    = new DTLSEndPoint(dtlsSignKeys, dtlsValidateKeys, port + 1);

            server.AddEndPoint(ep2);

            IResource root = new HelloWorldResource("hello", true);

            server.Add(root);

            IResource x = new OscoapTest("coap");

            root.Add(x);

            x = new OscoapTest("1");
            root.Add(x);

            root.Add(new OscoapTest("2"));
            root.Add(new OscoapTest("3"));
            root.Add(new OscoapTest("6"));
            root.Add(new OscoapTest("7"));

            server.Add(new OscoapTest("test"));

            server.Add(new TimeResource("observe"));

            server.Add(new LargeResource("LargeResource"));

#if DEV_VERSION
            AceTest.Setup(server, "RS1");
#if false
            server.Add(new Com.AugustCellars.CoAP.EDHOC.EdhocResource(edhocKeys, edhocSign));
#endif

            //  Setup the ACE resources
            string UseAsServer = "coaps://localhost:5689/token";
            // UseAsServer = "coaps://31.133.142.90/token";
            // UseAsServer = "coaps://31.133.134.176/token";

            KeySet myDecryptKeySet = new KeySet();
            OneKey key             = new OneKey();

            key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }));
            key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("SERVER_KID")));
            key.Add(CoseKeyKeys.Algorithm, AlgorithmValues.AES_CCM_64_128_128);

            myDecryptKeySet.AddKey(key);

            key = new OneKey();
            key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[] { (byte)'a', (byte)'b', (byte)'c', 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }));
            key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(new byte[] { 0x70, 0x63, 0x6F, 0x61, 0x70, 0x3A, 0x2F, 0x2F, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x68, 0x6F, 0x73, 0x74 }));
            key.Add(CoseKeyKeys.Algorithm, CBORObject.FromObject(5));
            myDecryptKeySet.AddKey(key);

            AuthZ authZ = new AuthZ(myDecryptKeySet, null);
            server.Add(authZ);
            AceOAuthTest r = new AceOAuthTest("ace-echo", true, true, UseAsServer);
            r.AuthTokenProcessor = authZ;
            server.Add(r);
            OscoapContexts = SecurityContextSet.AllContexts;
#endif

            // ep2.Add(new AceOAuthTest("ace/echo", true, true, null));

#if INCLUDE_RD
            ResourceDirectoryResource.CreateResources(server);
#endif

#if DEV_VERSION
            // server = new CoapServer(config);
            CoAPEndPoint tcp = new TcpEndPoint(port);
            tcp.Start();
            server.AddEndPoint(tcp);

            // server.Add(new HelloWorldResource("hello", false));
            // server.Add(new LargeResource("LargeResource"));
            server.Add(new LargeResource("ExtraLargeResource", 20 * 1024));
            server.Add(new StorageResource("StorageHere"));
            server.Start();

            // server = new CoapServer(config);
            tcp = new TLSEndPoint(dtlsSignKeys, dtlsValidateKeys, port + 1);
            tcp.Start();
            server.AddEndPoint(tcp);

            AceTest.Setup(server, "RS2");

            //server.Add(new HelloWorldResource("hello", false));
#endif

            server.Start();
            return(server);
        }