Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / extlibs / tinydtls / tests / dtls-client.c
1 #include "tinydtls.h" 
2
3 /* This is needed for apple */
4 #define __APPLE_USE_RFC_3542
5
6 #include <stdio.h>
7 #include <string.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <ctype.h>
11 #include <netinet/in.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <sys/time.h>
15 #include <arpa/inet.h>
16 #include <netdb.h>
17 #include <signal.h>
18
19 #include "global.h" 
20 #include "debug.h" 
21 #include "dtls.h" 
22
23 #define DEFAULT_PORT 20220
24
25 #define PSK_CLIENT_IDENTITY  "Client_identity"
26 #define PSK_SERVER_IDENTITY  "Server_identity"
27 #define PSK_DEFAULT_KEY      "secretPSK"
28 #define PSK_OPTIONS          "i:s:k:"
29
30 #ifdef __GNUC__
31 #define UNUSED_PARAM __attribute__((unused))
32 #else
33 #define UNUSED_PARAM
34 #endif /* __GNUC__ */
35
36 static char buf[200];
37 static size_t len = 0;
38
39 typedef struct {
40   size_t length;               /* length of string */
41   unsigned char *s;            /* string data */
42 } dtls_str;
43
44 static dtls_str output_file = { 0, NULL }; /* output file name */
45
46 static dtls_context_t *dtls_context = NULL;
47 static dtls_context_t *orig_dtls_context = NULL;
48
49
50 static const unsigned char ecdsa_priv_key[] = {
51                         0x41, 0xC1, 0xCB, 0x6B, 0x51, 0x24, 0x7A, 0x14,
52                         0x43, 0x21, 0x43, 0x5B, 0x7A, 0x80, 0xE7, 0x14,
53                         0x89, 0x6A, 0x33, 0xBB, 0xAD, 0x72, 0x94, 0xCA,
54                         0x40, 0x14, 0x55, 0xA1, 0x94, 0xA9, 0x49, 0xFA};
55
56 static const unsigned char ecdsa_pub_key_x[] = {
57                         0x36, 0xDF, 0xE2, 0xC6, 0xF9, 0xF2, 0xED, 0x29,
58                         0xDA, 0x0A, 0x9A, 0x8F, 0x62, 0x68, 0x4E, 0x91,
59                         0x63, 0x75, 0xBA, 0x10, 0x30, 0x0C, 0x28, 0xC5,
60                         0xE4, 0x7C, 0xFB, 0xF2, 0x5F, 0xA5, 0x8F, 0x52};
61
62 static const unsigned char ecdsa_pub_key_y[] = {
63                         0x71, 0xA0, 0xD4, 0xFC, 0xDE, 0x1A, 0xB8, 0x78,
64                         0x5A, 0x3C, 0x78, 0x69, 0x35, 0xA7, 0xCF, 0xAB,
65                         0xE9, 0x3F, 0x98, 0x72, 0x09, 0xDA, 0xED, 0x0B,
66                         0x4F, 0xAB, 0xC3, 0x6F, 0xC7, 0x72, 0xF8, 0x29};
67
68 #ifdef DTLS_PSK
69 ssize_t
70 read_from_file(char *arg, unsigned char *buf, size_t max_buf_len) {
71   FILE *f;
72   ssize_t result = 0;
73
74   f = fopen(arg, "r");
75   if (f == NULL)
76     return -1;
77
78   while (!feof(f)) {
79     size_t bytes_read;
80     bytes_read = fread(buf, 1, max_buf_len, f);
81     if (ferror(f)) {
82       result = -1;
83       break;
84     }
85
86     buf += bytes_read;
87     result += bytes_read;
88     max_buf_len -= bytes_read;
89   }
90
91   fclose(f);
92   return result;
93 }
94
95 /* The PSK information for DTLS */
96 #define PSK_ID_MAXLEN 256
97 #define PSK_MAXLEN 256
98 static unsigned char psk_client_id[PSK_ID_MAXLEN];
99 static size_t psk_client_id_length = 0;
100 static unsigned char psk_server_id[PSK_ID_MAXLEN];
101 static size_t psk_server_id_length = 0;
102 static unsigned char psk_key[PSK_MAXLEN];
103 static size_t psk_key_length = 0;
104
105 /* This function is the "key store" for tinyDTLS. It is called to
106  * retrieve a key for the given identity within this particular
107  * session. */
108 static int
109 get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
110             const session_t *session UNUSED_PARAM,
111             dtls_credentials_type_t type,
112             const unsigned char *id, size_t id_len,
113             unsigned char *result, size_t result_length) {
114
115   switch (type) {
116   case DTLS_PSK_IDENTITY:
117     if (id_len) {
118       dtls_debug("got psk_identity_hint: '%.*s'\n", id_len, id);
119     }
120
121     if (result_length < psk_client_id_length) {
122       dtls_warn("cannot set psk_identity -- buffer too small\n");
123       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
124     }
125
126     memcpy(result, psk_client_id, psk_client_id_length);
127     return psk_client_id_length;
128   case DTLS_PSK_KEY:
129     if (id_len != psk_server_id_length || memcmp(psk_server_id, id, id_len) != 0) {
130       dtls_warn("PSK for unknown id requested, exiting\n");
131       return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
132     } else if (result_length < psk_key_length) {
133       dtls_warn("cannot set psk -- buffer too small\n");
134       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
135     }
136
137     memcpy(result, psk_key, psk_key_length);
138     return psk_key_length;
139   default:
140     dtls_warn("unsupported request type: %d\n", type);
141   }
142
143   return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
144 }
145 #endif /* DTLS_PSK */
146
147 #ifdef DTLS_ECC
148 static int
149 get_ecdsa_key(struct dtls_context_t *ctx,
150               const session_t *session,
151               const dtls_ecc_key_t **result) {
152   static const dtls_ecc_key_t ecdsa_key = {
153     .curve = DTLS_ECDH_CURVE_SECP256R1,
154     .priv_key = ecdsa_priv_key,
155     .pub_key_x = ecdsa_pub_key_x,
156     .pub_key_y = ecdsa_pub_key_y
157   };
158
159   *result = &ecdsa_key;
160   return 0;
161 }
162
163 static int
164 verify_ecdsa_key(struct dtls_context_t *ctx,
165                  const session_t *session,
166                  const unsigned char *other_pub_x,
167                  const unsigned char *other_pub_y,
168                  size_t key_size) {
169   return 0;
170 }
171 #endif /* DTLS_ECC */
172
173 static void
174 try_send(struct dtls_context_t *ctx, session_t *dst) {
175   int res;
176   res = dtls_write(ctx, dst, (uint8 *)buf, len);
177   if (res >= 0) {
178     memmove(buf, buf + res, len - res);
179     len -= res;
180   }
181 }
182
183 static void
184 handle_stdin() {
185   if (fgets(buf + len, sizeof(buf) - len, stdin))
186     len += strlen(buf + len);
187 }
188
189 static int
190 read_from_peer(struct dtls_context_t *ctx, 
191                session_t *session, uint8 *data, size_t len) {
192   size_t i;
193   for (i = 0; i < len; i++)
194     printf("%c", data[i]);
195   return 0;
196 }
197
198 static int
199 send_to_peer(struct dtls_context_t *ctx, 
200              session_t *session, uint8 *data, size_t len) {
201
202   int fd = *(int *)dtls_get_app_data(ctx);
203   return sendto(fd, data, len, MSG_DONTWAIT,
204                 &session->addr.sa, session->size);
205 }
206
207 static int
208 dtls_handle_read(struct dtls_context_t *ctx) {
209   int fd;
210   session_t session;
211 #define MAX_READ_BUF 2000
212   static uint8 buf[MAX_READ_BUF];
213   int len;
214
215   fd = *(int *)dtls_get_app_data(ctx);
216   
217   if (!fd)
218     return -1;
219
220   memset(&session, 0, sizeof(session_t));
221   session.size = sizeof(session.addr);
222   len = recvfrom(fd, buf, MAX_READ_BUF, 0, 
223                  &session.addr.sa, &session.size);
224   
225   if (len < 0) {
226     perror("recvfrom");
227     return -1;
228   } else {
229     dtls_dsrv_log_addr(DTLS_LOG_DEBUG, "peer", &session);
230     dtls_debug_dump("bytes from peer", buf, len);
231   }
232
233   return dtls_handle_message(ctx, &session, buf, len);
234 }    
235
236 static void dtls_handle_signal(int sig)
237 {
238   dtls_free_context(dtls_context);
239   dtls_free_context(orig_dtls_context);
240   signal(sig, SIG_DFL);
241   kill(getpid(), sig);
242 }
243
244 /* stolen from libcoap: */
245 static int
246 resolve_address(const char *server, struct sockaddr *dst) {
247   
248   struct addrinfo *res, *ainfo;
249   struct addrinfo hints;
250   static char addrstr[256];
251   int error;
252
253   memset(addrstr, 0, sizeof(addrstr));
254   if (server && strlen(server) > 0)
255     memcpy(addrstr, server, strlen(server));
256   else
257     memcpy(addrstr, "localhost", 9);
258
259   memset ((char *)&hints, 0, sizeof(hints));
260   hints.ai_socktype = SOCK_DGRAM;
261   hints.ai_family = AF_UNSPEC;
262
263   error = getaddrinfo(addrstr, "", &hints, &res);
264
265   if (error != 0) {
266     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
267     return error;
268   }
269
270   for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
271
272     switch (ainfo->ai_family) {
273     case AF_INET6:
274     case AF_INET:
275
276       memcpy(dst, ainfo->ai_addr, ainfo->ai_addrlen);
277       return ainfo->ai_addrlen;
278     default:
279       ;
280     }
281   }
282
283   freeaddrinfo(res);
284   return -1;
285 }
286
287 /*---------------------------------------------------------------------------*/
288 static void
289 usage( const char *program, const char *version) {
290   const char *p;
291
292   p = strrchr( program, '/' );
293   if ( p )
294     program = ++p;
295
296   fprintf(stderr, "%s v%s -- DTLS client implementation\n"
297           "(c) 2011-2014 Olaf Bergmann <bergmann@tzi.org>\n\n"
298 #ifdef DTLS_PSK
299           "usage: %s [-i file] [-s file] [-k file] [-o file] [-p port] [-v num] [-c num] addr [port]\n"
300 #else /*  DTLS_PSK */
301           "usage: %s [-o file] [-p port] [-v num] [-c num] addr [port]\n"
302 #endif /* DTLS_PSK */
303 #ifdef DTLS_PSK
304           "\t-i file\t\tread PSK Client identity from file\n"
305           "\t-s file\t\tread PSK Server identity from file\n"
306           "\t-k file\t\tread pre-shared key from file\n"
307 #endif /* DTLS_PSK */
308           "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n"
309           "\t-p port\t\tlisten on specified port (default is %d)\n"
310           "\t-v num\t\tverbosity level (default: 3)\n"
311           "\t-c num\t\tcipher suite (default: 1)\n"
312           "\t\t\t1: TLS_ECDH_anon_WITH_AES_128_CBC_SHA \n"
313           "\t\t\t2: TLS_PSK_WITH_AES_128_CCM_8\n"
314           "\t\t\t3: TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8\n",
315            program, version, program, DEFAULT_PORT);
316 }
317
318 static dtls_handler_t cb = {
319   .write = send_to_peer,
320   .read  = read_from_peer,
321   .event = NULL,
322 #ifdef DTLS_PSK
323   .get_psk_info = get_psk_info,
324 #endif /* DTLS_PSK */
325 #ifdef DTLS_ECC
326   .get_ecdsa_key = get_ecdsa_key,
327   .verify_ecdsa_key = verify_ecdsa_key
328 #endif /* DTLS_ECC */
329 };
330
331 #define DTLS_CLIENT_CMD_CLOSE "client:close"
332 #define DTLS_CLIENT_CMD_RENEGOTIATE "client:renegotiate"
333
334 /* As per RFC 6347 section 4.2.8, DTLS Server should support requests
335  * from clients who have silently abandoned the existing association
336  * and initiated a new handshake request by sending a ClientHello.
337  * Below command tests this feature.
338  */
339 #define DTLS_CLIENT_CMD_REHANDSHAKE "client:rehandshake"
340
341 int 
342 main(int argc, char **argv) {
343   fd_set rfds, wfds;
344   struct timeval timeout;
345   unsigned short port = DEFAULT_PORT;
346   char port_str[NI_MAXSERV] = "0";
347   log_t log_level = DTLS_LOG_WARN;
348   int fd, result;
349   int on = 1;
350   dtls_cipher_t selected_cipher = TLS_ECDH_anon_WITH_AES_128_CBC_SHA;
351   dtls_cipher_enable_t ecdh_anon_enalbe = DTLS_CIPHER_ENABLE;
352   int opt, res;
353   session_t dst;
354
355   dtls_init();
356   snprintf(port_str, sizeof(port_str), "%d", port);
357
358 #ifdef DTLS_PSK
359   psk_client_id_length = strlen(PSK_CLIENT_IDENTITY);
360   psk_server_id_length = strlen(PSK_SERVER_IDENTITY);
361   psk_key_length = strlen(PSK_DEFAULT_KEY);
362   memcpy(psk_client_id, PSK_CLIENT_IDENTITY, psk_client_id_length);
363   memcpy(psk_server_id, PSK_SERVER_IDENTITY, psk_server_id_length);
364   memcpy(psk_key, PSK_DEFAULT_KEY, psk_key_length);
365 #endif /* DTLS_PSK */
366
367   while ((opt = getopt(argc, argv, "p:o:v:c:" PSK_OPTIONS)) != -1) {
368     switch (opt) {
369 #ifdef DTLS_PSK
370     case 'i' : {
371       ssize_t result = read_from_file(optarg, psk_client_id, PSK_ID_MAXLEN);
372       if (result < 0) {
373         dtls_warn("cannot read Client PSK identity\n");
374       } else {
375         psk_client_id_length = result;
376       }
377       break;
378     }
379     case 's' : {
380       ssize_t result = read_from_file(optarg, psk_server_id, PSK_ID_MAXLEN);
381       if (result < 0) {
382         dtls_warn("cannot read Server PSK identity\n");
383       } else {
384         psk_server_id_length = result;
385       }
386       break;
387     }
388     case 'k' : {
389       ssize_t result = read_from_file(optarg, psk_key, PSK_MAXLEN);
390       if (result < 0) {
391         dtls_warn("cannot read PSK\n");
392       } else {
393         psk_key_length = result;
394       }
395       break;
396     }
397 #endif /* DTLS_PSK */
398     case 'p' :
399       strncpy(port_str, optarg, NI_MAXSERV-1);
400       port_str[NI_MAXSERV - 1] = '\0';
401       break;
402     case 'o' :
403       output_file.length = strlen(optarg);
404       output_file.s = (unsigned char *)malloc(output_file.length + 1);
405       
406       if (!output_file.s) {
407         dtls_crit("cannot set output file: insufficient memory\n");
408         exit(-1);
409       } else {
410         /* copy filename including trailing zero */
411         memcpy(output_file.s, optarg, output_file.length + 1);
412       }
413       break;
414     case 'v' :
415       log_level = strtol(optarg, NULL, 10);
416       break;
417     case 'c':
418       if( strcmp(optarg, "1") == 0)
419       {
420           selected_cipher = TLS_ECDH_anon_WITH_AES_128_CBC_SHA;
421           ecdh_anon_enalbe = DTLS_CIPHER_ENABLE;
422       }
423       else if( strcmp(optarg, "2") == 0)
424       {
425           selected_cipher = TLS_PSK_WITH_AES_128_CCM_8 ;
426           ecdh_anon_enalbe = DTLS_CIPHER_DISABLE;
427       }
428       else if( strcmp(optarg, "3") == 0)
429       {
430           selected_cipher = TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ;
431           ecdh_anon_enalbe = DTLS_CIPHER_DISABLE;
432       }
433       break;
434     default:
435       usage(argv[0], dtls_package_version());
436       exit(1);
437     }
438   }
439
440   dtls_set_log_level(log_level);
441   
442   if (argc <= optind) {
443     usage(argv[0], dtls_package_version());
444     exit(1);
445   }
446   
447   memset(&dst, 0, sizeof(session_t));
448   /* resolve destination address where server should be sent */
449   res = resolve_address(argv[optind++], &dst.addr.sa);
450   if (res < 0) {
451     dtls_emerg("failed to resolve address\n");
452     exit(-1);
453   }
454   dst.size = res;
455
456   /* use port number from command line when specified or the listen
457      port, otherwise */
458   dst.addr.sin.sin_port = htons(atoi(optind < argc ? argv[optind++] : port_str));
459
460   
461   /* init socket and set it to non-blocking */
462   fd = socket(dst.addr.sa.sa_family, SOCK_DGRAM, 0);
463
464   if (fd < 0) {
465     dtls_alert("socket: %s\n", strerror(errno));
466     return 0;
467   }
468
469   if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) ) < 0) {
470     dtls_alert("setsockopt SO_REUSEADDR: %s\n", strerror(errno));
471   }
472 #if 0
473   flags = fcntl(fd, F_GETFL, 0);
474   if (flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
475     dtls_alert("fcntl: %s\n", strerror(errno));
476     goto error;
477   }
478 #endif
479   on = 1;
480 #ifdef IPV6_RECVPKTINFO
481   if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on) ) < 0) {
482 #else /* IPV6_RECVPKTINFO */
483   if (setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on) ) < 0) {
484 #endif /* IPV6_RECVPKTINFO */
485     dtls_alert("setsockopt IPV6_PKTINFO: %s\n", strerror(errno));
486   }
487
488   if (signal(SIGINT, dtls_handle_signal) == SIG_ERR) {
489     dtls_alert("An error occurred while setting a signal handler.\n");
490     return EXIT_FAILURE;
491   }
492
493   dtls_context = dtls_new_context(&fd);
494   if (!dtls_context) {
495     dtls_emerg("cannot create context\n");
496     exit(-1);
497   }
498
499
500   /* select cipher suite */
501   dtls_select_cipher(dtls_context, selected_cipher);
502
503   /* enable/disable tls_ecdh_anon_with_aes_128_cbc_sha */
504   dtls_enables_anon_ecdh(dtls_context, ecdh_anon_enalbe);
505
506   dtls_set_handler(dtls_context, &cb);
507
508   dtls_connect(dtls_context, &dst);
509
510   while (1) {
511     FD_ZERO(&rfds);
512     FD_ZERO(&wfds);
513
514     FD_SET(fileno(stdin), &rfds);
515     FD_SET(fd, &rfds);
516     /* FD_SET(fd, &wfds); */
517     
518     timeout.tv_sec = 5;
519     timeout.tv_usec = 0;
520     
521     result = select(fd+1, &rfds, &wfds, 0, &timeout);
522     
523     if (result < 0) {           /* error */
524       if (errno != EINTR)
525         perror("select");
526     } else if (result == 0) {   /* timeout */
527     } else {                    /* ok */
528       if (FD_ISSET(fd, &wfds))
529         /* FIXME */;
530       else if (FD_ISSET(fd, &rfds))
531         dtls_handle_read(dtls_context);
532       else if (FD_ISSET(fileno(stdin), &rfds))
533         handle_stdin();
534     }
535
536     if (len) {
537       if (len >= strlen(DTLS_CLIENT_CMD_CLOSE) &&
538           !memcmp(buf, DTLS_CLIENT_CMD_CLOSE, strlen(DTLS_CLIENT_CMD_CLOSE))) {
539         printf("client: closing connection\n");
540         dtls_close(dtls_context, &dst);
541         len = 0;
542       } else if (len >= strlen(DTLS_CLIENT_CMD_RENEGOTIATE) &&
543                  !memcmp(buf, DTLS_CLIENT_CMD_RENEGOTIATE, strlen(DTLS_CLIENT_CMD_RENEGOTIATE))) {
544         printf("client: renegotiate connection\n");
545         dtls_renegotiate(dtls_context, &dst);
546         len = 0;
547       } else if (len >= strlen(DTLS_CLIENT_CMD_REHANDSHAKE) &&
548                  !memcmp(buf, DTLS_CLIENT_CMD_REHANDSHAKE, strlen(DTLS_CLIENT_CMD_REHANDSHAKE))) {
549         printf("client: rehandshake connection\n");
550         if (orig_dtls_context == NULL) {
551           /* Cache the current context. We cannot free the current context as it will notify 
552            * the Server to close the connection (which we do not want).
553            */
554           orig_dtls_context = dtls_context;
555           /* Now, Create a new context and attempt to initiate a handshake. */
556           dtls_context = dtls_new_context(&fd);
557           if (!dtls_context) {
558             dtls_emerg("cannot create context\n");
559             exit(-1);
560           }
561           dtls_set_handler(dtls_context, &cb);
562           dtls_connect(dtls_context, &dst);
563         }
564         len = 0;
565       } else {
566         try_send(dtls_context, &dst);
567       }
568     }
569   }
570   
571   dtls_free_context(dtls_context);
572   dtls_free_context(orig_dtls_context);
573   exit(0);
574 }
575