Esempio n. 1
0
        private void ServerEventHandler(object o, OscoreEvent e)
        {
            _callbackCode = e.Code;
            switch (_serverEventChoice)
            {
            case 0:
                break;

            case 1:
                e.SecurityContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                       new byte[][] { clientId }, new OneKey[] { _clientSign1 });
                break;

            case 2:
                e.SecurityContext.AddRecipient(clientId, _clientSign1);
                e.RecipientContext = e.SecurityContext.Recipients[clientId];
                break;

            case 3:
                e.SecurityContext.ReplaceSender(serverId2, _serverSign1);
                break;

            case 4:
                e.SecurityContext = SecurityContext.DeriveGroupContext(secret2, groupId2, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                       new byte[][] { clientId }, new OneKey[] { _clientSign1 });
                break;

            default:
                Assert.Fail();
                break;
            }
        }
Esempio n. 2
0
        public void PivExhaustion()
        {
            SecurityContext context  = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null);
            SecurityContext context2 = SecurityContext.DeriveGroupContext(secret2, groupId2, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null);

            for (int i = 0; i < 10; i++)
            {
                context.Sender.IncrementSequenceNumber();
            }

            context.Sender.MaxSequenceNumber = 10;
            context.OscoreEvents            += ClientEventHandler;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 20
            };

            Response r = client.Get();

            Assert.IsTrue(trigger.WaitOne(1000));
            Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _clientCallbackCode);

            _clientEventChoice = 1;
            client.Timeout     = 1000 * 60;
            r = client.Get();
            Assert.AreEqual(OscoreEvent.EventCode.UnknownGroupIdentifier, _callbackCode);
        }
Esempio n. 3
0
        public void ServerNewSenderGroup()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId, serverId2 }, new OneKey[] { _serverSign1, _serverSign1 });
            SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                               new byte[][] { clientId2, clientId }, new OneKey[] { _clientSign2, _clientSign1 });

            _server.SecurityContexts.Add(serverContext);
            serverContext.OscoreEvents += ServerEventHandler;

            serverContext.Sender.SequenceNumber = 10;

            serverContext.Sender.MaxSequenceNumber = 10;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 60 * 1000
            };

            _serverEventChoice = 4;
            client.Observe(o => { Assert.AreEqual("/abc", o.PayloadString); });

            Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _callbackCode);
        }
Esempio n. 4
0
        private static SecurityContextSet LoadContextSet(string fileName)
        {
            if (fileName == null)
            {
                fileName = "ServerKeys.cbor";
            }
            KeySet             keys   = new KeySet();
            SecurityContextSet newSet = new SecurityContextSet();

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

            using (BinaryReader reader = new BinaryReader(fs)) {
                byte[]     data = reader.ReadBytes((int)fs.Length);
                CBORObject obj  = CBORObject.DecodeFromBytes(data);
                for (int i = 0; i < obj.Count; i++)
                {
                    OneKey   key    = new OneKey(obj[i]);
                    string[] usages = key[_UsageKey].AsString().Split(' ');

                    foreach (String usage in usages)
                    {
                        if (usage == "oscoap")
                        {
                            SecurityContext ctx = SecurityContext.DeriveContext(
                                key[CoseKeyParameterKeys.Octet_k].GetByteString(),
                                null,
                                key[CBORObject.FromObject("RecipID")].GetByteString(),
                                key[CBORObject.FromObject("SenderID")].GetByteString(), null,
                                key[CoseKeyKeys.Algorithm]);
                            newSet.Add(ctx);
                            break;
                        }
                        else if (usage == "oscoap-group")
                        {
                            SecurityContext ctx = SecurityContext.DeriveGroupContext(
                                key[CoseKeyParameterKeys.Octet_k].GetByteString(), key[CBORObject.FromObject(2)].GetByteString(), key[CBORObject.FromObject("SenderID")].GetByteString(),
                                null, null,
                                null, null, null, key[CoseKeyKeys.Algorithm]);
                            foreach (CBORObject recipient in key[CBORObject.FromObject("recipients")].Values)
                            {
                                ctx.AddRecipient(recipient[CBORObject.FromObject("RecipID")].GetByteString(), new OneKey(recipient[CBORObject.FromObject("sign")]));
                            }
                            newSet.Add(ctx);
                        }
                    }

                    if ((usages.Length != 1) || (usages[0] != "oscoap"))
                    {
                        keys.AddKey(key);
                    }
                }
                reader.Close();
            }

            //
            return(newSet);
        }
