summaryrefslogtreecommitdiff
path: root/manual/html_node/DTLS-echo-server-with-X_002e509-authentication.html
blob: afa19a91f5ff9932fd9d32643fa96b1d020d2613 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- This manual is last updated 4 March 2015 for version
3.5.4 of GnuTLS.

Copyright (C) 2001-2015 Free Software Foundation, Inc.\\
Copyright (C) 2001-2015 Nikos Mavrogiannopoulos

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.  A
copy of the license is included in the section entitled "GNU Free
Documentation License". -->
<!-- Created by GNU Texinfo 6.1, http://www.gnu.org/software/texinfo/ -->
<head>
<title>GnuTLS 3.5.4: DTLS echo server with X.509 authentication</title>

<meta name="description" content="GnuTLS 3.5.4: DTLS echo server with X.509 authentication">
<meta name="keywords" content="GnuTLS 3.5.4: DTLS echo server with X.509 authentication">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Function-and-Data-Index.html#Function-and-Data-Index" rel="index" title="Function and Data Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Server-examples.html#Server-examples" rel="up" title="Server examples">
<link href="OCSP-example.html#OCSP-example" rel="next" title="OCSP example">
<link href="Echo-server-with-anonymous-authentication.html#Echo-server-with-anonymous-authentication" rel="prev" title="Echo server with anonymous authentication">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.indentedblock {margin-right: 0em}
blockquote.smallindentedblock {margin-right: 0em; font-size: smaller}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
kbd {font-style: oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nolinebreak {white-space: nowrap}
span.roman {font-family: initial; font-weight: normal}
span.sansserif {font-family: sans-serif; font-weight: normal}
ul.no-bullet {list-style: none}
body { 
	margin: 2%;
	padding: 0 5%;
	background: #ffffff;
}
h1,h2,h3,h4,h5 {
    font-weight: bold;
    padding: 5px 5px 5px 5px;
    background-color: #c2e0ff;
    color: #336699;
}
h1 {
    padding: 2em 2em 2em 5%;
    color: white;
    background: #336699;
    text-align: center;
    letter-spacing: 3px;
}
h2 { text-decoration: underline; }
pre {
  margin: 0 5%;
  padding: 0.5em;
}
pre.example,pre.verbatim {
  padding-bottom: 1em;

  border: solid #c2e0ff;
  background: #f0faff;
  border-width: 1px 1px 1px 5px;
  margin: 1em auto;
  width: 90%;
}

div.node {
  margin: 0 -5% 0 -2%;
  padding: 0.5em 0.5em;
  margin-top: 0.5em;
  margin-bottom: 0.5em;
  font-weight: bold;
}
dd, li {
  padding-top: 0.1em;
  padding-bottom: 0.1em;
}
div.float {

  margin-bottom: 0.5em;
  text-align: center;
}

table {
  text-align: left;
  margin-left:auto;
  margin-right:auto;
  border-spacing: 7px;
  width: 50%;
}

th {
  padding: 0;
  color: #336699;
  background-color: #c2e0ff;
  border: solid #000000;
  border-width: 0px;
  margin: 1em auto;
  text-align: center;
  margin-left:auto;
  margin-right:auto;
}

td {
  padding: 0;
  border: solid #000000;
  background-color: #f0faff;
  border-width: 0px;
  margin: 1em auto;
  text-align: left;
  margin-left:auto;
  margin-right:auto;
  padding-left: 1em;
}

dl {
  text-align: left;
  margin-left:auto;
  margin-right:auto;
  width: 50%;

  padding-left: 1em;
  border: solid #c2e0ff;
  background: #f0faff;
  border-width: 5px 1px 1px 1px;
  margin: 1em auto;
}

-->
</style>


</head>

<body lang="en">
<a name="DTLS-echo-server-with-X_002e509-authentication"></a>
<div class="header">
<p>
Previous: <a href="Echo-server-with-anonymous-authentication.html#Echo-server-with-anonymous-authentication" accesskey="p" rel="prev">Echo server with anonymous authentication</a>, Up: <a href="Server-examples.html#Server-examples" accesskey="u" rel="up">Server examples</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Function-and-Data-Index.html#Function-and-Data-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="DTLS-echo-server-with-X_002e509-authentication-1"></a>
<h4 class="subsection">7.2.4 DTLS echo server with <acronym>X.509</acronym> authentication</h4>

<p>This example is a very simple echo server using Datagram TLS and 
<acronym>X.509</acronym> authentication.
</p>
<pre class="verbatim">/* This example code is placed in the public domain. */

#ifdef HAVE_CONFIG_H
#include &lt;config.h&gt;
#endif

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;errno.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;arpa/inet.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;sys/select.h&gt;
#include &lt;netdb.h&gt;
#include &lt;string.h&gt;
#include &lt;unistd.h&gt;
#include &lt;gnutls/gnutls.h&gt;
#include &lt;gnutls/dtls.h&gt;

#define KEYFILE &quot;key.pem&quot;
#define CERTFILE &quot;cert.pem&quot;
#define CAFILE &quot;/etc/ssl/certs/ca-certificates.crt&quot;
#define CRLFILE &quot;crl.pem&quot;

/* This is a sample DTLS echo server, using X.509 authentication.
 * Note that error checking is minimal to simplify the example.
 */

#define MAX_BUFFER 1024
#define PORT 5557

typedef struct {
        gnutls_session_t session;
        int fd;
        struct sockaddr *cli_addr;
        socklen_t cli_addr_size;
} priv_data_st;

static int pull_timeout_func(gnutls_transport_ptr_t ptr, unsigned int ms);
static ssize_t push_func(gnutls_transport_ptr_t p, const void *data,
                         size_t size);
static ssize_t pull_func(gnutls_transport_ptr_t p, void *data,
                         size_t size);
static const char *human_addr(const struct sockaddr *sa, socklen_t salen,
                              char *buf, size_t buflen);
static int wait_for_connection(int fd);
static int generate_dh_params(void);

/* Use global credentials and parameters to simplify
 * the example. */
static gnutls_certificate_credentials_t x509_cred;
static gnutls_priority_t priority_cache;
static gnutls_dh_params_t dh_params;

int main(void)
{
        int listen_sd;
        int sock, ret;
        struct sockaddr_in sa_serv;
        struct sockaddr_in cli_addr;
        socklen_t cli_addr_size;
        gnutls_session_t session;
        char buffer[MAX_BUFFER];
        priv_data_st priv;
        gnutls_datum_t cookie_key;
        gnutls_dtls_prestate_st prestate;
        int mtu = 1400;
        unsigned char sequence[8];

        /* this must be called once in the program
         */
        gnutls_global_init();

        gnutls_certificate_allocate_credentials(&amp;x509_cred);
        gnutls_certificate_set_x509_trust_file(x509_cred, CAFILE,
                                               GNUTLS_X509_FMT_PEM);

        gnutls_certificate_set_x509_crl_file(x509_cred, CRLFILE,
                                             GNUTLS_X509_FMT_PEM);

        ret =
            gnutls_certificate_set_x509_key_file(x509_cred, CERTFILE,
                                                 KEYFILE,
                                                 GNUTLS_X509_FMT_PEM);
        if (ret &lt; 0) {
                printf(&quot;No certificate or key were found\n&quot;);
                exit(1);
        }

        generate_dh_params();

        gnutls_certificate_set_dh_params(x509_cred, dh_params);

        gnutls_priority_init(&amp;priority_cache,
                             &quot;PERFORMANCE:-VERS-TLS-ALL:+VERS-DTLS1.0:%SERVER_PRECEDENCE&quot;,
                             NULL);

        gnutls_key_generate(&amp;cookie_key, GNUTLS_COOKIE_KEY_SIZE);

        /* Socket operations
         */
        listen_sd = socket(AF_INET, SOCK_DGRAM, 0);

        memset(&amp;sa_serv, '\0', sizeof(sa_serv));
        sa_serv.sin_family = AF_INET;
        sa_serv.sin_addr.s_addr = INADDR_ANY;
        sa_serv.sin_port = htons(PORT);

        {                       /* DTLS requires the IP don't fragment (DF) bit to be set */
#if defined(IP_DONTFRAG)
                int optval = 1;
                setsockopt(listen_sd, IPPROTO_IP, IP_DONTFRAG,
                           (const void *) &amp;optval, sizeof(optval));
#elif defined(IP_MTU_DISCOVER)
                int optval = IP_PMTUDISC_DO;
                setsockopt(listen_sd, IPPROTO_IP, IP_MTU_DISCOVER,
                           (const void *) &amp;optval, sizeof(optval));
#endif
        }

        bind(listen_sd, (struct sockaddr *) &amp;sa_serv, sizeof(sa_serv));

        printf(&quot;UDP server ready. Listening to port '%d'.\n\n&quot;, PORT);

        for (;;) {
                printf(&quot;Waiting for connection...\n&quot;);
                sock = wait_for_connection(listen_sd);
                if (sock &lt; 0)
                        continue;

                cli_addr_size = sizeof(cli_addr);
                ret = recvfrom(sock, buffer, sizeof(buffer), MSG_PEEK,
                               (struct sockaddr *) &amp;cli_addr,
                               &amp;cli_addr_size);
                if (ret &gt; 0) {
                        memset(&amp;prestate, 0, sizeof(prestate));
                        ret =
                            gnutls_dtls_cookie_verify(&amp;cookie_key,
                                                      &amp;cli_addr,
                                                      sizeof(cli_addr),
                                                      buffer, ret,
                                                      &amp;prestate);
                        if (ret &lt; 0) {  /* cookie not valid */
                                priv_data_st s;

                                memset(&amp;s, 0, sizeof(s));
                                s.fd = sock;
                                s.cli_addr = (void *) &amp;cli_addr;
                                s.cli_addr_size = sizeof(cli_addr);

                                printf
                                    (&quot;Sending hello verify request to %s\n&quot;,
                                     human_addr((struct sockaddr *)
                                                &amp;cli_addr,
                                                sizeof(cli_addr), buffer,
                                                sizeof(buffer)));

                                gnutls_dtls_cookie_send(&amp;cookie_key,
                                                        &amp;cli_addr,
                                                        sizeof(cli_addr),
                                                        &amp;prestate,
                                                        (gnutls_transport_ptr_t)
                                                        &amp; s, push_func);

                                /* discard peeked data */
                                recvfrom(sock, buffer, sizeof(buffer), 0,
                                         (struct sockaddr *) &amp;cli_addr,
                                         &amp;cli_addr_size);
                                usleep(100);
                                continue;
                        }
                        printf(&quot;Accepted connection from %s\n&quot;,
                               human_addr((struct sockaddr *)
                                          &amp;cli_addr, sizeof(cli_addr),
                                          buffer, sizeof(buffer)));
                } else
                        continue;

                gnutls_init(&amp;session, GNUTLS_SERVER | GNUTLS_DATAGRAM);
                gnutls_priority_set(session, priority_cache);
                gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
                                       x509_cred);

                gnutls_dtls_prestate_set(session, &amp;prestate);
                gnutls_dtls_set_mtu(session, mtu);

                priv.session = session;
                priv.fd = sock;
                priv.cli_addr = (struct sockaddr *) &amp;cli_addr;
                priv.cli_addr_size = sizeof(cli_addr);

                gnutls_transport_set_ptr(session, &amp;priv);
                gnutls_transport_set_push_function(session, push_func);
                gnutls_transport_set_pull_function(session, pull_func);
                gnutls_transport_set_pull_timeout_function(session,
                                                           pull_timeout_func);

                do {
                        ret = gnutls_handshake(session);
                }
                while (ret == GNUTLS_E_INTERRUPTED
                       || ret == GNUTLS_E_AGAIN);
                /* Note that DTLS may also receive GNUTLS_E_LARGE_PACKET.
                 * In that case the MTU should be adjusted.
                 */

                if (ret &lt; 0) {
                        fprintf(stderr, &quot;Error in handshake(): %s\n&quot;,
                                gnutls_strerror(ret));
                        gnutls_deinit(session);
                        continue;
                }

                printf(&quot;- Handshake was completed\n&quot;);

                for (;;) {
                        do {
                                ret =
                                    gnutls_record_recv_seq(session, buffer,
                                                           MAX_BUFFER,
                                                           sequence);
                        }
                        while (ret == GNUTLS_E_AGAIN
                               || ret == GNUTLS_E_INTERRUPTED);

                        if (ret &lt; 0 &amp;&amp; gnutls_error_is_fatal(ret) == 0) {
                                fprintf(stderr, &quot;*** Warning: %s\n&quot;,
                                        gnutls_strerror(ret));
                                continue;
                        } else if (ret &lt; 0) {
                                fprintf(stderr, &quot;Error in recv(): %s\n&quot;,
                                        gnutls_strerror(ret));
                                break;
                        }

                        if (ret == 0) {
                                printf(&quot;EOF\n\n&quot;);
                                break;
                        }

                        buffer[ret] = 0;
                        printf
                            (&quot;received[%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x]: %s\n&quot;,
                             sequence[0], sequence[1], sequence[2],
                             sequence[3], sequence[4], sequence[5],
                             sequence[6], sequence[7], buffer);

                        /* reply back */
                        ret = gnutls_record_send(session, buffer, ret);
                        if (ret &lt; 0) {
                                fprintf(stderr, &quot;Error in send(): %s\n&quot;,
                                        gnutls_strerror(ret));
                                break;
                        }
                }

                gnutls_bye(session, GNUTLS_SHUT_WR);
                gnutls_deinit(session);

        }
        close(listen_sd);

        gnutls_certificate_free_credentials(x509_cred);
        gnutls_priority_deinit(priority_cache);

        gnutls_global_deinit();

        return 0;

}

