private void ExecutePOSTRequest() { string payload = "--no payload--"; try { Request request = new Request(Method.POST); request.OscoreContext = SecurityContext.DeriveContext(secret, null, clientId, serverId); request.SetUri("coap://localhost:" + _serverPort + "/" + request_short + respond_short); request.SetPayload(request_short ? SHORT_POST_REQUEST : LONG_POST_REQUEST); request.Send(_clientEndpoint); // receive response and check Response response = request.WaitForResponse(/*1000*/); Assert.IsNotNull(response); payload = response.PayloadString; if (respond_short) { Assert.AreEqual(SHORT_POST_RESPONSE, payload); } else { Assert.AreEqual(LONG_POST_RESPONSE, payload); } } finally { Thread.Sleep(100); // Quickly wait until last ACKs arrive } }
private void CreateServer() { CoAPEndPoint endpoint = new CoAPEndPoint(0); _server = new CoapServer(); // _resource = new StorageResource(TARGET, CONTENT_1); // _server.Add(_resource); Resource r2 = new EchoLocation("abc"); _server.Add(r2); r2.Add(new EchoLocation("def")); _server.AddEndPoint(endpoint); _server.Start(); _serverPort = ((System.Net.IPEndPoint)endpoint.LocalEndPoint).Port; Console.WriteLine($"Server port = {_serverPort}"); SecurityContextSet oscoapContexts = new SecurityContextSet(); _server.SecurityContexts.Add(SecurityContext.DeriveContext(secret, null, serverId, clientId)); _server.SecurityContexts.OscoreEvents += ServerEventHandler; }
private static void AddOscoreKey(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(CBORObject.FromObject(6))) { salt = cbor[CBORObject.FromObject(6)].GetByteString(); } byte[] contextId = null; if (cbor.ContainsKey(CBORObject.FromObject(7))) { contextId = cbor[CBORObject.FromObject(7)].GetByteString(); } SecurityContext ctx = SecurityContext.DeriveContext( cbor[CBORObject.FromObject(1)].GetByteString(), contextId, cbor[CBORObject.FromObject(2)].GetByteString(), cbor[CBORObject.FromObject(3)].GetByteString(), salt, null /*cbor[CoseKeyKeys.Algorithm]*/); Program._OscoreKeys.Add(cmds[1], ctx); }
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); }
public void Ocoap_Get() { CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc") { OscoapContext = SecurityContext.DeriveContext(_Secret, _ClientId, _ServerId) }; Response r = client.Get(); Assert.AreEqual("/abc", r.PayloadString); }
private void CreateServer() { _server = new CoapServer(); CoAPEndPoint endpoint = new CoAPEndPoint(_serverPort, _config); _server.AddEndPoint(endpoint); _server.MessageDeliverer = new MessageDeliverer(this); _server.SecurityContexts.Add(SecurityContext.DeriveContext(secret, null, serverId, clientId)); _server.Start(); _serverPort = ((System.Net.IPEndPoint)endpoint.LocalEndPoint).Port; }
public static void RunTest(int test) { if (_oscoap_context == null) { _oscoap_context = SecurityContext.DeriveContext( new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23 }, Encoding.UTF8.GetBytes("client"), Encoding.UTF8.GetBytes("server"), null, AlgorithmValues.AES_CCM_16_64_128); } 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; } }
private void CreateServer() { CoAPEndPoint endpoint = new CoAPEndPoint(0); _server = new CoapServer(); // _resource = new StorageResource(TARGET, CONTENT_1); // _server.Add(_resource); Resource r2 = new EchoLocation("abc"); _server.Add(r2); r2.Add(new EchoLocation("def")); _server.AddEndPoint(endpoint); _server.Start(); _serverPort = ((System.Net.IPEndPoint)endpoint.LocalEndPoint).Port; SecurityContextSet oscoapContexts = new SecurityContextSet(); SecurityContextSet.AllContexts.Add(SecurityContext.DeriveContext(_Secret, _ServerId, _ClientId)); }
private void ExecuteGETRequest() { string payload = "nothing"; try { Request request = Request.NewGet(); request.Destination = new IPEndPoint(IPAddress.Loopback, _serverPort); request.OscoreContext = SecurityContext.DeriveContext(secret, null, clientId, serverId); request.Send(_clientEndpoint); // receive response and check Response response = request.WaitForResponse(/*1000*/); Assert.IsNotNull(response); payload = response.PayloadString; Assert.AreEqual(respond_short ? SHORT_GET_RESPONSE : LONG_GET_RESPONSE, payload); } finally { Thread.Sleep(100); // Quickly wait until last ACKs arrive } }
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()); } }
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; } }
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()); } }
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; } }
public static void KdcToken(string[] cmds) { if (cmds.Length != 7) { Console.WriteLine("Incorrect argument Count: KdcToken <AS> <Audience> <Scope> <OscoreKeys> <Kdc> <Store>"); return; } Request request = new Request(Method.POST) { URI = new Uri(cmds[1]) }; Oauth.Request oRequest = new Oauth.Request(Oauth.Request.GrantType_ClientToken) { Audience = cmds[2], Scope = CBORObject.FromObject(cmds[3]) }; request.Payload = oRequest.EncodeToBytes(); request.ContentType = MediaType.ApplicationAceCbor; request.OscoreContext = Program._OscoreKeys[cmds[4]]; request.Send(); Response response = request.WaitForResponse(); if (response.StatusCode != StatusCode.Created) { Console.WriteLine($"Error with response from the AS - Code is {response.StatusCode}"); return; } Oauth.Response oResponse = Oauth.Response.FromCBOR(response.Payload); Confirmation cnf = oResponse.Confirmation; byte[][] oscoreSalts = new byte[2][]; request = new Request(Method.POST) { URI = new Uri(cmds[5]) }; CBORObject kdcRequest = CBORObject.NewMap(); kdcRequest.Add(Oauth_Parameter.Access_Token.Key, oResponse.Token); if (cnf.AsCBOR.ContainsKey(CBORObject.FromObject(Confirmation.ConfirmationIds.COSE_OSCORE))) { oscoreSalts[0] = SecureRandom.GetNextBytes(new SecureRandom(), 8); kdcRequest.Add(Oauth_Parameter.CNonce.Key, CBORObject.FromObject(oscoreSalts[0])); request.ContentFormat = MediaType.ApplicationAceCbor; } request.Payload = kdcRequest.EncodeToBytes(); request.Send(); response = request.WaitForResponse(); if (response.StatusCode != StatusCode.Created) { Console.WriteLine("Failure"); return; } Console.WriteLine("Successfully posted to KDC"); CBORObject cborResponse = CBORObject.DecodeFromBytes(response.Payload); GroupData groupData = new GroupData(); if (cborResponse.ContainsKey(Oauth_Parameter.CNonce.Key)) { groupData.ServerNonce = cborResponse[Oauth_Parameter.CNonce.Key].GetByteString(); } if (cborResponse.ContainsKey("sign_info")) { groupData.SignInfo = CBORObject.DecodeFromBytes(cborResponse["sign_info"].GetByteString()); } else { groupData.SignInfo = CBORObject.DecodeFromBytes(new byte[] { 0x83, 0x27, 0x06, 0x82, 0x01, 0x06 }); } if (cborResponse.ContainsKey("pub_key_enc")) { groupData.PubKeyEnc = cborResponse["pub_key_enc"].GetByteString(); } groupData.SignNonce = cborResponse["SignNonce"].GetByteString(); if (cnf.AsCBOR.ContainsKey(CBORObject.FromObject(Confirmation.ConfirmationIds.COSE_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(); } oscoreSalts[1] = cborResponse[Oauth_Parameter.CNonce.Key].GetByteString(); 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); oscoapContext.UserData = groupData; Program._OscoreKeys.Add(cmds[6], oscoapContext); } else if (cnf.AsCBOR.ContainsKey(CBORObject.FromObject(Confirmation.ConfirmationIds.COSE_Key))) { TlsKeyPair tlsKey = new TlsKeyPair(cnf.Key); tlsKey.PrivateKey.UserData = groupData; Program._TlsKeys.Add(cmds[5], new TlsKeyPair(cnf.Key)); } else { Console.WriteLine("Don't know how to get the key"); } }
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); }