Esempio n. 5
0
        public void NoGroupId()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null);

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
//                Timeout = 60
            };

            Console.WriteLine($"--Server port = {_serverPort}");


            Response r = client.Get();

            Assert.AreEqual(OscoreEvent.EventCode.UnknownGroupIdentifier, _callbackCode);
        }
Esempio n. 6
0
        /// <summary>
        /// What the CBOR structure needs to look like:
        ///
        /// </summary>
        /// <param name="cmds"></param>
        private static void AddGroupOscoreKey(string[] cmds)
        {
            if (cmds.Length != 3)
            {
                Console.WriteLine("Incorrect number of arguments: " + cmds.Length);
                return;
            }

            CBORObject cbor = CBORDiagnostics.Parse(cmds[2]);

            byte[] salt = null;
            if (cbor.ContainsKey(CoseKeyKeys.slt))
            {
                salt = cbor[CoseKeyKeys.slt].GetByteString();
            }

            SecurityContext ctx = SecurityContext.DeriveGroupContext(cbor[CoseKeyParameterKeys.Octet_k].GetByteString(),
                                                                     cbor[CBORObject.FromObject("GroupID")].GetByteString(),
                                                                     cbor[CBORObject.FromObject("sender")][CBORObject.FromObject("ID")].GetByteString(),
                                                                     cbor["sender"]["sign"][CoseKeyKeys.Algorithm],
                                                                     new OneKey(cbor["sender"]["sign"]),
                                                                     null, null, salt, cbor[CoseKeyKeys.Algorithm]);

            ctx.CountersignParams    = cbor["ParCS"];
            ctx.CountersignKeyParams = cbor["ParCSKey"];

            foreach (CBORObject recipient in cbor[CBORObject.FromObject("recipients")].Values)
            {
                OneKey signKey = null;
                if (recipient.ContainsKey("sign"))
                {
                    signKey = new OneKey(recipient["sign"]);
                }

                ctx.AddRecipient(recipient[CBORObject.FromObject("ID")].GetByteString(), signKey);
            }

            ctx.Locate = (context, kid) => {
                Console.WriteLine("Looking for a kid with a value of " + ByteArrayUtils.ToHexString(kid));
                return(null);
            };

            Program._OscoreKeys.Add(cmds[1], ctx);
        }
Esempio n. 7
0
        public void SetGroupId()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId }, new OneKey[] { _serverSign1 });

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 60 * 1000
            };

            Console.WriteLine($"--Server port = {_serverPort}");

            _serverEventChoice = 1;
            Response r = client.Get();

            Assert.IsNotNull(r);
            Assert.AreEqual("/abc", r.PayloadString);
        }
Esempio n. 8
0
        private void ClientEventHandler(object o, OscoreEvent e)
        {
            _clientCallbackCode = e.Code;
            switch (_clientEventChoice)
            {
            case 0:
                _callbackCode = e.Code;
                break;

            case 1:
                _callbackCode     = e.Code;
                e.SecurityContext = SecurityContext.DeriveGroupContext(secret2, groupId2, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null);
                break;

            default:
                Assert.Fail();
                break;
            }
        }
Esempio n. 9
0
        public void MissingKeyId()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId }, new OneKey[] { _serverSign1 });
            SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                               new byte[][] { clientId2 }, new OneKey[] { _clientSign2 });

            _server.SecurityContexts.Add(serverContext);
            serverContext.OscoreEvents += ServerEventHandler;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 60 * 1000
            };

            _serverEventChoice = 0;
            Response r = client.Get();

            Assert.AreEqual(OscoreEvent.EventCode.UnknownKeyIdentifier, _callbackCode);
        }
