From bf5dd5a82fb663ed06d2dd1a9e757cc865e66ac3 Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Thu, 26 Apr 2018 13:15:58 +0100 Subject: [PATCH] coap-{client|server}: Add in PKI Support. Tidy up Usage output examples/client.c Add in support for using PKI certificates examples/coap-server.c Add in support for using PKI certificates remove default PSK key Add in '-h hint' option Make Usage reflect actual options available to use man/coap-client.txt.in Include the missing options Update -A option to be a single entity Sort the options into ascending order as reported by Usage man/coap-server.txt.in Include the missing options Add in '-h hint' option --- examples/client.c | 103 +++++++++++++++++++++++++++-------------- examples/coap-server.c | 84 +++++++++++++++++++++++++++------ man/coap-client.txt.in | 63 ++++++++++++++++++------- man/coap-server.txt.in | 49 ++++++++++++++++---- 4 files changed, 224 insertions(+), 75 deletions(-) diff --git a/examples/client.c b/examples/client.c index 7508f837..af0c1f89 100644 --- a/examples/client.c +++ b/examples/client.c @@ -58,6 +58,8 @@ static int reliable = 0; unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */ +static char *cert_file = NULL; /* Combined certificate and private key file */ + typedef unsigned char method_t; method_t method = 1; /* the method we are using in our requests */ @@ -506,43 +508,49 @@ usage( const char *program, const char *version) { fprintf( stderr, "%s v%s -- a small CoAP implementation\n" "(c) 2010-2015 Olaf Bergmann \n\n" - "usage: %s [-A type...] [-t type] [-b [num,]size] [-B seconds] [-e text]\n" - "\t\t[-m method] [-N] [-o file] [-P addr[:port]] [-p port]\n" - "\t\t[-s duration] [-O num,text] [-T string] [-v num] [-a addr] [-U]\n\n" - "\t\t[-u user] [-k key] [-r] URI\n\n" - "\tURI can be an absolute or relative coap URI,\n" - "\t-a addr\tthe local interface address to use\n" - "\t-A type...\taccepted media type\n" - "\t-t type\t\tcontent format for given resource for PUT/POST\n" - "\t-b [num,]size\tblock size to be used in GET/PUT/POST requests\n" + "Usage: %s [-a addr] [-b [num,]size] [-c certfile] [-e text]\n" + "\t\t[-f file] [-k key] [-l loss] [-m method] [-o file]\n" + "\t\t[-p port] [-r] [-s duration] [-t type] [-u user]\n" + "\t\t[-v num] [-A type] [-B seconds] [-N] [-O num,text]\n" + "\t\t[-P addr[:port]] [-T token] [-U] URI\n\n" + "\tURI can be an absolute URI or a URI prefixed with scheme and host\n\n" + "\t-a addr\t\tThe local interface address to use\n" + "\t-b [num,]size\tBlock size to be used in GET/PUT/POST requests\n" "\t \t\t(value must be a multiple of 16 not larger than 1024)\n" "\t \t\tIf num is present, the request chain will start at\n" "\t \t\tblock num\n" - "\t-B seconds\tbreak operation after waiting given seconds\n" - "\t\t\t(default is %d)\n" - "\t-e text\t\tinclude text as payload (use percent-encoding for\n" + "\t-c certfile\tPEM file containing both CERTIFICATE and PRIVATE KEY\n" + "\t \t\tThis argument requires (D)TLS with PKI to be available\n" + "\t-e text\t\tInclude text as payload (use percent-encoding for\n" "\t\t\tnon-ASCII characters)\n" - "\t-f file\t\tfile to send with PUT/POST (use '-' for STDIN)\n" + "\t-f file\t\tFile to send with PUT/POST (use '-' for STDIN)\n" "\t-k key\t\tPre-shared key for the specified user. This argument\n" - "\t \t\trequires DTLS with PSK to be available.\n" - "\t-m method\trequest method (get|put|post|delete|fetch|patch|ipatch), default is 'get'\n" - "\t-N\t\tsend NON-confirmable message\n" - "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n" - "\t-p port\t\tlisten on specified port\n" - "\t-s duration\tsubscribe for given duration [s]\n" - "\t-u user\t\tuser identity for pre-shared key mode. This argument\n" - "\t \t\trequires DTLS with PSK to be available.\n" - "\t-v num\t\tverbosity level (default: 3)\n" - "\t-O num,text\tadd option num with contents text to request\n" - "\t-P addr[:port]\tuse proxy (automatically adds Proxy-Uri option to\n" - "\t\t\trequest)\n" - "\t-T token\tinclude specified token\n" - "\t-U\t\tnever include Uri-Host or Uri-Port options\n" + "\t \t\trequires (D)TLS with PSK to be available\n" + "\t-l list\t\tFail to send some datagrams specified by a comma separated\n" + "\t\t\tlist of numbers or number ranges (for debugging only)\n" + "\t-l loss%%\tRandomly fail to send datagrams with the specified\n" + "\t\t\tprobability (for debugging only)\n" + "\t-m method\tRequest method (get|put|post|delete|fetch|patch|ipatch),\n" + "\t\t\tdefault is 'get'\n" + "\t-o file\t\tOutput received data to this file (use '-' for STDOUT)\n" + "\t-p port\t\tListen on specified port\n" "\t-r\t\tUse reliable protocol (TCP or TLS)\n" - "\t-l list\t\tFail to send some datagram specified by a comma separated list of number or number intervals(for debugging only)\n" - "\t-l loss%%\tRandomly fail to send datagrams with the specified probability(for debugging only)\n" + "\t-s duration\tSubscribe to / Observe resource for given duration [s]\n" + "\t-t type\t\tContent format for given resource for PUT/POST\n" + "\t-u user\t\tUser identity for pre-shared key mode. This argument\n" + "\t \t\trequires (D)TLS with PSK to be available\n" + "\t-v num\t\tVerbosity level (default: 3)\n" + "\t-A type\t\tAccepted media type\n" + "\t-B seconds\tBreak operation after waiting given seconds\n" + "\t\t\t(default is %d)\n" + "\t-N\t\tSend NON-confirmable message\n" + "\t-O num,text\tAdd option num with contents text to request\n" + "\t-P addr[:port]\tUse proxy (automatically adds Proxy-Uri option to\n" + "\t\t\trequest)\n" + "\t-T token\tInclude specified token\n" + "\t-U\t\tNever include Uri-Host or Uri-Port options\n" "\n" - "examples:\n" + "Examples:\n" "\tcoap-client -m get coap://[::1]/\n" "\tcoap-client -m get coap://[::1]/.well-known/core\n" "\tcoap-client -m get -T cafe coap://[::1]/time\n" @@ -1015,18 +1023,38 @@ get_session( coap_address_init( &bind_addr ); bind_addr.size = rp->ai_addrlen; memcpy( &bind_addr.addr, rp->ai_addr, rp->ai_addrlen ); - if ( identity && key && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) - session = coap_new_client_session_psk( ctx, &bind_addr, dst, proto, identity, key, key_len ); - else + if (cert_file && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS)) { + coap_dtls_pki_t dtls_pki; + memset (&dtls_pki, 0, sizeof(dtls_pki)); + dtls_pki.public_cert = cert_file; + dtls_pki.private_key = cert_file; + session = coap_new_client_session_pki(ctx, &bind_addr, dst, proto, &dtls_pki); + } + else if ((identity || key) && + (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) { + session = coap_new_client_session_psk( ctx, &bind_addr, dst, proto, + identity, key, key_len ); + } + else { session = coap_new_client_session( ctx, &bind_addr, dst, proto ); + } if ( session ) break; } } freeaddrinfo( result ); } else { - if ( identity && key && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) - session = coap_new_client_session_psk( ctx, NULL, dst, proto, identity, key, key_len ); + if (cert_file && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS)) { + coap_dtls_pki_t dtls_pki; + memset (&dtls_pki, 0, sizeof(dtls_pki)); + dtls_pki.public_cert = cert_file; + dtls_pki.private_key = cert_file; + session = coap_new_client_session_pki(ctx, NULL, dst, proto, &dtls_pki); + } + else if ((identity || key) && + (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) + session = coap_new_client_session_psk( ctx, NULL, dst, proto, + identity, key, key_len ); else session = coap_new_client_session( ctx, NULL, dst, proto ); } @@ -1052,7 +1080,7 @@ main(int argc, char **argv) { ssize_t user_length = 0, key_length = 0; int create_uri_opts = 1; - while ((opt = getopt(argc, argv, "Nra:b:e:f:g:k:m:p:s:t:o:v:A:B:O:P:T:u:U:l:")) != -1) { + while ((opt = getopt(argc, argv, "Nra:b:c:e:f:k:m:p:s:t:o:v:A:B:O:P:T:u:U:l:")) != -1) { switch (opt) { case 'a': strncpy(node_str, optarg, NI_MAXHOST - 1); @@ -1064,6 +1092,9 @@ main(int argc, char **argv) { case 'B': wait_seconds = atoi(optarg); break; + case 'c': + cert_file = optarg; + break; case 'e': if (!cmdline_input(optarg, &payload)) payload.length = 0; diff --git a/examples/coap-server.c b/examples/coap-server.c index 495a6de7..abfdd0f9 100644 --- a/examples/coap-server.c +++ b/examples/coap-server.c @@ -47,6 +47,13 @@ static time_t my_clock_base = 0; struct coap_resource_t *time_resource = NULL; +static char *cert_file = NULL; /* Combined certificate and private key file */ +#define MAX_KEY 64 /* Maximum length of a key (i.e., PSK) in bytes. */ +static uint8_t key[MAX_KEY]; +static ssize_t key_length = 0; +int key_defined = 0; +static const char *hint = "CoAP"; + #ifndef WITHOUT_ASYNC /* This variable is used to mimic long-running tasks that require * asynchronous responses. */ @@ -336,9 +343,22 @@ init_resources(coap_context_t *ctx) { static void fill_keystore(coap_context_t *ctx) { - static uint8_t key[] = "secretPSK"; - size_t key_len = sizeof( key ) - 1; - coap_context_set_psk( ctx, "CoAP", key, key_len ); + if (cert_file) { + coap_dtls_pki_t dtls_pki; + memset (&dtls_pki, 0, sizeof(dtls_pki)); + dtls_pki.public_cert = cert_file; + dtls_pki.private_key = cert_file; + coap_context_set_pki(ctx, &dtls_pki); + if (key_defined) + coap_context_set_psk(ctx, hint, key, key_length); + } + else if (key_defined) { + coap_context_set_psk(ctx, hint, key, key_length); + } + else if (coap_dtls_is_supported() || coap_tls_is_supported()) { + coap_log(LOG_DEBUG, + "(D)TLS not enabled as neither -k or -c options specified\n"); + } } static void @@ -351,13 +371,23 @@ usage( const char *program, const char *version) { fprintf( stderr, "%s v%s -- a small CoAP implementation\n" "(c) 2010,2011,2015 Olaf Bergmann \n\n" - "usage: %s [-A address] [-p port]\n\n" - "\t-A address\tinterface address to bind to\n" - "\t-g group\tjoin the given multicast group\n" - "\t-p port\t\tlisten on specified port\n" - "\t-v num\t\tverbosity level (default: 3)\n" - "\t-l list\t\tFail to send some datagram specified by a comma separated list of number or number intervals(for debugging only)\n" - "\t-l loss%%\t\tRandmoly fail to send datagrams with the specified probability(for debugging only)\n", + "Usage: %s [-A address] [-g group] [-p port] [-l loss] [-c certfile]\n" + "\t\t[-k key] [-h hint] [-v num]\n\n" + "\t-A address\tInterface address to bind to\n" + "\t-g group\tJoin the given multicast group\n" + "\t-p port\t\tListen on specified port\n" + "\t-c certfile\tPEM file containing both CERTIFICATE and PRIVATE KEY\n" + "\t \t\tThis argument requires (D)TLS with PKI to be available\n" + "\t-h hint\t\tPSK Hint. Default is CoAP\n" + "\t-k key\t\tPre-shared key. This argument requires (D)TLS with PSK\n" + "\t \t\tto be available. This cannot be empty if defined.\n" + "\t \t\tNote that both -c and -k need to be defined\n" + "\t \t\tfor both PSK and PKI to be concurrently supported\n" + "\t-l list\t\tFail to send some datagram specified by a comma separated\n" + "\t\t\tlist of number or number intervals (for debugging only)\n" + "\t-l loss%%\tRandomly fail to send datagrams with the specified\n" + "\t\t\tprobability (for debugging only)\n" + "\t-v num\t\tVerbosity level (default: 3)\n", program, version, program ); } @@ -409,7 +439,7 @@ get_context(const char *node, const char *port) { ep_udp = coap_new_endpoint(ctx, &addr, COAP_PROTO_UDP); if (ep_udp) { - if (coap_dtls_is_supported()) { + if (coap_dtls_is_supported() && (key_defined || cert_file)) { ep_dtls = coap_new_endpoint(ctx, &addrs, COAP_PROTO_DTLS); if (!ep_dtls) coap_log(LOG_CRIT, "cannot create DTLS endpoint\n"); @@ -420,7 +450,7 @@ get_context(const char *node, const char *port) { } ep_tcp = coap_new_endpoint(ctx, &addr, COAP_PROTO_TCP); if (ep_tcp) { - if (coap_tls_is_supported()) { + if (coap_tls_is_supported() && (key_defined || cert_file)) { ep_tls = coap_new_endpoint(ctx, &addrs, COAP_PROTO_TLS); if (!ep_tls) coap_log(LOG_CRIT, "cannot create TLS endpoint\n"); @@ -504,6 +534,16 @@ join(coap_context_t *ctx, char *group_name){ return result; } +static ssize_t +cmdline_read_key(char *arg, unsigned char *buf, size_t maxlen) { + size_t len = strnlen(arg, maxlen); + if (len) { + memcpy(buf, arg, len); + return len; + } + return -1; +} + int main(int argc, char **argv) { coap_context_t *ctx; @@ -517,15 +557,33 @@ main(int argc, char **argv) { clock_offset = time(NULL); - while ((opt = getopt(argc, argv, "A:g:p:v:l:")) != -1) { + while ((opt = getopt(argc, argv, "A:c:g:h:k:p:v:l:")) != -1) { switch (opt) { case 'A' : strncpy(addr_str, optarg, NI_MAXHOST-1); addr_str[NI_MAXHOST - 1] = '\0'; break; + case 'c' : + cert_file = optarg; + break; case 'g' : group = optarg; break; + case 'h' : + if (!optarg[0]) { + coap_log( LOG_CRIT, "Invalid PSK hint specified\n" ); + break; + } + hint = optarg; + break; + case 'k' : + key_length = cmdline_read_key(optarg, key, MAX_KEY); + if (key_length < 0) { + coap_log( LOG_CRIT, "Invalid PSK key specified\n" ); + break; + } + key_defined = 1; + break; case 'p' : strncpy(port_str, optarg, NI_MAXSERV-1); port_str[NI_MAXSERV - 1] = '\0'; diff --git a/man/coap-client.txt.in b/man/coap-client.txt.in index 4fd29bed..ec0ba2b7 100644 --- a/man/coap-client.txt.in +++ b/man/coap-client.txt.in @@ -14,21 +14,27 @@ coap-client - CoAP Client based on libcoap SYNOPSIS -------- -*coap-client* [*-A* type1, _type2_ ,...] [*-t* type] [*-b* [num,]size] - [*-B* seconds] [*-e* text] [*-f* file] [*-m* method] [*-N*] - [*-o* file] [*-P* addr[:port]] [*-p* port] [*-s* duration] - [*-O* num,text] [*-T* token] [*-v* num] [*-a* addr] [*-U*] URI +*coap-client* [*-a* addr] [*-b* [num,]size] [*-c* certfile] [*-e* text] + [*-f* file] [*-k* key] [*-l* loss] [*-m* method] [*-o* file] + [*-p* port] [*-r*] [*-s* duration] [*-t* type] [*-u* user] + [*-v* num] [*-A* type] [*-B* seconds] [*-N*] + [*-O* num,text] [*-P* addr[:port]] [*-T* token] [*-U*] URI DESCRIPTION ----------- *coap-client* is a CoAP client to communicate with 6LoWPAN devices via the protocol CoAP (RFC 7252) using the URI given as argument on the command line. The URI must have the scheme 'coap', 'coap+tcp', 'coaps' or -'coaps+tcp' when coap-client was built with support for secure communication. +'coaps+tcp'. 'coaps' and 'coaps+tcp' are only supported when coap-client is +built with support for secure (D)TLS communication. + +If 'coaps' or 'coap+tcp' is being used, provided the CoAP server supports PKI +and is configured with a Certificate and Private Key, the coap-client does not +need to have a Pre-Shared Key (-k) or Certificate (-c) configured. + The URI's host part may be a DNS name or a literal IP address. Note that, for IPv6 address references, angle brackets are required (c.f. EXAMPLES). - OPTIONS ------- *-a* addr:: @@ -43,12 +49,28 @@ OPTIONS retrieve the subsequent block from the server until there are no more outstanding blocks for the requested content. +*-c* certfile:: + Use the specified PEM file which contains the CERTIFICATE and PRIVATE + KEY information. This argument requires (D)TLS with PKI to be available. + *-e* text:: Include text as payload (use percent-encoding for non-ASCII characters). *-f* file:: File to send with PUT/POST (use '-' for STDIN). +*-k* key:: + Pre-shared key for the specified user (-u option also required). + This argument requires (D)TLS with PSK to be available. + +*-l* list:: + Fail to send some datagrams specified by a comma separated list of + numbers or number ranges (debugging only). + +*-l* loss%:: + Randomly failed to send datagams with the specified probability - 100% + all datagrams, 0% no datagrams (debugging only). + *-m* method:: The request method for action (get|put|post|delete), default is 'get'. (Note that the string passed to *-m* is compared case-insensitive.) @@ -59,9 +81,12 @@ OPTIONS *-p* port:: The port to listen on. +*-r*:: + Use reliable protocol (TCP or TLS). + *-s* duration:: - Subscribe to the resource specified by URI for the given 'duration' in - seconds. + Subscribe to / observe the resource specified by URI for the given + 'duration' in seconds. *-t* type:: Content format for given resource for PUT/POST. 'type' must be either @@ -78,14 +103,16 @@ OPTIONS application/json (json) application/cbor (cbor) +*-u* user:: + User identity for pre-shared key mode (-k option also required). + This argument requires (D)TLS with PSK to be available. + *-v* num:: The verbosity level to use (default: 3, maximum is 9). *-A* type:: - Accepted media types as comma-separated list of symbolic or numeric - values, there are multiple arguments as comma separated list - possible. 'type' must be either a numeric value reflecting a valid - CoAP content format or a string that specifies a registered format as + Accepted media type. 'type' must be either a numeric value reflecting a + valid CoAP content format or a string that specifies a registered format as described for option *-t*. *-B* seconds:: @@ -114,19 +141,21 @@ EXAMPLES ---- coap-client coap://coap.me ---- -Query resource '/' from server 'coap.me' (via the GET method). +Query the resource '/' from server 'coap.me' (using the GET method). * Example ---- coap-client -m get coap://[::1]/ ---- -Query on localhost via the 'GET' method. +Query the resource '/' on localhost using the 'GET' method to get back the +summary defined attributes. * Example ---- coap-client -m get coap://[::1]/.well-known/core ---- -Quite the same, except on the resource '.well-known/core' on localhost. +Query on the resource '.well-known/core' on localhost to get back a list of +the known resources along with their attribute definitions. * Example ---- @@ -135,14 +164,14 @@ coap://[2001:db8:c001:f00d:221:2eff:ff00:2704]:5683/actuators/leds?color=r -f- ---- Send text 'mode=on' to resource 'actuators/leds?color=r' on the endpoint with address '2001:db8:c001:f00d:221:2eff:ff00:2704' and port '5683'. Note that the -port '5683' is the default port and isn't really needed to append. +port '5683' is the default port and isn't actually required in this instance. * Example ---- coap-client -m put coap://[fec0::3]/ck -T 3a -t binary -f to_upload ---- Put the contents of file 'to_upload' with content type 'binary' (i.e. -application/octet-stream) into resource 'ck' on 'fec0::3' by usage of a token +application/octet-stream) into resource 'ck' on 'fec0::3' using a token of '3a' via the 'PUT' method. FILES diff --git a/man/coap-server.txt.in b/man/coap-server.txt.in index 27450850..ced18b1f 100644 --- a/man/coap-server.txt.in +++ b/man/coap-server.txt.in @@ -14,12 +14,12 @@ coap-server - CoAP Server based on libcoap SYNOPSIS -------- -*coap-server* [*-A* addr] [*-g* group] [*-p* port] [*-v* num] +*coap-server* [*-A* addr] [*-g* group] [*-p* port] [*-l* loss] + [*-k* key] [*-h* hint] [*-c* certfile] [*-v* num] DESCRIPTION ----------- -*coap-server* is a CoAP server which simulate 6LoWPAN devices which can be -addressed via the CoAP protocol. +*coap-server* is an example server for the 'Constrained Application Protocol` (RFC 7252). OPTIONS ------- @@ -30,9 +30,33 @@ OPTIONS Join specified multicast 'group' on startup. *-p* port:: - The 'port' on the given address the server will be waitung for connections. + The 'port' on the given address will be listening for incoming connections. + If (D)TLS is supported, then 'port' + 1 will also be listened on for + (D)TLS connections. The default port is 5683 if not given any other value. +*-c* certfile:: + Use the specified PEM file which contains the CERTIFICATE and PRIVATE + KEY information. This argument requires (D)TLS with PKI to be available. + +*-k* key:: + Pre-shared key to use for inbound connections. This cannot be empty if defined. + This argument requires (D)TLS with PSK to be available. + *Note:* if -c is defined, you need to define -k as well to have the server + support both PSK and PKI. + +*-h* hint:: + Pre-shared key hint to use for inbound connections. The default is 'CoAP'. + This cannot be empty if defined. + +*-l* list:: + Fail to send some datagrams specified by a comma separated list of + numbers or number intervals (debugging only). + +*-l* loss%:: + Randomly failed to send datagams with the specified probability - 100% + all datagrams, 0% no datagrams (debugging only). + *-v* num:: The verbosity level to use (default: 3, maximum is 9). @@ -42,25 +66,32 @@ EXAMPLES ---- coap-server -A ::1 ---- -Let the server listen on localhost (port 5683). +Let the server listen on localhost (port '5683'). + +* Example +---- +coap-server -A ::1 -k mysecretKey -h myhint +---- +Let the server listen on localhost (port '5683' and '5684') with the server +set up for PSK authentication. * Example ---- coap-server -A ::1 -p 13011 ---- -Quite the same, except listening port is '13011' (and not the default port -5683). +The same, except the listening port is '13011' (and not the default port +'5683'). * Example ---- -coap-server -A 2001:db8:81a8:0:6ef0:dead:feed:beef -v 5 +coap-server -A 2001:db8:81a8:0:6ef0:dead:feed:beef -v 5 ---- The listening address is set to '2001:db8:81a8:0:6ef0:dead:feed:beef' and the verbosity level is set to '5'. * Example ---- -coap-server -A 2001:db8:81a8:0:6ef0:dead:feed:beef -g FF02::FD +coap-server -A 2001:db8:81a8:0:6ef0:dead:feed:beef -g FF02::FD ---- Set listening address to '2001:db8:81a8:0:6ef0:dead:feed:beef' and join the All CoAP Nodes multicast group 'FF02::FD'.