Esempio n. 1
0
        public void MutiTierTest()
        {
            CoapClient client = new CoapClient(new Uri($"coap://localhost:{_port}/ps"));
            Response   resp   = client.Get();

            Assert.AreEqual(StatusCode.Content, resp.StatusCode);
            Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType);
            List <WebLink> links = LinkFormat.Parse(resp.PayloadString).ToList();

            Assert.AreEqual(0, links.Count);

            resp = client.Post($"<middle>;ct={MediaType.ApplicationLinkFormat}", MediaType.ApplicationLinkFormat);
            Assert.AreEqual(StatusCode.Created, resp.StatusCode);
            Assert.AreEqual("ps/middle", resp.LocationPath);

            client.UriPath = "/ps/middle";
            resp           = client.Post($"<topic1>;ct={MediaType.TextPlain}", MediaType.ApplicationLinkFormat);
            Assert.AreEqual(StatusCode.Created, resp.StatusCode);
            Assert.AreEqual("ps/middle/topic1", resp.LocationPath);

            resp = client.Post($"<topic2>;ct={MediaType.ApplicationCbor}", MediaType.ApplicationLinkFormat);
            Assert.AreEqual(StatusCode.Created, resp.StatusCode);
            Assert.AreEqual("ps/middle/topic2", resp.LocationPath);

            client.UriPath = "";
            resp           = client.Get();
            Assert.AreEqual(StatusCode.Content, resp.StatusCode);
            Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType);
            links = LinkFormat.Parse(resp.PayloadString).ToList();
            Assert.AreEqual(3, links.Count);
            string[] linkStrings = resp.PayloadString.Split(',');

            Assert.Contains("</ps/middle/topic2>;ct=60;obs", linkStrings);
            Assert.Contains("</ps/middle/topic1>;ct=0;obs", linkStrings);;
        }
        public void PostTo()
        {
            CoapClient c = new CoapClient(Program.Host)
            {
                UriPath  = "/.well-known/core",
                UriQuery = "ep=node1",
                Timeout  = 5000,
                EndPoint = EndPoints.First()
            };

            Response r = c.Post(new byte[] { }, MediaType.ApplicationLinkFormat);

            if (r == null)
            {
                Console.WriteLine("No response received");
            }
            else
            {
                if (r.StatusCode != StatusCode.Changed)
                {
                    Console.WriteLine("Incorrect response");
                }

                Console.WriteLine(Utils.ToString(r));
            }
        }
Esempio n. 3
0
        static void RunTest5_4_1()
        {
            CoapClient request = new CoapClient(Program.Host + "/oscore/hello/1")
            {
                Timeout = 2000
            };

            Response response = request.Post(new byte[] { 0x4a }, MediaType.TextPlain);

            if (response == null)
            {
                Console.WriteLine("Failed to receive response");
                return;
            }

            if (response.StatusCode != StatusCode.Changed)
            {
                Console.WriteLine($"Content type should be 2.04 not {response.StatusCode}");
            }

            if (response.PayloadSize != 1 || response.Payload[0] != 0x4a)
            {
                Console.WriteLine("Payload for the package is wrong - should be 0x4a");
            }

            Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");
        }
        static void RunTest4(string[] cmds)
        {
            //  Do it as a third party.
            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath  = ResourceRegister,
                UriQuery = "ep=node2",
                Timeout  = 20 * 1000
            };
            Response r1 = cl.Post(
                "</temp>;rt=\"temperature\";ct=0," +
                "</light>;rt=\"light-lux\";ct=0," +
                "</t>;anchor=\"sensors/temp\";rel=\"alternate\"," +
                "<http://www.example.com/sensors/t123>;anchor=\"sensors/temp\";rel=\"describedby\"",
                MediaType.ApplicationLinkFormat);

            if (r1 == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }

            Test4Location = r1.LocationPath;
            return;
        }
        static void ProductCall()
        {
            // Create a new client
            var client = new CoapClient();

            // Set the Uri to visit
            client.Uri = new Uri("coap://127.0.0.1:5683/products");

            // Build the data
            MemoryStream stream = new MemoryStream();

            // Example product
            dynamic product = new JObject();

            product.name  = "Example Product";
            product.price = 120.35;

            // Get JSON object from example product
            var response = client.Post(product.ToString(), MediaType.ApplicationJson);

            Console.WriteLine("Wrote product: {0}", product.ToString());

            // Get the response
            Console.WriteLine("Response from GET: {0}", response.PayloadString);
            Console.ReadLine();
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            Thread.Sleep(1000);

            CoapClient client = new CoapClient()
            {
                Uri     = new Uri("coap://localhost"),
                UriPath = "/ps"
            };

            Response resp = client.Get();

            Console.WriteLine($"Discover ==> {resp.ToString()}");


            resp = client.Post("<topic1>;ct=40", MediaType.ApplicationLinkFormat);
            Console.WriteLine($"Create topic1 ==> {resp.ToString()}");

            client.UriPath = "/ps/topic1";
            resp           = client.Post("<subtopic1>;ct=0;rt=temperature;obs", MediaType.ApplicationLinkFormat);
            Console.WriteLine($"Create subtopic1 ==> {resp.ToString()}");

            client.UriPath = "/ps";
            resp           = client.Get();
            Console.WriteLine($"Discover ==> {resp.PayloadString}");


            client.UriPath = "/ps/topic1/subtopic1";
            resp           = client.Post("Payload #1", MediaType.TextPlain);
            Console.WriteLine($"Post #1 ==> {resp.ToString()}");

            resp = client.Post("Payload #2", MediaType.TextPlain);
            Console.WriteLine($"Post #2 ==> {resp.ToString()}");

            resp = client.Post("Payload #3", MediaType.TextXml);
            Console.WriteLine($"Post #2 ==> {resp.ToString()}");
        }