static int wait_for_connection(int fd)
{
        fd_set rd, wr;
        int n;

        FD_ZERO(&amp;rd);
        FD_ZERO(&amp;wr);

        FD_SET(fd, &amp;rd);

        /* waiting part */
        n = select(fd + 1, &amp;rd, &amp;wr, NULL, NULL);
        if (n == -1 &amp;&amp; errno == EINTR)
                return -1;
        if (n &lt; 0) {
                perror(&quot;select()&quot;);
                exit(1);
        }

        return fd;
}

/* Wait for data to be received within a timeout period in milliseconds
 */
static int pull_timeout_func(gnutls_transport_ptr_t ptr, unsigned int ms)
{
        fd_set rfds;
        struct timeval tv;
        priv_data_st *priv = ptr;
        struct sockaddr_in cli_addr;
        socklen_t cli_addr_size;
        int ret;
        char c;

        FD_ZERO(&amp;rfds);
        FD_SET(priv-&gt;fd, &amp;rfds);

        tv.tv_sec = 0;
        tv.tv_usec = ms * 1000;

        while (tv.tv_usec &gt;= 1000000) {
                tv.tv_usec -= 1000000;
                tv.tv_sec++;
        }

        ret = select(priv-&gt;fd + 1, &amp;rfds, NULL, NULL, &amp;tv);

        if (ret &lt;= 0)
                return ret;

        /* only report ok if the next message is from the peer we expect
         * from 
         */
        cli_addr_size = sizeof(cli_addr);
        ret =
            recvfrom(priv-&gt;fd, &amp;c, 1, MSG_PEEK,
                     (struct sockaddr *) &amp;cli_addr, &amp;cli_addr_size);
        if (ret &gt; 0) {
                if (cli_addr_size == priv-&gt;cli_addr_size
                    &amp;&amp; memcmp(&amp;cli_addr, priv-&gt;cli_addr,
                              sizeof(cli_addr)) == 0)
                        return 1;
        }

        return 0;
}