Esempio n. 10
0
        public void SupplyMissingKeyId()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId }, new OneKey[] { _serverSign1 });
            SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                               new byte[][] { clientId2 }, new OneKey[] { _clientSign2 });

            _server.SecurityContexts.Add(serverContext);
            serverContext.OscoreEvents += ServerEventHandler;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 60 * 1000
            };

            _serverEventChoice = 2;
            Response r = client.Get();

            Assert.IsNotNull(r);
            Assert.AreEqual("/abc", r.PayloadString);
        }
Esempio n. 11
0
        public void ServerIvExhaustion()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId }, new OneKey[] { _serverSign1 });
            SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                               new byte[][] { clientId2, clientId }, new OneKey[] { _clientSign2, _clientSign1 });

            _server.SecurityContexts.Add(serverContext);
            serverContext.OscoreEvents += ServerEventHandler;

            for (int i = 0; i < 10; i++)
            {
                serverContext.Sender.IncrementSequenceNumber();
            }

            serverContext.Sender.MaxSequenceNumber = 10;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 60 * 1000
            };

            _serverEventChoice = 0;
            Response r = client.Get();

            Assert.IsNotNull(r);
            Assert.AreEqual("/abc", r.PayloadString);

            client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 30 * 1000,
            };
            client.Observe();

            Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _callbackCode);
        }
Esempio n. 12
0
        public static void RunTest(int test)
        {
            if (_oscoreContext == null)
            {
                _oscoreContext = SecurityContext.DeriveContext(
                    new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }, null,
                    new byte[0], new byte[] { 1 },
                    new byte[] { 0x9e, 0x7c, 0xa9, 0x22, 0x23, 0x78, 0x63, 0x40 });
            }

            if (_oscoreGroupContext == null)
            {
                _oscoreGroupContext = SecurityContext.DeriveGroupContext(
                    new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 },
                    new byte[] { 0x37, 0xcb, 0xf3, 0x21, 0x00, 0x17, 0xa2, 0xd3 }, new byte[0], null, null,
                    new byte[][] { new byte[] { 0x1 } }, null,
                    new byte[] { 0x9e, 0x7c, 0xa9, 0x22, 0x23, 0x78, 0x63, 0x40 });
            }

            switch (test)
            {
            case 0:
                RunTest0();
                break;

            case 1:
                RunTest1();
                break;

            case 2:
                RunTest2();
                break;

            case 3:
                RunTest3();
                break;

            case 4:
                RunTest4();
                break;

            case 5:
                RunTest5();
                break;

            case 6:
                RunTest6();
                break;

            case 7:
                RunTest7();
                break;

            case 8:
                RunTest8();
                break;

            case 9:
                RunTest9();
                break;

            case 10:
                RunTest10();
                break;

            case 11:
                RunTest11();
                break;

            case 12:
                RunTest51();
                break;

            case 13:
                RunTest52();
                break;

            case 14:
                RunTest53();
                break;

            case 15:
                RunTest5_2_2();
                break;

            case 16:
                RunTest5_3_1();
                break;

            case 17:
                RunTest5_4_1();
                break;
            }
        }