Esempio n. 7
0
        private static void TestPostMessage_ApiCoap()
        {
            var cliente = new CoapClient();

            cliente.Uri = uri;

            var files = Directory.EnumerateFiles(path, "*.txt");

            foreach (string file in files)
            {
                var fileName = new FileInfo(file).Name;

                var peticion = ObtenerMetricas(fileName);
                var response = cliente.Post(peticion);

                Console.WriteLine(fileName + " response: " + response.StatusCode.ToString());
            }
        }
Esempio n. 8
0
        private static async Task TestPost_ApiCoap()
        {
            var client = new CoapClient();

            client.Uri = new Uri("coap://localhost:5683/helloworld");

            var json = JsonConvert.SerializeObject(new EntidadSensor()
            {
                FK_IdEstacionBase = 1,
                Id       = 11,
                Nombre   = "EB01SE11",
                Latitud  = 0.00.ToString(),
                Longitud = 0.00.ToString()
            });
            var res = client.Post(json);

            Console.WriteLine(res.ResponseText);
        }
Esempio n. 9
0
        private static async Task PeticionPost()
        {
            var cliente = new CoapClient();

            cliente.Uri = uri;

            var files = Directory.EnumerateFiles(path, "*.txt");

            foreach (string file in files)
            {
                var fileName = new FileInfo(file).Name;

                string peticion = ObtenerMetricas(fileName);
                var    response = cliente.Post(peticion);

                if (response.StatusCode.ToString() == "Changed")
                {
                    File.Delete(file); //elimina el fichero
                }
            }
        }
        static void RunTest6(string[] cmds)
        {
            //  Do it as a third party.
            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath  = GroupRegister,
                UriQuery = "gp=lights&base=coap://[ff35:30:2001:db8::1]/",
                Timeout  = 20 * 1000
            };
            Response r1 = cl.Post(
                $"<{Test3Location}>,<{Test4Location}>",
                MediaType.ApplicationLinkFormat);

            if (r1 == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }

            Test6Location = r1.LocationPath;
        }
Esempio n. 11
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var files = Directory.EnumerateFiles(directorioSensores, "*.txt");

                    foreach (string file in files)
                    {
                        var fileName = new FileInfo(file).Name;

                        string payload = GetData(fileName);
                        if (!string.IsNullOrEmpty(payload))
                        {
                            var result = client.Post(payload);

                            if (result.StatusCode.ToString() == "Changed")
                            {
                                _logger.Information($"WORKER (ExecuteAsync) - La informacion del fichero {fileName} se ha insertado correctamente");

                                File.Delete(file); //elimina el fichero
                            }
                            else
                            {
                                _logger.Error($"ERR. WORKER (ExecuteAsync) - No se ha podido insertar la información del fichero {fileName}");
                                File.Delete(file); //elimina el fichero
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error($"ERR WORKER (ExecuteAsync) - {ex.Message}");
                }

                await Task.Delay(tiempoEnvio * 1000, stoppingToken);
            }
        }
        static void RunTest5(string[] cmds)
        {
            //  Do it as a third party.
            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath  = ResourceRegister,
                UriQuery = "ep=node3",
                Timeout  = 20 * 1000
            };
            Response r1 = cl.Post(
                "</light/left>;rt=\"light\";ct=0," +
                "</light/middle>;rt=\"light\";ct=0," +
                "</light/right>;rt=\"light\";ct=0",
                MediaType.ApplicationLinkFormat);

            if (r1 == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }

            Test5Location = r1.LocationPath;
        }