static ssize_t
push_func(gnutls_transport_ptr_t p, const void *data, size_t size)
{
        priv_data_st *priv = p;

        return sendto(priv-&gt;fd, data, size, 0, priv-&gt;cli_addr,
                      priv-&gt;cli_addr_size);
}

static ssize_t pull_func(gnutls_transport_ptr_t p, void *data, size_t size)
{
        priv_data_st *priv = p;
        struct sockaddr_in cli_addr;
        socklen_t cli_addr_size;
        char buffer[64];
        int ret;

        cli_addr_size = sizeof(cli_addr);
        ret =
            recvfrom(priv-&gt;fd, data, size, 0,
                     (struct sockaddr *) &amp;cli_addr, &amp;cli_addr_size);
        if (ret == -1)
                return ret;

        if (cli_addr_size == priv-&gt;cli_addr_size
            &amp;&amp; memcmp(&amp;cli_addr, priv-&gt;cli_addr, sizeof(cli_addr)) == 0)
                return ret;

        printf(&quot;Denied connection from %s\n&quot;,
               human_addr((struct sockaddr *)
                          &amp;cli_addr, sizeof(cli_addr), buffer,
                          sizeof(buffer)));

        gnutls_transport_set_errno(priv-&gt;session, EAGAIN);
        return -1;
}