Esempio n. 13
0
        static void RunCommand(string[] commands)
        {
            if (commands.Length == 0)
            {
                return;
            }



            switch (commands[0].ToUpper())
            {
            default:
                _dispatchTable.Execute(commands);
                break;


            case "SCRIPT":
                TextReader x = new StreamReader(commands[1]);
                RunScript(x);
                x.Dispose();
                break;



            case "COMMENT":
                break;

            case "EXIT":
                Environment.Exit(0);
                break;

            case "PAUSE":
                Console.ReadLine();
                break;

            case "TIMEOUT":
                break;

            case "LOG-LEVEL":
                if (commands.Length != 2)
                {
                    Console.WriteLine("Incorrect number of args");
                    return;
                }
                switch (commands[1].ToUpper())
                {
                case "INFO":
                    LogManager.Level = LogLevel.Info;
                    break;

                case "NONE":
                    LogManager.Level = LogLevel.None;
                    break;

                case "FATAL":
                    LogManager.Level = LogLevel.Fatal;
                    break;

                default:
                    Console.WriteLine("Unknown level");
                    break;
                }
                break;

            case "LOG-TO":
                break;

            case "OPTION":
                OptionType typ = GetOptionType(commands[1]);
                switch (typ)
                {
                case OptionType.ContentFormat:
                case OptionType.Accept:
                    if (commands.Length == 2)
                    {
                        _Options.Add(Option.Create(typ));
                    }
                    else
                    {
                        for (int i = 2; i < commands.Length; i++)
                        {
                            int val = MediaType.ApplicationLinkFormat;
                            if (int.TryParse(commands[i], out val))
                            {
                                _Options.Add(Option.Create(typ, val));
                            }
                            else
                            {
                                Console.WriteLine($"Bad option value '{commands[i]}'");
                            }
                        }
                    }
                    break;

                case OptionType.Unknown:
                    Console.WriteLine("Unrecognized type string");
                    return;

                default:
                    if (commands.Length == 2)
                    {
                        _Options.Add(Option.Create(typ));
                    }
                    else
                    {
                        for (int i = 2; i < commands.Length; i++)
                        {
                            _Options.Add(Option.Create(typ, commands[i]));
                        }
                    }
                    break;
                }
                break;

            case "CLEAR-OPTION":
                if (commands.Length == 1)
                {
                    _Options.Clear();
                    return;
                }
                typ = GetOptionType(commands[1]);
                List <Option> del = new List <Option>();
                foreach (Option op in _Options)
                {
                    if (op.Type == typ)
                    {
                        del.Add(op);
                    }
                }
                foreach (Option op in del)
                {
                    _Options.Remove(op);
                }
                break;

            case "BODY":
                if (commands.Length == 1)
                {
                    break;
                }
                byte[] b = File.ReadAllBytes(commands[1]);
                Body = b;
                break;



#if false
            case "EDHOC":
                RunEdhoc(commands);
                break;
#endif

            case "ADD-OSCOAP":
                if (commands.Length != 3)
                {
                    Console.WriteLine("Incorrect number of arguments: " + commands.Length);
                    return;
                }

                CBORObject      cbor = CBORDiagnostics.Parse(commands[2]);
                SecurityContext ctx  = SecurityContext.DeriveContext(
                    cbor[CoseKeyParameterKeys.Octet_k].GetByteString(),
                    cbor[CBORObject.FromObject("RecipID")].GetByteString(),
                    cbor[CBORObject.FromObject("SenderID")].GetByteString(), null,
                    cbor[CoseKeyKeys.Algorithm]);

                _OscopKeys.Add(commands[1], ctx);

                break;

#if DEV_VERSION
            case "ADD-OSCOAP-GROUP":
                if (commands.Length != 3)
                {
                    Console.WriteLine("Incorrect number of arguments: " + commands.Length);
                    return;
                }
                cbor = CBORDiagnostics.Parse(commands[2]);
                ctx  = SecurityContext.DeriveGroupContext(cbor[CoseKeyParameterKeys.Octet_k].GetByteString(), cbor[CoseKeyKeys.KeyIdentifier].GetByteString(),
                                                          cbor[CBORObject.FromObject("sender")][CBORObject.FromObject("ID")].GetByteString(), null, null, cbor[CoseKeyKeys.Algorithm]);
                ctx.Sender.SigningKey = new OneKey(cbor["sender"]["sign"]);
                foreach (CBORObject recipient in cbor[CBORObject.FromObject("recipients")].Values)
                {
                    ctx.AddRecipient(recipient[CBORObject.FromObject("ID")].GetByteString(), new OneKey(recipient["sign"]));
                }

                _OscopKeys.Add(commands[1], ctx);
                break;
#endif

            case "USE-OSCOAP":
                if (commands.Length != 2)
                {
                    Console.WriteLine("Incorrect number of arguments: " + commands.Length);
                    return;
                }

                if (commands[1] == "NONE")
                {
                    _CurrentOscoap = null;
                    return;
                }

                if (!_OscopKeys.ContainsKey(commands[1]))
                {
                    Console.WriteLine($"OSCOAP Key {commands[1]} is not defined");
                    return;
                }

                _CurrentOscoap = _OscopKeys[commands[1]];
                break;

            case "OSCOAP-TEST":
                OscoapTests.RunTest(Int32.Parse(commands[1]));
                break;

            case "OSCOAP-PIV":
                _CurrentOscoap.Sender.SequenceNumber = Int32.Parse(commands[1]);
                break;

            case "EDHOC-ADD-SERVER-KEY":
                if (commands.Length != 2)
                {
                    Console.WriteLine("Incorrect number of arguments: " + commands.Length);
                    return;
                }

                cbor = CBORDiagnostics.Parse(commands[2]);
                _EdhocServerKeys.AddKey(new OneKey(cbor));
                break;

            case "EDHOC-ADD-USER-KEY":
                if (commands.Length != 3)
                {
                    Console.WriteLine("Incorrect number of arguments: " + commands.Length);
                    return;
                }

                cbor = CBORDiagnostics.Parse(commands[2]);
                _EdhocValidateKeys.Add(commands[1], new OneKey(cbor));
                break;
            }
        }