Esempio n. 13
0
        static void RunTest53()
        {
            CoapClient request = new CoapClient(Program.Host + "/oscore/hello/1")
            {
                Timeout       = 2000,
                OscoreContext = _oscoreContext
            };

            byte[] saveKey = _oscoreContext.Recipient.Key;
            byte[] newKey  = (byte[])saveKey.Clone();
            _oscoreContext.Sender.Key = newKey;
            newKey[0] += 1;

            Response response = request.Post(new byte[] { 0x4a }, MediaType.TextPlain);


            if (response == null)
            {
                Console.WriteLine("Failed to receive response");
                return;
            }

            if (response.StatusCode != StatusCode.Changed)
            {
                Console.WriteLine($"Content type should be 2.04 not {response.StatusCode}");
            }

            if (response.PayloadSize != 1 || response.Payload[0] != 0x4a)
            {
                Console.WriteLine("Payload for the package is wrong - should be 0x4a");
            }

            Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");

            _oscoreContext.Recipient.Key = saveKey;
        }
Esempio n. 14
0
        static void RunTest6()
        {
            CoapClient request = new CoapClient(Program.Host + "/hello/6")
            {
                Timeout       = 2000,
                OscoapContext = _oscoap_context
            };

            Response response = request.Post(new byte[] { 0x4a }, MediaType.TextPlain);


            if (response == null)
            {
                Console.WriteLine("Failed to receive response");
                return;
            }

            if (response.StatusCode != StatusCode.Changed)
            {
                Console.WriteLine($"Content type should be 2.04 not {response.StatusCode}");
            }

            Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");
        }
        static void RunTest13(string[] cmds)
        {
            //  Do it as a third party.
            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath  = Test4Location,
                UriQuery = "base=coaps://new.example.com:5684",
                Timeout  = 20 * 1000
            };
            Response r1 = cl.Post((byte[])null, MediaType.Undefined);

            if (r1 == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }

            if (r1.StatusCode != StatusCode.Changed)
            {
                Console.WriteLine("Incorrect return code");
            }

            Console.WriteLine(Utils.ToString(r1));
        }
 public static Response SetValues(this CoapClient _client, TradFriRequest request)
 {
     _client.UriPath = request.UriPath;
     return(_client.Post(request.Payload));
 }
        static void RunTest2X(string[] cmds)
        {
            int useContentFormat = MediaType.ApplicationLinkFormat;

            if (cmds.Length > 2)
            {
                switch (cmds[2].ToLower())
                {
#if false // Dead code?
                case "cbor":
                    useContentFormat = MediaType.ApplicationLinkFormatCbor;
                    break;

                case "json":
                    useContentFormat = MediaType.ApplicationLinkFormatJson;
                    break;
#endif

                default:
                    Console.WriteLine("Unrecognized content type");
                    return;
                }
            }
            CoapClient            c = new CoapClient(Program.Host);
            IEnumerable <WebLink> d = c.Discover("rt=core.r*", MediaType.ApplicationLinkFormat);

            string endpointRegister = null;
            string endpointLookup   = null;
            string groupRegister    = null;
            string groupLookup      = null;
            string resourceLookup   = null;

            foreach (WebLink w in d)
            {
                foreach (string s in w.Attributes.GetResourceTypes())
                {
                    switch (s)
                    {
                    case "core.rd":
                        endpointRegister = w.Uri;
                        break;

                    case "core.rd-lookup-res":
                        resourceLookup = w.Uri;
                        break;

                    case "core.rd-group":
                        groupRegister = w.Uri;
                        break;

                    case "core.rd-lookup-gp":
                        groupLookup = w.Uri;
                        break;

                    case "core.rd-lookup-ep":
                        endpointLookup = w.Uri;
                        break;
                    }
                }
            }

            if (endpointRegister == null)
            {
                Console.WriteLine("No endpoint registration resource found");
                return;
            }

            //  Register three endpoints and get their locations

            Uri uri1 = new Uri(Program.Host, endpointRegister);
            c          = new CoapClient(uri1);
            c.UriQuery = "ep=endpoint1&con=coap://sensor1&lt=240";

            Response r =
                c.Post(EncodeResources(
                           "</sensors/temp>;ct=41;rt=\"temperature-c\";if=sensor,</sensors/light>;ct=41;rt=\"light-lux\";if=sensor;obs",
                           useContentFormat),
                       useContentFormat);
            string endpoint1Location = r.Location;

            c.UriQuery = "ep=endpoint2&d=floor3&con=coap://sensor2&lt=120";
            r          = c.Post(EncodeResources(
                                    "</sensors/temp>;ct=41;rt=\"temperature-c\";if=sensor,</sensors/light>;ct=41;rt=\"light-lux\";if=sensor",
                                    useContentFormat), useContentFormat);
            string endpoint2Location = r.Location;

            c.UriQuery = "ep=endpoint3&con=coaps://door1&even=yes&lt=120";
            r          = c.Post(EncodeResources(
                                    "</door/state>;ct=41;rt=doorx;if=senseor,</door/lock>,</door/desc>;ct=0;anchor=\"https://doorcomany/locks?locktype=1\";rt=description",
                                    useContentFormat), useContentFormat);
            string endpoint3Location = r.Location;

            //  do end point queries
            if (endpointLookup == null)
            {
                Console.WriteLine("No endpoint lookup resource found");
            }
            else
            {
                uri1 = new Uri(Program.Host, endpointLookup);
                c    = new CoapClient(uri1);
                d    = c.Discover(endpointLookup, null, useContentFormat);
                Console.WriteLine("Query Endpoint all - expect 3");
                foreach (WebLink w in d)
                {
                    Console.WriteLine("  " + w.ToString());
                }

                d = c.Discover(endpointLookup, "if=sensor", useContentFormat);
                Console.WriteLine("Query for if=sensor");
                foreach (WebLink w in d)
                {
                    Console.WriteLine("  " + w.ToString());
                }

                d = c.Discover(endpointLookup, "even=yes", useContentFormat);
                Console.WriteLine("Query for even=yes");
                foreach (WebLink w in d)
                {
                    Console.WriteLine("  " + w.ToString());
                }
            }

            if (resourceLookup == null)
            {
                Console.WriteLine("No resource lookup resource found");
            }
            else
            {
                uri1 = new Uri(Program.Host, resourceLookup);
                c    = new CoapClient(uri1);

                d = c.Discover(resourceLookup, null, useContentFormat);
                Console.WriteLine("Query resources all");
                foreach (WebLink w in d)
                {
                    Console.WriteLine("  " + w.ToString());
                }

                d = c.Discover(resourceLookup, "if=sensor", useContentFormat);
                Console.WriteLine("Query resource - if=sensor");
                foreach (WebLink w in d)
                {
                    Console.WriteLine("  " + w.ToString());
                }

                d = c.Discover(resourceLookup, "ep=endpoint1", useContentFormat);
                Console.WriteLine("Query resource - endpoint1");
                foreach (WebLink w in d)
                {
                    Console.WriteLine("  " + w.ToString());
                }
            }


            if (groupRegister != null)
            {
                uri1       = new Uri(Program.Host, groupRegister);
                c          = new CoapClient(uri1);
                c.UriQuery = "gp=lights";
                r          = c.Post($"<{endpoint1Location}>,<{endpoint2Location}>", MediaType.ApplicationLinkFormat);

                string group1Location = r.Location;

                c.UriQuery = "gp=all&con=coap://[MD1]:8080&odd=no";
                r          = c.Post($"<{endpoint1Location}>,<{endpoint2Location}>,<{endpoint3Location}>",
                                    MediaType.ApplicationLinkFormat);

                if (groupLookup != null)
                {
                    uri1 = new Uri(Program.Host, groupLookup);
                    c    = new CoapClient(uri1);

                    //  Get all of the groups
                    d = c.Discover(groupLookup, null, useContentFormat);
                    Console.WriteLine("Retrieve all groups - expect 3");
                    foreach (WebLink w in d)
                    {
                        Console.WriteLine("  " + w.ToString());
                    }

                    // Get all groups w/ doors
                    d = c.Discover(groupLookup, "rt=doorx", useContentFormat);
                    Console.WriteLine("Retrieve groups w/ rt=doors - expect 1");
                    foreach (WebLink w in d)
                    {
                        Console.WriteLine("  " + w.ToString());
                    }
                }
            }
        }
        private static void RunTest3(string[] cmds)
        {
            //  Simple registration -

            RdServer server = new RdServer();

            server.Start();
            server.PostTo();

            Thread.Sleep(20 * 1000);

            server.Stop();

            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath  = EndpointLookup,
                UriQuery = "ep=node1",
                Timeout  = 20 * 1000
            };

            Response r1 = cl.Get(MediaType.ApplicationLinkFormat);

            if (r1 != null && r1.StatusCode == StatusCode.Content)
            {
                string ss = r1.PayloadString.Substring(1);
                int    i  = ss.IndexOf('>');
                Test3Location = ss.Substring(0, i);
            }

            Console.WriteLine("Test 3 done");