static const char *human_addr(const struct sockaddr *sa, socklen_t salen,
                              char *buf, size_t buflen)
{
        const char *save_buf = buf;
        size_t l;

        if (!buf || !buflen)
                return NULL;

        *buf = '\0';

        switch (sa-&gt;sa_family) {
#if HAVE_IPV6
        case AF_INET6:
                snprintf(buf, buflen, &quot;IPv6 &quot;);
                break;
#endif

        case AF_INET:
                snprintf(buf, buflen, &quot;IPv4 &quot;);
                break;
        }

        l = strlen(buf);
        buf += l;
        buflen -= l;

        if (getnameinfo(sa, salen, buf, buflen, NULL, 0, NI_NUMERICHOST) !=
            0)
                return NULL;

        l = strlen(buf);
        buf += l;
        buflen -= l;

        strncat(buf, &quot; port &quot;, buflen);

        l = strlen(buf);
        buf += l;
        buflen -= l;

        if (getnameinfo(sa, salen, NULL, 0, buf, buflen, NI_NUMERICSERV) !=
            0)
                return NULL;

        return save_buf;
}

static int generate_dh_params(void)
{
        int bits = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH,
                                               GNUTLS_SEC_PARAM_LEGACY);

        /* Generate Diffie-Hellman parameters - for use with DHE
         * kx algorithms. When short bit length is used, it might
         * be wise to regenerate parameters often.
         */
        gnutls_dh_params_init(&amp;dh_params);
        gnutls_dh_params_generate2(dh_params, bits);

        return 0;
}
</pre>

<hr>
<div class="header">
<p>
Previous: <a href="Echo-server-with-anonymous-authentication.html#Echo-server-with-anonymous-authentication" accesskey="p" rel="prev">Echo server with anonymous authentication</a>, Up: <a href="Server-examples.html#Server-examples" accesskey="u" rel="up">Server examples</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Function-and-Data-Index.html#Function-and-Data-Index" title="Index" rel="index">Index</a>]</p>
</div>



</body>
</html>