Esempio n. 14
0
        static KeySet LoadKeys(string fileName)
        {
            if (fileName == null)
            {
                fileName = "ServerKeys.cbor";
            }
            KeySet keys = new KeySet();

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

            using (BinaryReader reader = new BinaryReader(fs)) {
                byte[]     data = reader.ReadBytes((int)fs.Length);
                CBORObject obj  = CBORObject.DecodeFromBytes(data);

                for (int i = 0; i < obj.Count; i++)
                {
                    OneKey   key    = new OneKey(obj[i]);
                    string[] usages = key[_UsageKey].AsString().Split(' ');

                    foreach (String usage in usages)
                    {
                        if (usage == "oscoap")
                        {
                            SecurityContext ctx = SecurityContext.DeriveContext(
                                key[CoseKeyParameterKeys.Octet_k].GetByteString(),
                                key[CBORObject.FromObject("RecipID")].GetByteString(),
                                key[CBORObject.FromObject("SenderID")].GetByteString(), null,
                                key[CoseKeyKeys.Algorithm]);
                            SecurityContextSet.AllContexts.Add(ctx);
                            break;
                        }
#if DEV_VERSION
                        else if (usage == "oscoap-group")
                        {
                            SecurityContext ctx = SecurityContext.DeriveGroupContext(
                                key[CoseKeyParameterKeys.Octet_k].GetByteString(),
                                key[CoseKeyKeys.KeyIdentifier].GetByteString(),
                                key[CBORObject.FromObject("sender")][CBORObject.FromObject("ID")].GetByteString(), null,
                                null, key[CoseKeyKeys.Algorithm]);
                            ctx.Sender.SigningKey = new OneKey(obj[i]["sign"]);
                            foreach (CBORObject recipient in key[CBORObject.FromObject("recipients")].Values)
                            {
                                ctx.AddRecipient(recipient[CBORObject.FromObject("ID")].GetByteString(),
                                                 new OneKey(recipient["sign"]));
                            }

                            SecurityContextSet.AllContexts.Add(ctx);
                        }
#endif
                        else if (usage == "dtls")
                        {
                            if (key.HasPrivateKey())
                            {
                                DtlsSignKeys.AddKey(key);
                            }
                            else
                            {
                                DtlsValidateKeys.AddKey(key);
                            }
                        }

                        else if (usage == "edhoc")
                        {
                            if (key[CoseKeyKeys.KeyType].Equals(GeneralValues.KeyType_EC) ||
                                key[CoseKeyKeys.KeyType].Equals(GeneralValues.KeyType_OKP))
                            {
                                if (key.ContainsName(CoseKeyParameterKeys.EC_D))
                                {
                                    edhocSign = key;
                                }
                                else
                                {
                                    edhocKeys.AddKey(key);
                                }
                            }
                            else
                            {
                                edhocKeys.AddKey(key);
                            }
                        }
                    }

                    if ((usages.Length != 1) || (usages[0] != "oscoap"))
                    {
                        keys.AddKey(key);
                    }
                }

                reader.Close();
            }

            return(keys);
        }