#if false
            if (cmds.Length == 2)
            {
                //  Do it as a third party.
                CoapClient cl = new CoapClient(Program.Host)
                {
                    UriPath  = "/rd",
                    Timeout  = 20 * 1000,
                    UriQuery = "lt=6000&ep=node1"
                };
                Response r1 = cl.Post(
                    "</sensors/temp>;ct=41;rt=\"temperature-c\";if=sensor;anchor=\"coap://spurious.example.com:5683\"," +
                    "</sensors/light>;ct=41;rt=\"light-lux\";if=sensor",
                    MediaType.ApplicationLinkFormat);
                if (r1 == null)
                {
                    Console.WriteLine("No response message retrieved");
                    return;
                }

                Test3Location = r1.LocationPath;
                return;
            }

            if (cmds.Length != 4)
            {
                Console.WriteLine("Should be 'rd_test 1 <server to do Simple Registration> <endpoint name>'");
                return;
            }

            CoapClient client = new CoapClient(cmds[2])
            {
                UriPath = "/rd/post2",
                Timeout = 20 * 1000
            };

            Response r = client.Post(Program.Host.ToString() + " " + cmds[3]);
            if (r == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }
            else if (r.Code != (int)StatusCode.Changed)
            {
                Console.WriteLine("Unexpected status code {0}.{1} returned", r.Code / 32, r.Code % 32);
                return;
            }
#endif
        }
Esempio n. 19
0
        public void Process(Request request, Response response)
        {
            //  Is this processable?
            if (response.StatusCode != StatusCode.Unauthorized ||
                response.ContentFormat != 65008)
            {
                return;
            }

            try {
                //  Init from the response data
                Oauth.AsInfo info = new Oauth.AsInfo(response.Payload);

                //  Missage this as needed.
                string aSServer = info.ASServer;

                //  Need to build one from scratch

                if (!authServers.ContainsKey(info.ASServer))
                {
                    Console.WriteLine($"No security association is setup for {info.ASServer}");
                    return;
                }

                AuthServerInfo asi = authServers[info.ASServer];

                if (asi.ClientLink == null)
                {
                    asi.ClientLink = new CoapClient(new Uri(info.ASServer));
                    if (asi.UseDTLS)
                    {
                        asi.ClientLink.EndPoint = new DTLSClientEndPoint(asi.TlsKey);
                        asi.ClientLink.EndPoint.Start();
                    }
                }

                // M00BUG - need to make sure that this will pickup a port number if given.
                string audience = $"{request.URI.Scheme}://{request.URI.Authority}";

                Oauth.Request myRequest = new Oauth.Request("client_credentials")
                {
                    Audience = audience,
                    Scope    = CBORObject.FromObject(request.UriPath)
                };

                myRequest.Profile = Profile;

                byte[] payload = myRequest.EncodeToBytes();

                asi.ClientLink.Timeout = 2 * 60 * 1000;
                Response asResponse = asi.ClientLink.Post(payload, MediaType.ApplicationCbor);


                if (asResponse == null)
                {
                    asi.ClientLink.EndPoint.Stop();
                    asi.ClientLink = null;
                    Console.WriteLine($"Timed out requesting token from {info.ASServer}");
                    return;
                }

                if (asResponse.StatusCode != StatusCode.Created)
                {
                    //  We had an error condition appear
                    if (asResponse.Payload != null)
                    {
                        CBORObject obj       = CBORObject.DecodeFromBytes(asResponse.Payload);
                        int        error     = obj["error"].AsInt32();
                        string     errorText = "";
                        if (obj.ContainsKey("error_description"))
                        {
                            errorText = obj["error_description"].AsString();
                        }
                        Console.WriteLine(
                            $"Recieved an error {asResponse.StatusCode} with error no = {error} and description '{errorText}'");
                    }
                    else
                    {
                        Console.WriteLine($"Received and error {asResponse.StatusCode} from the AS but no text");
                    }

                    return;
                }

                Oauth.Response myResponse = new Oauth.Response(asResponse.Payload);


                // default profile for client -
#if false
                if (Profile != null && myResponse.Profile != Profile)
                {
                    Console.WriteLine("AS Server returned an unexpected profile {0}", myResponse.Profile);
                    return;
                }
#endif
                myResponse.Profile = Oauth.ProfileIds.Coap_Dtls;

                //  Post token to resource server

                CoapClient client = new CoapClient();
                client.Uri     = new Uri($"coap://{request.URI.Authority}/authz-info");
                client.Timeout = 10000; // 1 second
                Response tknResponse = client.Post(myResponse.Token, MediaType.ApplicationCbor);
                if (tknResponse == null)
                {
                    Console.WriteLine("Post of token failed w/ no response");
                    return;
                }

                if (tknResponse.StatusCode != StatusCode.Created)
                {
                    Console.WriteLine($"Post of token failed with error {tknResponse.StatusCode}");
                    return;
                }

                Confirmation cnf = myResponse.Confirmation;


                Request newRequest = new Request(request.Method);
                newRequest.Payload = request.Payload;
                newRequest.SetOptions(request.GetOptions());

                DTLSClientEndPoint endPoint = null;

                switch (myResponse.Profile)
                {
                case Oauth.ProfileIds.Coap_Dtls: {
                    OneKey key = cnf.Key;
                    endPoint = new DTLSClientEndPoint(cnf.Key);
                    endPoint.Start();

                    newRequest.EndPoint = endPoint;
                    newRequest.URI      = new Uri($"coaps://{request.URI.Authority}/{request.URI.AbsolutePath}");
                }
                break;

                case Oauth.ProfileIds.Coap_Oscore: {
                    OneKey oneKey = cnf.Key;
                    byte[] salt   = null;
                    if (oneKey.ContainsName("slt"))
                    {
                        salt = oneKey[CBORObject.FromObject("slt")].GetByteString();
                    }
                    CBORObject alg = null;
                    if (oneKey.ContainsName(CoseKeyKeys.Algorithm))
                    {
                        alg = oneKey[CoseKeyKeys.Algorithm];
                    }
                    CBORObject kdf = null;
                    if (oneKey.ContainsName(CBORObject.FromObject("kdf")))
                    {
                        kdf = oneKey[CBORObject.FromObject("kdf")];
                    }

                    SecurityContext oscoapContext = SecurityContext.DeriveContext(
                        oneKey[CoseKeyParameterKeys.Octet_k].GetByteString(),
                        oneKey[CBORObject.FromObject("sid")].GetByteString(),
                        oneKey[CBORObject.FromObject("rid")].GetByteString(),
                        salt, alg, kdf);
                    newRequest.OscoapContext = oscoapContext;
                }
                break;

                default:
                    Console.WriteLine("Cannot rewrite as we don't recognize the profile");
                    return;
                }

                newRequest.Respond += delegate(Object sender, ResponseEventArgs e)
                {
                    Response responseN = e.Response;
                    if (responseN == null)
                    {
                        Console.WriteLine("Request timeout");
                    }
                    else
                    {
                        Console.WriteLine(Utils.ToString(responseN));
                        Console.WriteLine("Time (ms): " + responseN.RTT);
                    }

                    if (endPoint != null)
                    {
                        endPoint.Stop();
                    }
                };

                newRequest.Send();
            }
            catch (Exception e) {
                Console.WriteLine("Error processing AceAuthz - " + e.ToString());
            }
        }
Esempio n. 20
0
        public void Process(Request request, Response response)
        {
            //  Is this processable?
            if (response.StatusCode != StatusCode.Unauthorized /* ||
                                                                * !(response.ContentFormat == 65008 || response.ContentFormat == MediaType.ApplicationCbor)*/)
            {
                return;
            }

            try {
                //  Init from the response data
                Oauth.AsInfo info = new Oauth.AsInfo(response.Payload);

                //  Massage this as needed.
                string aSServer = info.ASServer;

                //  Need to build one from scratch

                if (!authServers.ContainsKey(info.ASServer))
                {
                    Console.WriteLine($"No security association is setup for {info.ASServer}");
                    return;
                }

                AuthServerInfo asi = authServers[info.ASServer];

                if (asi.ClientLink == null)
                {
                    asi.ClientLink = new CoapClient(new Uri(info.ASServer));
                    if (asi.UseDTLS)
                    {
                        asi.ClientLink.EndPoint = new DTLSClientEndPoint(asi.TlsKey);
                        asi.ClientLink.EndPoint.Start();
                    }
                    else
                    {
                        if (asi.ClientLink.Uri.Scheme == "coaps")
                        {
                            asi.ClientLink.Uri = new Uri($"coap://{asi.ClientLink.Uri.Authority}/{asi.ClientLink.UriPath}");
                        }
                        asi.ClientLink.OscoreContext = asi.OscoreKey;
                    }
                }

                // M00BUG - need to make sure that this will pickup a port number if given.
                string audience = $"{request.URI.Scheme}://{request.URI.Authority}";
                if (UseAudience != null)
                {
                    audience = UseAudience;
                }

                Oauth.Request myRequest = new Oauth.Request("client_credentials")
                {
                    Audience = audience,
                    Scope    = (UseScopeValue == null) ? CBORObject.FromObject(request.UriPath) : UseScopeValue
                };

                if (ClientKey != null)
                {
                    myRequest.Cnf = new Confirmation();
                    switch (ClientKeyType)
                    {
                    case 1: // kid
                        myRequest.Cnf.Kid = ClientKey.PrivateKey[CoseKeyKeys.KeyIdentifier].GetByteString();
                        break;

                    case 2: // key
                        myRequest.Cnf.Key = ClientKey.PrivateKey;
                        break;
                    }
                }

                Response asResponse;
                if (asi.UseJSON)
                {
                    string jsonPayload = myRequest.EncodeToString();
                    asi.ClientLink.Timeout = 2 * 60 * 1000;
                    asResponse             = asi.ClientLink.Post(jsonPayload, MediaType.ApplicationJson);
                }
                else
                {
                    byte[] payload = myRequest.EncodeToBytes();
                    asi.ClientLink.Timeout = 2 * 60 * 1000;
                    asResponse             = asi.ClientLink.Post(payload, MediaType.ApplicationCbor);
                }


                if (asResponse == null)
                {
                    asi.ClientLink.EndPoint.Stop();
                    asi.ClientLink = null;
                    Console.WriteLine($"Timed out requesting token from {info.ASServer}");
                    return;
                }

                if (asResponse.StatusCode != StatusCode.Created)
                {
                    //  We had an error condition appear
                    if (asResponse.Payload != null)
                    {
                        CBORObject obj       = CBORObject.DecodeFromBytes(asResponse.Payload);
                        int        error     = obj[/*"error"*/ CBORObject.FromObject(15)].AsInt32();
                        string     errorText = "";
                        if (obj.ContainsKey(/*"error_description")*/ CBORObject.FromObject(16)))
                        {
                            errorText = obj[CBORObject.FromObject(16)].AsString();
                        }
                        Console.WriteLine(
                            $"Received an error {asResponse.StatusCode} with error no = {error} and description '{errorText}'");
                    }
                    else
                    {
                        Console.WriteLine($"Received and error {asResponse.StatusCode} from the AS but no text");
                    }

                    return;
                }

                Oauth.Response myResponse = Oauth.Response.FromCBOR(asResponse.Payload);


                // default profile for client -
#if false
                if (Profile != null && myResponse.Profile != Profile)
                {
                    Console.WriteLine("AS Server returned an unexpected profile {0}", myResponse.Profile);
                    return;
                }
#endif
                if (!myResponse.ContainsKey(Oauth.Oauth_Parameter.Profile))
                {
                    myResponse.Profile = Oauth.ProfileIds.Coap_Dtls;
                }

                //  Post token to resource server

                byte[][] OscoreSalts = null;

                if (!SendTokenAsPsk)
                {
                    CoapClient client = new CoapClient();
                    client.Uri     = new Uri($"coap://{request.URI.Authority}/authz-info");
                    client.Timeout = 10000; // 1 second

                    Response tknResponse = null;
                    if (myResponse.Profile == Oauth.ProfileIds.Coap_Oscore)
                    {
                        byte[]     mySalt = new byte[] { 32, 33, 34, 35, 36, 37, 38 };
                        CBORObject post   = CBORObject.NewMap();
                        post.Add((CBORObject)Oauth.Oauth_Parameter.Access_Token, myResponse.Token);
                        post.Add((CBORObject)Oauth.Oauth_Parameter.CNonce, mySalt);
                        tknResponse = client.Post(post.EncodeToBytes(), MediaType.ApplicationAceCbor);
                        OscoreSalts = new byte[][] { mySalt, null };
                    }
                    else
                    {
                        tknResponse = client.Post(myResponse.Token, MediaType.ApplicationOctetStream);
                    }

                    if (tknResponse == null)
                    {
                        Console.WriteLine("Post of token failed w/ no response");
                        return;
                    }

                    if (tknResponse.StatusCode != StatusCode.Created)
                    {
                        Console.WriteLine($"Post of token failed with error {tknResponse.StatusCode}");
                        return;
                    }

                    if (tknResponse.ContentType == MediaType.ApplicationAceCbor)
                    {
                        CBORObject post = CBORObject.DecodeFromBytes(tknResponse.Payload);
                        if (post.ContainsKey((CBORObject)Oauth.Oauth_Parameter.Client_id))
                        {
                            //  Retrieve
                        }

                        if (post.ContainsKey((CBORObject)Oauth.Oauth_Parameter.CNonce))
                        {
                            if (OscoreSalts == null)
                            {
                                throw new Exception("Internal Error - salts");
                            }
                            OscoreSalts[1] = post[(CBORObject)Oauth.Oauth_Parameter.CNonce].GetByteString();
                        }
                    }
                }

                Confirmation cnf = myResponse.Confirmation;
                if (cnf == null)
                {
                    if (ClientKey == null)
                    {
                        Console.WriteLine("Returned a token but I don't know what key I should be using");
                        return;
                    }
                    cnf = new Confirmation(ClientKey.PrivateKey);
                }

                if (cnf.Kid != null)
                {
                    Console.WriteLine("Missing code - how do we map a kid to a real key?");
                    return;
                }

                Request newRequest = new Request(request.Method);
                newRequest.Payload = request.Payload;
                newRequest.SetOptions(request.GetOptions());

                DTLSClientEndPoint endPoint = null;

                switch (myResponse.Profile)
                {
                case Oauth.ProfileIds.Coap_Dtls: {
                    OneKey key = cnf.Key;
                    LastKeyFound = cnf.Key;
                    if (SendTokenAsPsk)
                    {
                        cnf.Key.AsCBOR().Set(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(myResponse.Token));
                    }

                    endPoint = new DTLSClientEndPoint(cnf.Key);
                    endPoint.Start();

                    if (myResponse.RsConfirmation != null)
                    {
                        ResourceInfo rsInfo = new ResourceInfo(myResponse.RsConfirmation.Key);
                        endPoint.TlsEventHandler += rsInfo.CheckRPK;
                    }

                    newRequest.EndPoint = endPoint;
                    newRequest.URI      = new Uri($"coaps://{request.URI.Authority}/{request.URI.AbsolutePath}");
                }
                break;

                case Oauth.ProfileIds.Coap_Oscore: {
                    CBORObject oscoreContext = cnf.AsCBOR[CBORObject.FromObject(Confirmation.ConfirmationIds.COSE_OSCORE)];

                    byte[] salt = new byte[0];
                    if (oscoreContext.ContainsKey(CBORObject.FromObject(6)))
                    {
                        salt = oscoreContext[CBORObject.FromObject(CBORObject.FromObject(6))].GetByteString();
                    }
                    CBORObject alg = null;
                    if (oscoreContext.ContainsKey(CBORObject.FromObject(5)))
                    {
                        alg = oscoreContext[CBORObject.FromObject(5)];
                    }
                    CBORObject kdf = null;
                    if (oscoreContext.ContainsKey(CBORObject.FromObject(4)))
                    {
                        kdf = oscoreContext[CBORObject.FromObject(4)];
                    }
                    byte[] keyContext = null;
                    if (oscoreContext.ContainsKey(CBORObject.FromObject(7)))
                    {
                        keyContext = oscoreContext[CBORObject.FromObject(7)].GetByteString();
                    }

                    if (OscoreSalts == null)
                    {
                        throw new Exception("Internal Error");
                    }

                    byte[] newSalt = new byte[salt.Length + OscoreSalts[0].Length + OscoreSalts[1].Length];
                    Array.Copy(salt, newSalt, salt.Length);
                    Array.Copy(OscoreSalts[0], 0, newSalt, salt.Length, OscoreSalts[0].Length);
                    Array.Copy(OscoreSalts[1], 0, newSalt, salt.Length + OscoreSalts[0].Length, OscoreSalts[1].Length);

                    SecurityContext oscoapContext = SecurityContext.DeriveContext(
                        oscoreContext[CBORObject.FromObject(1)].GetByteString(), keyContext,
                        oscoreContext[CBORObject.FromObject(2)].GetByteString(),
                        oscoreContext[CBORObject.FromObject(3)].GetByteString(),
                        newSalt, alg, kdf);

                    newRequest.OscoreContext = oscoapContext;

                    newRequest.URI = new Uri($"coap://{request.URI.Authority}/{request.URI.AbsolutePath}");
                }
                break;

                default:
                    Console.WriteLine("Cannot rewrite as we don't recognize the profile");
                    return;
                }

                newRequest.Respond += delegate(object sender, ResponseEventArgs e)
                {
                    Response responseN = e.Response;
                    if (responseN == null)
                    {
                        Console.WriteLine("Request timeout");
                    }
                    else
                    {
                        Console.WriteLine(Utils.ToString(responseN));
                        Console.WriteLine("Time (ms): " + responseN.RTT);
                    }

                    if (endPoint != null)
                    {
                        endPoint.Stop();
                    }
                };

                newRequest.Send();
            }
            catch (Exception e) {
                Console.WriteLine("Error processing AceAuthz - " + e.ToString());
            }
        }