Debian Codegraph @

snmplib/transports/snmpDTLSUDPDomain.c

raw
1 /* Portions of this file are subject to the following copyright(s). See
2 * the Net-SNMP's COPYING file for more details and other copyrights
3 * that may apply:
4 */
5 /*
6 * Portions of this file are copyrighted by:
7 * Copyright Copyright 2003 Sun Microsystems, Inc. All rights reserved.
8 * Use is subject to license terms specified in the COPYING file
9 * distributed with the Net-SNMP package.
10 */
11 /*
12 * See the following web pages for useful documentation on this transport:
13 * http://www.net-snmp.org/wiki/index.php/TUT:Using_TLS
14 * http://www.net-snmp.org/wiki/index.php/Using_DTLS
15 */
16
17 #include <net-snmp/net-snmp-config.h>
18
19 #ifdef HAVE_LIBSSL_DTLS
20
21 #include <net-snmp/net-snmp-features.h>
22
23 netsnmp_feature_require(cert_util);
24 netsnmp_feature_require(sockaddr_size);
25
26 #include "snmpIPBaseDomain.h"
27 #include <net-snmp/library/snmpDTLSUDPDomain.h>
28 #include <net-snmp/library/snmpUDPIPv6Domain.h>
29 #include <net-snmp/library/snmp_assert.h>
30
31 #include <stdio.h>
32 #include <sys/types.h>
33 #include <ctype.h>
34 #include <errno.h>
35
36 #ifdef HAVE_STRING_H
37 #include <string.h>
38 #else
39 #include <strings.h>
40 #endif
41 #ifdef HAVE_STDLIB_H
42 #include <stdlib.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
47 #ifdef HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
49 #endif
50 #ifdef HAVE_NETINET_IN_H
51 #include <netinet/in.h>
52 #endif
53 #ifdef HAVE_ARPA_INET_H
54 #include <arpa/inet.h>
55 #endif
56 #ifdef HAVE_NETDB_H
57 #include <netdb.h>
58 #endif
59 #ifdef HAVE_SYS_UIO_H
60 #include <sys/uio.h>
61 #endif
62
63 #include "../memcheck.h"
64
65 #include <net-snmp/types.h>
66 #include <net-snmp/output_api.h>
67 #include <net-snmp/config_api.h>
68
69 #include <net-snmp/library/snmp_transport.h>
70 #include <net-snmp/library/system.h>
71 #include <net-snmp/library/tools.h>
72 #include <net-snmp/library/callback.h>
73
74 #include "openssl/bio.h"
75 #include "openssl/ssl.h"
76 #include "openssl/err.h"
77 #include "openssl/rand.h"
78
79 #include <net-snmp/library/snmpSocketBaseDomain.h>
80 #include <net-snmp/library/snmpTLSBaseDomain.h>
81 #include <net-snmp/library/snmpUDPDomain.h>
82 #include <net-snmp/library/cert_util.h>
83 #include <net-snmp/library/snmp_openssl.h>
84
85 #ifndef INADDR_NONE
86 #define INADDR_NONE -1
87 #endif
88
89 #define WE_ARE_SERVER 0
90 #define WE_ARE_CLIENT 1
91
92 oid netsnmpDTLSUDPDomain[] = { TRANSPORT_DOMAIN_DTLS_UDP_IP };
93 size_t netsnmpDTLSUDPDomain_len = OID_LENGTH(netsnmpDTLSUDPDomain);
94
95 static netsnmp_tdomain dtlsudpDomain;
96 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
97 static int openssl_addr_index6 = 0;
98 #endif
99
100 /* this stores openssl credentials for each connection since openssl
101 can't do it for us at the moment; hopefully future versions will
102 change */
103 typedef struct bio_cache_s {
104 BIO *read_bio; /* OpenSSL will read its incoming SSL packets from here */
105 BIO *write_bio; /* OpenSSL will write its outgoing SSL packets to here */
106 netsnmp_sockaddr_storage sas;
107 u_int flags;
108 struct bio_cache_s *next;
109 int msgnum;
110 char *write_cache;
111 size_t write_cache_len;
112 _netsnmpTLSBaseData *tlsdata;
113 } bio_cache;
114
115 /** bio_cache flags */
116 #define NETSNMP_BIO_HAVE_COOKIE 0x0001 /* verified cookie */
117 #define NETSNMP_BIO_CONNECTED 0x0002 /* received decoded data */
118 #define NETSNMP_BIO_DISCONNECTED 0x0004 /* peer shutdown */
119
120 static bio_cache *biocache = NULL;
121
122 static int openssl_addr_index = 0;
123
124 #ifdef HAVE_SSL_CTX_SET_COOKIE_GENERATE_CB
125 static int netsnmp_dtls_verify_cookie(SSL *ssl,
126 SECOND_APPVERIFY_COOKIE_CB_ARG_QUALIFIER
127 unsigned char *cookie,
128 unsigned int cookie_len);
129 static int netsnmp_dtls_gen_cookie(SSL *ssl, unsigned char *cookie,
130 unsigned int *cookie_len);
131 #endif
132
133 /* this stores remote connections in a list to search through */
134 /* XXX: optimize for searching */
135 /* XXX: handle state issues for new connections to reduce DOS issues */
136 /* (TLS should do this, but openssl can't do more than one ctx per sock */
137 /* XXX: put a timer on the cache for expirary purposes */
138 static bio_cache *find_bio_cache(const netsnmp_sockaddr_storage *from_addr)
139 {
140 bio_cache *cachep = NULL;
141
142 for (cachep = biocache; cachep; cachep = cachep->next) {
143
144 if (cachep->sas.sa.sa_family != from_addr->sa.sa_family)
145 continue;
146
147 if ((from_addr->sa.sa_family == AF_INET) &&
148 ((cachep->sas.sin.sin_addr.s_addr !=
149 from_addr->sin.sin_addr.s_addr) ||
150 (cachep->sas.sin.sin_port != from_addr->sin.sin_port)))
151 continue;
152 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
153 else if ((from_addr->sa.sa_family == AF_INET6) &&
154 ((cachep->sas.sin6.sin6_port != from_addr->sin6.sin6_port) ||
155 (cachep->sas.sin6.sin6_scope_id !=
156 from_addr->sin6.sin6_scope_id) ||
157 (memcmp(cachep->sas.sin6.sin6_addr.s6_addr,
158 from_addr->sin6.sin6_addr.s6_addr,
159 sizeof(from_addr->sin6.sin6_addr.s6_addr)) != 0)))
160 continue;
161 #endif
162 /* found an existing connection */
163 break;
164 }
165 return cachep;
166 }
167
168 /* removes a single cache entry and returns SUCCESS on finding and
169 removing it. */
170 static int remove_bio_cache(bio_cache *thiscache)
171 {
172 bio_cache *cachep = NULL, *prevcache = NULL;
173
174 cachep = biocache;
175 while (cachep) {
176 if (cachep == thiscache) {
177
178 /* remove it from the list */
179 if (NULL == prevcache) {
180 /* at the first cache in the list */
181 biocache = thiscache->next;
182 } else {
183 prevcache->next = thiscache->next;
184 }
185
186 return SNMPERR_SUCCESS;
187 }
188 prevcache = cachep;
189 cachep = cachep->next;
190 }
191 return SNMPERR_GENERR;
192 }
193
194 /* frees the contents of a bio_cache */
195 static void free_bio_cache(bio_cache *cachep)
196 {
197 /* These are freed by the SSL_free() call */
198 /*
199 BIO_free(cachep->read_bio);
200 BIO_free(cachep->write_bio);
201 */
202 DEBUGMSGTL(("9:dtlsudp:bio_cache", "releasing %p\n", cachep));
203 SNMP_FREE(cachep->write_cache);
204 netsnmp_tlsbase_free_tlsdata(cachep->tlsdata);
205 }
206
207 static void remove_and_free_bio_cache(bio_cache *cachep)
208 {
209 /** no debug, remove_bio_cache does it */
210 remove_bio_cache(cachep);
211 free_bio_cache(cachep);
212 }
213
214
215 /* XXX: lots of malloc/state cleanup needed */
216 #define DIEHERE(msg) do { snmp_log(LOG_ERR, "%s\n", msg); return NULL; } while(0)
217
218 static bio_cache *
219 start_new_cached_connection(netsnmp_transport *t,
220 const netsnmp_sockaddr_storage *remote_addr,
221 int we_are_client)
222 {
223 bio_cache *cachep = NULL;
224 _netsnmpTLSBaseData *tlsdata;
225
226 DEBUGTRACETOK("9:dtlsudp");
227
228 /* RFC5953: section 5.3.1, step 1:
229 1) The snmpTlstmSessionOpens counter is incremented.
230 */
231 if (we_are_client)
232 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENS);
233
234 if (!t->sock)
235 DIEHERE("no socket passed in to start_new_cached_connection\n");
236 if (!remote_addr)
237 DIEHERE("no remote_addr passed in to start_new_cached_connection\n");
238
239 cachep = SNMP_MALLOC_TYPEDEF(bio_cache);
240 if (!cachep)
241 return NULL;
242
243 /* allocate our TLS specific data */
244 if (NULL == (tlsdata = netsnmp_tlsbase_allocate_tlsdata(t, !we_are_client))) {
245 SNMP_FREE(cachep);
246 return NULL;
247 }
248 cachep->tlsdata = tlsdata;
249
250 /* RFC5953: section 5.3.1, step 1:
251 2) The client selects the appropriate certificate and cipher_suites
252 for the key agreement based on the tmSecurityName and the
253 tmRequestedSecurityLevel for the session. For sessions being
254 established as a result of a SNMP-TARGET-MIB based operation, the
255 certificate will potentially have been identified via the
256 snmpTlstmParamsTable mapping and the cipher_suites will have to
257 be taken from system-wide or implementation-specific
258 configuration. If no row in the snmpTlstmParamsTable exists then
259 implementations MAY choose to establish the connection using a
260 default client certificate available to the application.
261 Otherwise, the certificate and appropriate cipher_suites will
262 need to be passed to the openSession() ASI as supplemental
263 information or configured through an implementation-dependent
264 mechanism. It is also implementation-dependent and possibly
265 policy-dependent how tmRequestedSecurityLevel will be used to
266 influence the security capabilities provided by the (D)TLS
267 connection. However this is done, the security capabilities
268 provided by (D)TLS MUST be at least as high as the level of
269 security indicated by the tmRequestedSecurityLevel parameter.
270 The actual security level of the session is reported in the
271 tmStateReference cache as tmSecurityLevel. For (D)TLS to provide
272 strong authentication, each principal acting as a command
273 generator SHOULD have its own certificate.
274 */
275 /* Implementation notes:
276 + This Information is passed in via the transport and default
277 paremeters
278 */
279 /* see if we have base configuration to copy in to this new one */
280 if (NULL != t->data && t->data_length == sizeof(_netsnmpTLSBaseData)) {
281 _netsnmpTLSBaseData *parentdata = t->data;
282 if (parentdata->our_identity)
283 tlsdata->our_identity = strdup(parentdata->our_identity);
284 if (parentdata->their_identity)
285 tlsdata->their_identity = strdup(parentdata->their_identity);
286 if (parentdata->their_fingerprint)
287 tlsdata->their_fingerprint = strdup(parentdata->their_fingerprint);
288 if (parentdata->trust_cert)
289 tlsdata->trust_cert = strdup(parentdata->trust_cert);
290 if (parentdata->their_hostname)
291 tlsdata->their_hostname = strdup(parentdata->their_hostname);
292 }
293
294 DEBUGMSGTL(("dtlsudp", "starting a new connection\n"));
295 cachep->next = biocache;
296 biocache = cachep;
297
298 if (remote_addr->sa.sa_family == AF_INET)
299 memcpy(&cachep->sas.sin, &remote_addr->sin, sizeof(remote_addr->sin));
300 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
301 else if (remote_addr->sa.sa_family == AF_INET6)
302 memcpy(&cachep->sas.sin6, &remote_addr->sin6, sizeof(remote_addr->sin6));
303 #endif
304 else
305 DIEHERE("unknown address family");
306
307 /* create caching memory bios for OpenSSL to read and write to */
308
309 cachep->read_bio = BIO_new(BIO_s_mem()); /* openssl reads from */
310 if (!cachep->read_bio)
311 DIEHERE("failed to create the openssl read_bio");
312
313 cachep->write_bio = BIO_new(BIO_s_mem()); /* openssl writes to */
314 if (!cachep->write_bio) {
315 BIO_free(cachep->read_bio);
316 cachep->read_bio = NULL;
317 DIEHERE("failed to create the openssl write_bio");
318 }
319
320 BIO_set_mem_eof_return(cachep->read_bio, -1);
321 BIO_set_mem_eof_return(cachep->write_bio, -1);
322
323 if (we_are_client) {
324 /* we're the client */
325 DEBUGMSGTL(("dtlsudp",
326 "starting a new connection as a client to sock: %d\n",
327 t->sock));
328 tlsdata->ssl = SSL_new(sslctx_client_setup(DTLS_method(), tlsdata));
329
330 /* XXX: session setting 735 */
331 } else {
332 /* we're the server */
333 SSL_CTX *ctx = sslctx_server_setup(DTLS_method());
334 if (!ctx) {
335 BIO_free(cachep->read_bio);
336 BIO_free(cachep->write_bio);
337 cachep->read_bio = NULL;
338 cachep->write_bio = NULL;
339 DIEHERE("failed to create the SSL Context");
340 }
341
342 #ifdef HAVE_SSL_CTX_SET_COOKIE_GENERATE_CB
343 /* turn on cookie exchange */
344 /* Set DTLS cookie generation and verification callbacks */
345 SSL_CTX_set_cookie_generate_cb(ctx, netsnmp_dtls_gen_cookie);
346 SSL_CTX_set_cookie_verify_cb(ctx, netsnmp_dtls_verify_cookie);
347 #endif
348
349 tlsdata->ssl = SSL_new(ctx);
350 }
351
352 if (!tlsdata->ssl) {
353 BIO_free(cachep->read_bio);
354 BIO_free(cachep->write_bio);
355 cachep->read_bio = NULL;
356 cachep->write_bio = NULL;
357 DIEHERE("failed to create the SSL session structure");
358 }
359
360 SSL_set_mode(tlsdata->ssl, SSL_MODE_AUTO_RETRY);
361
362 /* set the bios that openssl should read from and write to */
363 /* (and we'll do the opposite) */
364 SSL_set_bio(tlsdata->ssl, cachep->read_bio, cachep->write_bio);
365
366 /* RFC5953: section 5.3.1, step 1:
367 3) Using the destTransportDomain and destTransportAddress values,
368 the client will initiate the (D)TLS handshake protocol to
369 establish session keys for message integrity and encryption.
370
371 If the attempt to establish a session is unsuccessful, then
372 snmpTlstmSessionOpenErrors is incremented, an error indication is
373 returned, and processing stops. If the session failed to open
374 because the presented server certificate was unknown or invalid
375 then the snmpTlstmSessionUnknownServerCertificate or
376 snmpTlstmSessionInvalidServerCertificates MUST be incremented and
377 a snmpTlstmServerCertificateUnknown or
378 snmpTlstmServerInvalidCertificate notification SHOULD be sent as
379 appropriate. Reasons for server certificate invalidation
380 includes, but is not limited to, cryptographic validation
381 failures and an unexpected presented certificate identity.
382 */
383 /* Implementation notes:
384 + Because we're working asynchronously the real "end" point of
385 opening a connection doesn't occur here as certificate
386 verification and other things needs to happen first in the
387 verify callback, etc. See the netsnmp_dtlsudp_recv()
388 function for the final processing.
389 */
390 /* set the SSL notion of we_are_client/server */
391 if (we_are_client)
392 SSL_set_connect_state(tlsdata->ssl);
393 else {
394 /* XXX: we need to only create cache entries when cookies succeed */
395
396 SSL_set_options(tlsdata->ssl, SSL_OP_COOKIE_EXCHANGE);
397
398 SSL_set_ex_data(tlsdata->ssl, openssl_addr_index, cachep);
399
400 SSL_set_accept_state(tlsdata->ssl);
401 }
402
403 /* RFC5953: section 5.3.1, step 1:
404 6) The TLSTM-specific session identifier (tlstmSessionID) is set in
405 the tmSessionID of the tmStateReference passed to the TLS
406 Transport Model to indicate that the session has been established
407 successfully and to point to a specific (D)TLS connection for
408 future use. The tlstmSessionID is also stored in the LCD for
409 later lookup during processing of incoming messages
410 (Section 5.1.2).
411 */
412 /* Implementation notes:
413 + our sessionID is stored as the transport's data pointer member
414 */
415 DEBUGMSGT(("9:dtlsudp:bio_cache:created", "%p\n", cachep));
416
417 return cachep;
418 }
419
420 static bio_cache *
421 find_or_create_bio_cache(netsnmp_transport *t,
422 const netsnmp_sockaddr_storage *from_addr,
423 int we_are_client)
424 {
425 bio_cache *cachep = find_bio_cache(from_addr);
426
427 if (NULL == cachep) {
428 /* none found; need to start a new context */
429 cachep = start_new_cached_connection(t, from_addr, we_are_client);
430 if (NULL == cachep) {
431 snmp_log(LOG_ERR, "failed to open a new dtls connection\n");
432 }
433 } else {
434 DEBUGMSGT(("9:dtlsudp:bio_cache:found", "%p\n", cachep));
435 }
436 return cachep;
437 }
438
439 static const netsnmp_indexed_addr_pair *
440 _extract_addr_pair(netsnmp_transport *t, const void *opaque, int olen)
441 {
442 if (opaque) {
443 switch (olen) {
444 case sizeof(netsnmp_tmStateReference): {
445 const netsnmp_tmStateReference *tmStateRef = opaque;
446
447 if (tmStateRef->have_addresses)
448 return &tmStateRef->addresses;
449 break;
450 }
451 default:
452 netsnmp_assert(0);
453 }
454 }
455 if (t && t->data) {
456 switch (t->data_length) {
457 case sizeof(netsnmp_indexed_addr_pair):
458 return t->data;
459 case sizeof(_netsnmpTLSBaseData): {
460 _netsnmpTLSBaseData *tlsdata = t->data;
461
462 return tlsdata->addr;
463 }
464 default:
465 netsnmp_assert(0);
466 }
467 }
468
469 return NULL;
470 }
471
472 static const struct sockaddr *
473 _find_remote_sockaddr(netsnmp_transport *t, const void *opaque, int olen,
474 int *socklen)
475 {
476 const netsnmp_indexed_addr_pair *addr_pair;
477 const struct sockaddr *sa = NULL;
478
479 addr_pair = _extract_addr_pair(t, opaque, olen);
480 if (NULL == addr_pair)
481 return NULL;
482
483 sa = &addr_pair->remote_addr.sa;
484 *socklen = netsnmp_sockaddr_size(sa);
485 return sa;
486 }
487
488
489 /*
490 * Reads data from our internal openssl outgoing BIO and sends any
491 * queued packets out the UDP port
492 */
493 static int
494 _netsnmp_send_queued_dtls_pkts(netsnmp_transport *t, bio_cache *cachep)
495 {
496 int outsize, rc2;
497 void *outbuf;
498
499 DEBUGTRACETOK("9:dtlsudp");
500
501 /* for memory bios, we now read from openssl's write
502 buffer (ie, the packet to go out) and send it out
503 the udp port manually */
504
505 outsize = BIO_ctrl_pending(cachep->write_bio);
506 outbuf = malloc(outsize);
507 if (outsize > 0 && outbuf) {
508 int socksize;
509 void *sa;
510
511 DEBUGMSGTL(("dtlsudp", "have %d bytes to send\n", outsize));
512
513 outsize = BIO_read(cachep->write_bio, outbuf, outsize);
514 MAKE_MEM_DEFINED(outbuf, outsize);
515 sa = NETSNMP_REMOVE_CONST(struct sockaddr *,
516 _find_remote_sockaddr(t, NULL, 0, &socksize));
517 if (NULL == sa)
518 sa = &cachep->sas.sa;
519 socksize = netsnmp_sockaddr_size(sa);
520 rc2 = t->base_transport->f_send(t, outbuf, outsize, &sa, &socksize);
521 if (rc2 == -1) {
522 snmp_log(LOG_ERR, "failed to send a DTLS specific packet\n");
523 }
524 } else if (outsize == 0) {
525 DEBUGMSGTL(("9:dtlsudp", "have 0 bytes to send\n"));
526 } else {
527 DEBUGMSGTL(("9:dtlsudp", "buffer allocation failed\n"));
528 }
529
530 free(outbuf);
531
532 return outsize;
533 }
534
535 /*
536 * If we have any outgoing SNMP data queued that OpenSSL/DTLS couldn't send
537 * (likely due to DTLS control packets needing to go out first)
538 * then this function attempts to send them.
539 */
540 /* returns SNMPERR_SUCCESS if we succeeded in getting the data out */
541 /* returns SNMPERR_GENERR if we still need more time */
542 static int
543 _netsnmp_bio_try_and_write_buffered(netsnmp_transport *t, bio_cache *cachep)
544 {
545 int rc;
546 _netsnmpTLSBaseData *tlsdata;
547
548 DEBUGTRACETOK("9:dtlsudp");
549
550 tlsdata = cachep->tlsdata;
551
552 /* make sure we have something to write */
553 if (!cachep->write_cache || cachep->write_cache_len == 0)
554 return SNMPERR_SUCCESS;
555
556 DEBUGMSGTL(("dtlsudp", "Trying to write %" NETSNMP_PRIz "d of buffered data\n",
557 cachep->write_cache_len));
558
559 /* try and write out the cached data */
560 rc = SSL_write(tlsdata->ssl, cachep->write_cache, cachep->write_cache_len);
561
562 while (rc == -1) {
563 int errnum = SSL_get_error(tlsdata->ssl, rc);
564 int bytesout;
565
566 /* don't treat want_read/write errors as real errors */
567 if (errnum != SSL_ERROR_WANT_READ &&
568 errnum != SSL_ERROR_WANT_WRITE) {
569 DEBUGMSGTL(("dtlsudp", "ssl_write error (of buffered data)\n"));
570 _openssl_log_error(rc, tlsdata->ssl, "SSL_write");
571 return SNMPERR_GENERR;
572 }
573
574 /* check to see if we have outgoing DTLS packets to send */
575 /* (SSL_write could have created DTLS control packets) */
576 bytesout = _netsnmp_send_queued_dtls_pkts(t, cachep);
577
578 /* If want_read/write but failed to actually send anything
579 then we need to wait for the other side, so quit */
580 if (bytesout <= 0) {
581 /* sending failed; must wait longer */
582 return SNMPERR_GENERR;
583 }
584
585 /* retry writing */
586 DEBUGMSGTL(("9:dtlsudp", "recalling ssl_write\n"));
587 rc = SSL_write(tlsdata->ssl, cachep->write_cache,
588 cachep->write_cache_len);
589 }
590
591 if (rc > 0)
592 cachep->msgnum++;
593
594 if (_netsnmp_send_queued_dtls_pkts(t, cachep) > 0) {
595 SNMP_FREE(cachep->write_cache);
596 cachep->write_cache_len = 0;
597 DEBUGMSGTL(("dtlsudp", " Write was successful\n"));
598 return SNMPERR_SUCCESS;
599 }
600 DEBUGMSGTL(("dtlsudp", " failed to send over UDP socket\n"));
601 return SNMPERR_GENERR;
602 }
603
604 static int
605 _netsnmp_add_buffered_data(bio_cache *cachep, const char *buf, size_t size)
606 {
607 if (cachep->write_cache && cachep->write_cache_len > 0) {
608 size_t newsize = cachep->write_cache_len + size;
609
610 char *newbuf = realloc(cachep->write_cache, newsize);
611 if (NULL == newbuf) {
612 /* ack! malloc failure */
613 /* XXX: free and close */
614 return SNMPERR_GENERR;
615 }
616 cachep->write_cache = newbuf;
617
618 /* write the new packet to the end */
619 memcpy(cachep->write_cache + cachep->write_cache_len,
620 buf, size);
621 cachep->write_cache_len = newsize;
622 } else {
623 cachep->write_cache = netsnmp_memdup(buf, size);
624 if (!cachep->write_cache) {
625 /* ack! malloc failure */
626 /* XXX: free and close */
627 return SNMPERR_GENERR;
628 }
629 cachep->write_cache_len = size;
630 }
631 return SNMPERR_SUCCESS;
632 }
633
634 static int
635 netsnmp_dtlsudp_recv(netsnmp_transport *t, void *buf, int size,
636 void **opaque, int *olength)
637 {
638 int rc = -1;
639 netsnmp_indexed_addr_pair *addr_pair = NULL;
640 netsnmp_tmStateReference *tmStateRef = NULL;
641 _netsnmpTLSBaseData *tlsdata;
642 bio_cache *cachep;
643
644 DEBUGTRACETOK("9:dtlsudp");
645
646 if (NULL == t || t->sock == 0)
647 return -1;
648
649 /* create a tmStateRef cache for slow fill-in */
650 tmStateRef = SNMP_MALLOC_TYPEDEF(netsnmp_tmStateReference);
651
652 if (tmStateRef == NULL) {
653 *opaque = NULL;
654 *olength = 0;
655 return -1;
656 }
657
658 /* Set the transportDomain */
659 memcpy(tmStateRef->transportDomain,
660 netsnmpDTLSUDPDomain, sizeof(netsnmpDTLSUDPDomain[0]) *
661 netsnmpDTLSUDPDomain_len);
662 tmStateRef->transportDomainLen = netsnmpDTLSUDPDomain_len;
663
664 addr_pair = &tmStateRef->addresses;
665 tmStateRef->have_addresses = 1;
666
667 while (rc < 0) {
668 void *opaque = NULL;
669 int olen;
670 rc = t->base_transport->f_recv(t, buf, size, &opaque, &olen);
671 if (rc > 0) {
672 if (olen > sizeof(*addr_pair))
673 snmp_log(LOG_ERR, "%s: from address length %d > %d\n",
674 NETSNMP_FUNCTION, olen, (int)sizeof(*addr_pair));
675 memcpy(addr_pair, opaque, SNMP_MIN(sizeof(*addr_pair), olen));
676 }
677 SNMP_FREE(opaque);
678 if (rc < 0 && errno != EINTR) {
679 break;
680 }
681 }
682
683 DEBUGMSGTL(("dtlsudp", "received %d raw bytes on way to dtls\n", rc));
684 if (rc < 0) {
685 DEBUGMSGTL(("dtlsudp", "recvfrom fd %d err %d (\"%s\")\n",
686 t->sock, errno, strerror(errno)));
687 SNMP_FREE(tmStateRef);
688 return -1;
689 }
690
691 /* now that we have the from address filled in, we can look up
692 the openssl context and have openssl read and process
693 appropriately */
694
695 /* RFC5953: section 5.1, step 1:
696 1) Determine the tlstmSessionID for the incoming message. The
697 tlstmSessionID MUST be a unique session identifier for this
698 (D)TLS connection. The contents and format of this identifier
699 are implementation-dependent as long as it is unique to the
700 session. A session identifier MUST NOT be reused until all
701 references to it are no longer in use. The tmSessionID is equal
702 to the tlstmSessionID discussed in Section 5.1.1. tmSessionID
703 refers to the session identifier when stored in the
704 tmStateReference and tlstmSessionID refers to the session
705 identifier when stored in the LCD. They MUST always be equal
706 when processing a given session's traffic.
707
708 If this is the first message received through this session and
709 the session does not have an assigned tlstmSessionID yet then the
710 snmpTlstmSessionAccepts counter is incremented and a
711 tlstmSessionID for the session is created. This will only happen
712 on the server side of a connection because a client would have
713 already assigned a tlstmSessionID during the openSession()
714 invocation. Implementations may have performed the procedures
715 described in Section 5.3.2 prior to this point or they may
716 perform them now, but the procedures described in Section 5.3.2
717 MUST be performed before continuing beyond this point.
718 */
719
720 /* RFC5953: section 5.1, step 2:
721 2) Create a tmStateReference cache for the subsequent reference and
722 assign the following values within it:
723
724 tmTransportDomain = snmpTLSTCPDomain or snmpDTLSUDPDomain as
725 appropriate.
726
727 tmTransportAddress = The address the message originated from.
728
729 tmSecurityLevel = The derived tmSecurityLevel for the session,
730 as discussed in Section 3.1.2 and Section 5.3.
731
732 tmSecurityName = The derived tmSecurityName for the session as
733 discussed in Section 5.3. This value MUST be constant during
734 the lifetime of the session.
735
736 tmSessionID = The tlstmSessionID described in step 1 above.
737 */
738
739 /* if we don't have a cachep for this connection then
740 we're receiving something new and are the server
741 side */
742 cachep =
743 find_or_create_bio_cache(t, &addr_pair->remote_addr, WE_ARE_SERVER);
744 if (NULL == cachep) {
745 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONACCEPTS);
746 SNMP_FREE(tmStateRef);
747 return -1;
748 }
749 tlsdata = cachep->tlsdata;
750 if (NULL == tlsdata->ssl) {
751 /*
752 * this happens when the server starts but doesn't have an
753 * identity and a client connects...
754 */
755 snmp_log(LOG_ERR,
756 "DTLSUDP: missing tlsdata!\n");
757 /*snmp_increment_statistic( XXX-rks ??? );*/
758 SNMP_FREE(tmStateRef);
759 return -1;
760 }
761
762 /* Implementation notes:
763 - we use the t->data memory pointer as the session ID
764 - the transport domain is already the correct type if we got here
765 - if we don't have a session yet (eg, no tmSessionID from the
766 specs) then we create one automatically here.
767 */
768
769 /* write the received buffer to the memory-based input bio */
770 BIO_write(cachep->read_bio, buf, rc);
771
772 /* RFC5953: section 5.1, step 3:
773 3) The incomingMessage and incomingMessageLength are assigned values
774 from the (D)TLS processing.
775 */
776 /* Implementation notes:
777 + rc = incomingMessageLength
778 + buf = IncomingMessage
779 */
780
781 /* XXX: in Wes' other example we do a SSL_pending() call
782 too to ensure we're ready to read... it's possible
783 that buffered stuff in openssl won't be caught by the
784 net-snmp select loop because it's already been pulled
785 out; need to deal with this) */
786 rc = SSL_read(tlsdata->ssl, buf, size);
787 MAKE_MEM_DEFINED(&rc, sizeof(rc));
788 if (rc > 0)
789 MAKE_MEM_DEFINED(buf, rc);
790
791 /*
792 * moved netsnmp_openssl_null_checks to netsnmp_tlsbase_wrapup_recv.
793 * currently netsnmp_tlsbase_wrapup_recv is where we check for
794 * algorithm compliance, but we (sometimes) know the algorithms
795 * at this point, so we could bail earlier (here)...
796 */
797
798 while (rc == -1) {
799 int errnum = SSL_get_error(tlsdata->ssl, rc);
800 int bytesout;
801
802 /* don't treat want_read/write errors as real errors */
803 if (errnum != SSL_ERROR_WANT_READ &&
804 errnum != SSL_ERROR_WANT_WRITE) {
805 _openssl_log_error(rc, tlsdata->ssl, "SSL_read");
806 break;
807 }
808
809 /* check to see if we have outgoing DTLS packets to send */
810 /* (SSL_read could have created DTLS control packets) */
811 bytesout = _netsnmp_send_queued_dtls_pkts(t, cachep);
812
813 /* If want_read/write but failed to actually send
814 anything then we need to wait for the other side,
815 so quit */
816 if (bytesout <= 0)
817 break;
818
819 /* retry reading */
820 DEBUGMSGTL(("9:dtlsudp", "recalling ssl_read\n"));
821 rc = SSL_read(tlsdata->ssl, buf, size);
822 MAKE_MEM_DEFINED(&rc, sizeof(rc));
823 if (rc > 0)
824 MAKE_MEM_DEFINED(buf, rc);
825 }
826
827 if (rc == -1) {
828 SNMP_FREE(tmStateRef);
829
830 DEBUGMSGTL(("9:dtlsudp", "no decoded data from dtls\n"));
831
832 if (SSL_get_error(tlsdata->ssl, rc) == SSL_ERROR_WANT_READ) {
833 DEBUGMSGTL(("9:dtlsudp", "ssl error want read\n"));
834
835 /* see if we have buffered write date to send out first */
836 if (cachep->write_cache) {
837 _netsnmp_bio_try_and_write_buffered(t, cachep);
838 /* XXX: check error or not here? */
839 /* (what would we do differently?) */
840 }
841
842 rc = -1; /* XXX: it's ok, but what's the right return? */
843 }
844 else
845 _openssl_log_error(rc, tlsdata->ssl, "SSL_read");
846
847 #if 0 /* to dump cache if we don't have a cookie, this is where to do it */
848 if (!(cachep->flags & NETSNMP_BIO_HAVE_COOKIE))
849 remove_and_free_bio_cache(cachep);
850 #endif
851 return rc;
852 }
853
854 DEBUGMSGTL(("dtlsudp", "received %d decoded bytes from dtls\n", rc));
855
856 if ((0 == rc) && (SSL_get_shutdown(tlsdata->ssl) & SSL_RECEIVED_SHUTDOWN)) {
857 DEBUGMSGTL(("dtlsudp", "peer disconnected\n"));
858 cachep->flags |= NETSNMP_BIO_DISCONNECTED;
859 remove_and_free_bio_cache(cachep);
860 SNMP_FREE(tmStateRef);
861 return rc;
862 }
863 cachep->flags |= NETSNMP_BIO_CONNECTED;
864
865 /* Until we've locally assured ourselves that all is well in
866 certificate-verification-land we need to be prepared to stop
867 here and ensure all our required checks have been done. */
868 if (0 == (tlsdata->flags & NETSNMP_TLSBASE_CERT_FP_VERIFIED)) {
869 int verifyresult;
870
871 if (tlsdata->flags & NETSNMP_TLSBASE_IS_CLIENT) {
872
873 /* verify that the server's certificate is the correct one */
874
875 /* RFC5953: section 5.3.1, step 1:
876 3) Using the destTransportDomain and
877 destTransportAddress values, the client will
878 initiate the (D)TLS handshake protocol to establish
879 session keys for message integrity and encryption.
880
881 If the attempt to establish a session is
882 unsuccessful, then snmpTlstmSessionOpenErrors is
883 incremented, an error indication is returned, and
884 processing stops. If the session failed to open
885 because the presented server certificate was
886 unknown or invalid then the
887 snmpTlstmSessionUnknownServerCertificate or
888 snmpTlstmSessionInvalidServerCertificates MUST be
889 incremented and a snmpTlstmServerCertificateUnknown
890 or snmpTlstmServerInvalidCertificate notification
891 SHOULD be sent as appropriate. Reasons for server
892 certificate invalidation includes, but is not
893 limited to, cryptographic validation failures and
894 an unexpected presented certificate identity.
895 */
896 /* RFC5953: section 5.3.1, step 1:
897 4) The (D)TLS client MUST then verify that the (D)TLS
898 server's presented certificate is the expected
899 certificate. The (D)TLS client MUST NOT transmit
900 SNMP messages until the server certificate has been
901 authenticated, the client certificate has been
902 transmitted and the TLS connection has been fully
903 established.
904
905 If the connection is being established from
906 configuration based on SNMP-TARGET-MIB
907 configuration, then the snmpTlstmAddrTable
908 DESCRIPTION clause describes how the verification
909 is done (using either a certificate fingerprint, or
910 an identity authenticated via certification path
911 validation).
912
913 If the connection is being established for reasons
914 other than configuration found in the
915 SNMP-TARGET-MIB then configuration and procedures
916 outside the scope of this document should be
917 followed. Configuration mechanisms SHOULD be
918 similar in nature to those defined in the
919 snmpTlstmAddrTable to ensure consistency across
920 management configuration systems. For example, a
921 command-line tool for generating SNMP GETs might
922 support specifying either the server's certificate
923 fingerprint or the expected host name as a command
924 line argument.
925 */
926 /* RFC5953: section 5.3.1, step 1:
927 5) (D)TLS provides assurance that the authenticated
928 identity has been signed by a trusted configured
929 certification authority. If verification of the
930 server's certificate fails in any way (for example
931 because of failures in cryptographic verification
932 or the presented identity did not match the
933 expected named entity) then the session
934 establishment MUST fail, the
935 snmpTlstmSessionInvalidServerCertificates object is
936 incremented. If the session can not be opened for
937 any reason at all, including cryptographic
938 verification failures and snmpTlstmCertToTSNTable
939 lookup failures, then the
940 snmpTlstmSessionOpenErrors counter is incremented
941 and processing stops.
942 */
943
944 /* Implementation notes:
945 + in the following function the server's certificate and
946 presented commonname or subjectAltName is checked
947 according to the rules in the snmpTlstmAddrTable.
948 */
949 if ((verifyresult = netsnmp_tlsbase_verify_server_cert(tlsdata->ssl, tlsdata))
950 != SNMPERR_SUCCESS) {
951 if (verifyresult == SNMPERR_TLS_NO_CERTIFICATE) {
952 /* assume we simply haven't received it yet and there
953 is more data to wait-for or send */
954 /* XXX: probably need to check for whether we should
955 send stuff from our end to continue the transaction
956 */
957 SNMP_FREE(tmStateRef);
958 return -1;
959 } else {
960 /* XXX: free needed memory */
961 snmp_log(LOG_ERR,
962 "DTLSUDP: failed to verify ssl certificate (of the server)\n");
963 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONUNKNOWNSERVERCERTIFICATE);
964 /* Step 5 says these are always incremented */
965 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONINVALIDSERVERCERTIFICATES);
966 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
967 SNMP_FREE(tmStateRef);
968 return -1;
969 }
970 }
971 tlsdata->flags |= NETSNMP_TLSBASE_CERT_FP_VERIFIED;
972 DEBUGMSGTL(("dtlsudp", "Verified the server's certificate\n"));
973 } else {
974 #ifndef NETSNMP_NO_LISTEN_SUPPORT
975 /* verify that the client's certificate is the correct one */
976
977 if ((verifyresult = netsnmp_tlsbase_verify_client_cert(tlsdata->ssl, tlsdata))
978 != SNMPERR_SUCCESS) {
979 if (verifyresult == SNMPERR_TLS_NO_CERTIFICATE) {
980 /* assume we simply haven't received it yet and there
981 is more data to wait-for or send */
982 /* XXX: probably need to check for whether we should
983 send stuff from our end to continue the transaction
984 */
985 SNMP_FREE(tmStateRef);
986 return -1;
987 } else {
988 /* XXX: free needed memory */
989 snmp_log(LOG_ERR,
990 "DTLSUDP: failed to verify ssl certificate (of the client)\n");
991 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONINVALIDCLIENTCERTIFICATES);
992 SNMP_FREE(tmStateRef);
993 return -1;
994 }
995 }
996 tlsdata->flags |= NETSNMP_TLSBASE_CERT_FP_VERIFIED;
997 DEBUGMSGTL(("dtlsudp", "Verified the client's certificate\n"));
998 #else /* NETSNMP_NO_LISTEN_SUPPORT */
999 return NULL;
1000 #endif /* NETSNMP_NO_LISTEN_SUPPORT */
1001 }
1002 }
1003
1004 if (rc > 0)
1005 cachep->msgnum++;
1006
1007 if (BIO_ctrl_pending(cachep->write_bio) > 0) {
1008 _netsnmp_send_queued_dtls_pkts(t, cachep);
1009 }
1010
1011 DEBUGIF ("9:dtlsudp") {
1012 char *str =
1013 t->base_transport->f_fmtaddr(t, addr_pair,
1014 sizeof(netsnmp_indexed_addr_pair));
1015 DEBUGMSGTL(("9:dtlsudp",
1016 "recvfrom fd %d got %d bytes (from %s)\n",
1017 t->sock, rc, str));
1018 free(str);
1019 }
1020
1021 /* see if we have buffered write date to send out first */
1022 if (cachep->write_cache) {
1023 if (SNMPERR_GENERR ==
1024 _netsnmp_bio_try_and_write_buffered(t, cachep)) {
1025 /* we still have data that can't get out in the buffer */
1026 /* XXX: nothing to do here? */
1027 }
1028 }
1029
1030 if (netsnmp_tlsbase_wrapup_recv(tmStateRef, tlsdata, opaque, olength) !=
1031 SNMPERR_SUCCESS)
1032 return SNMPERR_GENERR;
1033
1034 /* RFC5953: section 5.1, step 4:
1035 4) The TLS Transport Model passes the transportDomain,
1036 transportAddress, incomingMessage, and incomingMessageLength to
1037 the Dispatcher using the receiveMessage ASI:
1038
1039 statusInformation =
1040 receiveMessage(
1041 IN transportDomain -- snmpTLSTCPDomain or snmpDTLSUDPDomain,
1042 IN transportAddress -- address for the received message
1043 IN incomingMessage -- the whole SNMP message from (D)TLS
1044 IN incomingMessageLength -- the length of the SNMP message
1045 IN tmStateReference -- transport info
1046 )
1047 */
1048 /* Implementation notes: those parameters are all passed outward
1049 using the functions arguments and the return code below (the length) */
1050
1051 return rc;
1052 }
1053
1054
1055
1056 static int
1057 netsnmp_dtlsudp_send(netsnmp_transport *t, const void *buf, int size,
1058 void **opaque, int *olength)
1059 {
1060 int rc = -1;
1061 const netsnmp_indexed_addr_pair *addr_pair = NULL;
1062 bio_cache *cachep = NULL;
1063 const netsnmp_tmStateReference *tmStateRef = NULL;
1064 void *outbuf;
1065 _netsnmpTLSBaseData *tlsdata = NULL;
1066 int socksize;
1067 void *sa;
1068
1069 DEBUGTRACETOK("9:dtlsudp");
1070 DEBUGMSGTL(("dtlsudp", "sending %d bytes\n", size));
1071
1072 if (NULL == t || t->sock <= 0) {
1073 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONINVALIDCACHES);
1074 snmp_log(LOG_ERR, "invalid netsnmp_dtlsudp_send usage\n");
1075 return -1;
1076 }
1077
1078 /* determine remote addresses */
1079 addr_pair = _extract_addr_pair(t, opaque ? *opaque : NULL,
1080 olength ? *olength : 0);
1081 if (NULL == addr_pair) {
1082 /* RFC5953: section 5.2, step 1:
1083 1) If tmStateReference does not refer to a cache containing values
1084 for tmTransportDomain, tmTransportAddress, tmSecurityName,
1085 tmRequestedSecurityLevel, and tmSameSecurity, then increment the
1086 snmpTlstmSessionInvalidCaches counter, discard the message, and
1087 return the error indication in the statusInformation. Processing
1088 of this message stops.
1089 */
1090 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONINVALIDCACHES);
1091 snmp_log(LOG_ERR, "dtlsudp_send: can't get address to send to\n");
1092 return -1;
1093 }
1094
1095 /* RFC5953: section 5.2, step 2:
1096 2) Extract the tmSessionID, tmTransportDomain, tmTransportAddress,
1097 tmSecurityName, tmRequestedSecurityLevel, and tmSameSecurity
1098 values from the tmStateReference. Note: The tmSessionID value
1099 may be undefined if no session exists yet over which the message
1100 can be sent.
1101 */
1102 /* Implementation notes:
1103 - we use the t->data memory pointer as the session ID
1104 - the transport domain is already the correct type if we got here
1105 - if we don't have a session yet (eg, no tmSessionID from the
1106 specs) then we create one automatically here.
1107 */
1108 if (opaque != NULL && *opaque != NULL &&
1109 olength != NULL && *olength == sizeof(netsnmp_tmStateReference))
1110 tmStateRef = *opaque;
1111
1112
1113 /* RFC5953: section 5.2, step 3:
1114 3) If tmSameSecurity is true and either tmSessionID is undefined or
1115 refers to a session that is no longer open then increment the
1116 snmpTlstmSessionNoSessions counter, discard the message and
1117 return the error indication in the statusInformation. Processing
1118 of this message stops.
1119 */
1120 /* RFC5953: section 5.2, step 4:
1121 4) If tmSameSecurity is false and tmSessionID refers to a session
1122 that is no longer available then an implementation SHOULD open a
1123 new session using the openSession() ASI (described in greater
1124 detail in step 5b). Instead of opening a new session an
1125 implementation MAY return a snmpTlstmSessionNoSessions error to
1126 the calling module and stop processing of the message.
1127 */
1128 /* Implementation Notes:
1129 - We would never get here if the sessionID was different. We
1130 tie packets directly to the transport object and it could
1131 never be sent back over a different transport, which is what
1132 the above text is trying to prevent.
1133 - Auto-connections are handled higher in the Net-SNMP library stack
1134 */
1135
1136 /* RFC5953: section 5.2, step 5:
1137 5) If tmSessionID is undefined, then use tmTransportDomain,
1138 tmTransportAddress, tmSecurityName and tmRequestedSecurityLevel
1139 to see if there is a corresponding entry in the LCD suitable to
1140 send the message over.
1141
1142 5a) If there is a corresponding LCD entry, then this session
1143 will be used to send the message.
1144
1145 5b) If there is no corresponding LCD entry, then open a session
1146 using the openSession() ASI (discussed further in
1147 Section 5.3.1). Implementations MAY wish to offer message
1148 buffering to prevent redundant openSession() calls for the
1149 same cache entry. If an error is returned from
1150 openSession(), then discard the message, discard the
1151 tmStateReference, increment the snmpTlstmSessionOpenErrors,
1152 return an error indication to the calling module and stop
1153 processing of the message.
1154 */
1155
1156 /* we're always a client if we're sending to something unknown yet */
1157 if (NULL ==
1158 (cachep = find_or_create_bio_cache(t, &addr_pair->remote_addr,
1159 WE_ARE_CLIENT))) {
1160 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
1161 return -1;
1162 }
1163
1164 tlsdata = cachep->tlsdata;
1165 if (NULL == tlsdata || NULL == tlsdata->ssl) {
1166 /** xxx mem leak? free created bio cache? */
1167 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONNOSESSIONS);
1168 snmp_log(LOG_ERR, "bad tls data or ssl ptr in netsnmp_dtlsudp_send\n");
1169 return -1;
1170 }
1171
1172 if (!tlsdata->securityName && tmStateRef &&
1173 tmStateRef->securityNameLen > 0) {
1174 tlsdata->securityName = strdup(tmStateRef->securityName);
1175 }
1176
1177 /* see if we have previous outgoing data to send */
1178 if (cachep->write_cache) {
1179 if (SNMPERR_GENERR == _netsnmp_bio_try_and_write_buffered(t, cachep)) {
1180 /* we still have data that can't get out in the buffer */
1181
1182 DEBUGIF ("9:dtlsudp") {
1183 char *str = t->base_transport->f_fmtaddr(t, addr_pair,
1184 sizeof(netsnmp_indexed_addr_pair));
1185 DEBUGMSGTL(("9:dtlsudp", "cached %d bytes for %s on fd %d\n",
1186 size, str, t->sock));
1187 free(str);
1188 }
1189
1190 /* add the new data to the end of the existing cache */
1191 if (_netsnmp_add_buffered_data(cachep, buf, size) !=
1192 SNMPERR_SUCCESS) {
1193 /* XXX: free and close */
1194 }
1195 return -1;
1196 }
1197 }
1198
1199 DEBUGIF ("9:dtlsudp") {
1200 char *str = t->base_transport->f_fmtaddr(t, addr_pair,
1201 sizeof(netsnmp_indexed_addr_pair));
1202 DEBUGMSGTL(("9:dtlsudp", "send %d bytes from %p to %s on fd %d\n",
1203 size, buf, str, t->sock));
1204 free(str);
1205 }
1206
1207 /* RFC5953: section 5.2, step 6:
1208 6) Using either the session indicated by the tmSessionID if there
1209 was one or the session resulting from a previous step (4 or 5),
1210 pass the outgoingMessage to (D)TLS for encapsulation and
1211 transmission.
1212 */
1213 rc = SSL_write(tlsdata->ssl, buf, size);
1214
1215 while (rc == -1) {
1216 int bytesout;
1217 int errnum = SSL_get_error(tlsdata->ssl, rc);
1218
1219 /* don't treat want_read/write errors as real errors */
1220 if (errnum != SSL_ERROR_WANT_READ &&
1221 errnum != SSL_ERROR_WANT_WRITE) {
1222 DEBUGMSGTL(("dtlsudp", "ssl_write error\n"));
1223 _openssl_log_error(rc, tlsdata->ssl, "SSL_write");
1224 break;
1225 }
1226
1227 /* check to see if we have outgoing DTLS packets to send */
1228 /* (SSL_read could have created DTLS control packets) */
1229 bytesout = _netsnmp_send_queued_dtls_pkts(t, cachep);
1230
1231 /* If want_read/write but failed to actually send
1232 anything then we need to wait for the other side,
1233 so quit */
1234 if (bytesout <= 0) {
1235 /* We need more data written to or read from the socket
1236 but we're failing to do so and need to wait till the
1237 socket is ready again; unfortunately this means we need
1238 to buffer the SNMP data temporarily in the mean time */
1239
1240 DEBUGMSGTL(("9:dtlsudp", "cached %d bytes for fd %d\n", size,
1241 t->sock));
1242
1243 /* remember the packet */
1244 if (_netsnmp_add_buffered_data(cachep, buf, size) !=
1245 SNMPERR_SUCCESS) {
1246
1247 /* XXX: free and close */
1248 return -1;
1249 }
1250
1251 /* exit out of the loop until we get called again from
1252 socket data */
1253 break;
1254 }
1255 DEBUGMSGTL(("9:dtlsudp", "recalling ssl_write\n"));
1256 rc = SSL_write(tlsdata->ssl, buf, size);
1257 }
1258
1259 if (rc > 0)
1260 cachep->msgnum++;
1261
1262 /* for memory bios, we now read from openssl's write buffer (ie,
1263 the packet to go out) and send it out the udp port manually */
1264 rc = BIO_ctrl_pending(cachep->write_bio);
1265 if (rc <= 0) {
1266 /* in theory an ok thing */
1267 return 0;
1268 }
1269 outbuf = malloc(rc);
1270 if (!outbuf)
1271 return -1;
1272 rc = BIO_read(cachep->write_bio, outbuf, rc);
1273 MAKE_MEM_DEFINED(outbuf, rc);
1274 socksize = netsnmp_sockaddr_size(&cachep->sas.sa);
1275 sa = &cachep->sas.sa;
1276 rc = t->base_transport->f_send(t, outbuf, rc, &sa, &socksize);
1277 free(outbuf);
1278
1279 return rc;
1280 }
1281
1282
1283
1284 static int
1285 netsnmp_dtlsudp_close(netsnmp_transport *t)
1286 {
1287 /* XXX: issue a proper dtls closure notification(s) */
1288
1289 bio_cache *cachep = NULL;
1290 _netsnmpTLSBaseData *tlsbase = NULL;
1291
1292 DEBUGTRACETOK("9:dtlsudp");
1293
1294 DEBUGMSGTL(("dtlsudp:close", "closing dtlsudp transport %p\n", t));
1295
1296 /* RFC5953: section 5.4, step 1:
1297 1) Increment either the snmpTlstmSessionClientCloses or the
1298 snmpTlstmSessionServerCloses counter as appropriate.
1299 */
1300 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONCLIENTCLOSES);
1301
1302 /* RFC5953: section 5.4, step 2:
1303 2) Look up the session using the tmSessionID.
1304 */
1305 /* Implementation notes:
1306 + Our session id is stored as the t->data pointer
1307 */
1308 if (NULL != t->data && t->data_length == sizeof(_netsnmpTLSBaseData)) {
1309 tlsbase = t->data;
1310
1311 if (tlsbase->addr)
1312 cachep = find_bio_cache(&tlsbase->addr->remote_addr);
1313 }
1314
1315 /* RFC5953: section 5.4, step 3:
1316 3) If there is no open session associated with the tmSessionID, then
1317 closeSession processing is completed.
1318 */
1319 if (NULL == cachep)
1320 return netsnmp_socketbase_close(t);
1321
1322 /* if we have any remaining packets to send, try to send them */
1323 if (cachep->write_cache_len > 0) {
1324 int i = 0;
1325 char buf[8192];
1326 int rc;
1327 void *opaque = NULL;
1328 int opaque_len = 0;
1329 fd_set readfs;
1330 NETSNMP_SELECT_TIMEVAL tv;
1331
1332 DEBUGMSGTL(("dtlsudp:close",
1333 "%" NETSNMP_PRIz "d bytes remain in write_cache\n",
1334 cachep->write_cache_len));
1335
1336 /*
1337 * if negotiations have completed and we've received data, try and
1338 * send any queued packets.
1339 */
1340 if (1) {
1341 /* make configurable:
1342 - do this at all?
1343 - retries
1344 - timeout
1345 */
1346 for (i = 0; i < 6 && cachep->write_cache_len != 0; ++i) {
1347
1348 /* first see if we can send out what we have */
1349 _netsnmp_bio_try_and_write_buffered(t, cachep);
1350 if (cachep->write_cache_len == 0)
1351 break;
1352
1353 /* if we've failed that, we probably need to wait for packets */
1354 FD_ZERO(&readfs);
1355 FD_SET(t->sock, &readfs);
1356 tv.tv_sec = 0;
1357 tv.tv_usec = 50000;
1358 rc = select(t->sock+1, &readfs, NULL, NULL, &tv);
1359 if (rc > 0) {
1360 /* junk recv for catching negotiations still in play */
1361 opaque_len = 0;
1362 rc = netsnmp_dtlsudp_recv(t, buf, sizeof(buf),
1363 &opaque, &opaque_len);
1364 DEBUGMSGTL(("dtlsudp:close",
1365 "netsnmp_dtlsudp_recv() returned %d\n", rc));
1366 SNMP_FREE(opaque);
1367 }
1368 } /* for loop */
1369 }
1370
1371 /** dump anything that wasn't sent */
1372 if (cachep->write_cache_len > 0) {
1373 DEBUGMSGTL(("dtlsudp:close",
1374 "dumping %" NETSNMP_PRIz "d bytes from write_cache\n",
1375 cachep->write_cache_len));
1376 SNMP_FREE(cachep->write_cache);
1377 cachep->write_cache_len = 0;
1378 }
1379 }
1380
1381 /* RFC5953: section 5.4, step 4:
1382 4) Have (D)TLS close the specified connection. This MUST include
1383 sending a close_notify TLS Alert to inform the other side that
1384 session cleanup may be performed.
1385 */
1386 if (NULL != cachep->tlsdata && NULL != cachep->tlsdata->ssl) {
1387
1388 DEBUGMSGTL(("dtlsudp:close", "closing SSL socket\n"));
1389 SSL_shutdown(cachep->tlsdata->ssl);
1390
1391 /* send the close_notify we maybe generated in step 4 */
1392 if (BIO_ctrl_pending(cachep->write_bio) > 0)
1393 _netsnmp_send_queued_dtls_pkts(t, cachep);
1394 }
1395
1396 remove_and_free_bio_cache(cachep);
1397
1398 return netsnmp_socketbase_close(t);
1399 }
1400
1401 static char *
1402 netsnmp_dtlsudp_fmtaddr(netsnmp_transport *t, const void *data, int len,
1403 const char *pfx,
1404 char *(*fmt_base_addr)(const char *pfx,
1405 netsnmp_transport *t,
1406 const void *data, int len))
1407 {
1408 if (!data) {
1409 data = t->data;
1410 len = t->data_length;
1411 }
1412
1413 switch (data ? len : 0) {
1414 case sizeof(netsnmp_indexed_addr_pair):
1415 return netsnmp_ipv4_fmtaddr(pfx, t, data, len);
1416 case sizeof(netsnmp_tmStateReference): {
1417 const netsnmp_tmStateReference *r = data;
1418 const netsnmp_indexed_addr_pair *p = &r->addresses;
1419 netsnmp_transport *bt = t->base_transport;
1420
1421 if (r->have_addresses) {
1422 return fmt_base_addr("DTLSUDP", t, p, sizeof(*p));
1423 } else if (bt && t->data_length == sizeof(_netsnmpTLSBaseData)) {
1424 _netsnmpTLSBaseData *tlsdata = t->data;
1425 netsnmp_indexed_addr_pair *tls_addr = tlsdata->addr;
1426
1427 return bt->f_fmtaddr(bt, tls_addr, sizeof(*tls_addr));
1428 } else if (bt) {
1429 return bt->f_fmtaddr(bt, t->data, t->data_length);
1430 } else {
1431 return strdup("DTLSUDP: unknown");
1432 }
1433 }
1434 case sizeof(_netsnmpTLSBaseData): {
1435 const _netsnmpTLSBaseData *b = data;
1436 char *buf;
1437
1438 if (asprintf(&buf, "DTLSUDP: %s", b->addr_string) < 0)
1439 buf = NULL;
1440 return buf;
1441 }
1442 case 0:
1443 return strdup("DTLSUDP: unknown");
1444 default: {
1445 char *buf;
1446
1447 if (asprintf(&buf, "DTLSUDP: len %d", len) < 0)
1448 buf = NULL;
1449 return buf;
1450 }
1451 }
1452 }
1453
1454 static char *
1455 netsnmp_dtlsudp4_fmtaddr(netsnmp_transport *t, const void *data, int len)
1456 {
1457 return netsnmp_dtlsudp_fmtaddr(t, data, len, "DTLSUDP",
1458 netsnmp_ipv4_fmtaddr);
1459 }
1460
1461 /*
1462 * Open a DTLS-based transport for SNMP. Local is TRUE if addr is the local
1463 * address to bind to (i.e. this is a server-type session); otherwise addr is
1464 * the remote address to send things to.
1465 */
1466
1467 static netsnmp_transport *
1468 _transport_common(netsnmp_transport *t, int local)
1469 {
1470 char *tmp = NULL;
1471 int tmp_len;
1472
1473 DEBUGTRACETOK("9:dtlsudp");
1474
1475 if (NULL == t)
1476 return NULL;
1477
1478 /** save base transport for clients; need in send/recv functions later */
1479 if (t->data) { /* don't copy data */
1480 tmp = t->data;
1481 tmp_len = t->data_length;
1482 t->data = NULL;
1483 }
1484 t->base_transport = netsnmp_transport_copy(t);
1485
1486 if (tmp) {
1487 t->data = tmp;
1488 t->data_length = tmp_len;
1489 }
1490 if (NULL != t->data &&
1491 t->data_length == sizeof(netsnmp_indexed_addr_pair)) {
1492 _netsnmpTLSBaseData *tlsdata =
1493 netsnmp_tlsbase_allocate_tlsdata(t, local);
1494 tlsdata->addr = t->data;
1495 t->data = tlsdata;
1496 t->data_length = sizeof(_netsnmpTLSBaseData);
1497 }
1498
1499 /*
1500 * Set Domain
1501 */
1502 t->domain = netsnmpDTLSUDPDomain;
1503 t->domain_length = netsnmpDTLSUDPDomain_len;
1504
1505 t->f_recv = netsnmp_dtlsudp_recv;
1506 t->f_send = netsnmp_dtlsudp_send;
1507 t->f_close = netsnmp_dtlsudp_close;
1508 t->f_config = netsnmp_tlsbase_config;
1509 t->f_setup_session = netsnmp_tlsbase_session_init;
1510 t->f_accept = NULL;
1511 t->f_fmtaddr = netsnmp_dtlsudp4_fmtaddr;
1512 t->f_get_taddr = netsnmp_ipv4_get_taddr;
1513
1514 t->flags = NETSNMP_TRANSPORT_FLAG_TUNNELED;
1515
1516 return t;
1517 }
1518
1519 netsnmp_transport *
1520 netsnmp_dtlsudp_transport(const struct netsnmp_ep *ep, int local)
1521 {
1522 const struct sockaddr_in *addr = &ep->a.sin;
1523 netsnmp_transport *t, *t2;
1524
1525 DEBUGTRACETOK("dtlsudp");
1526
1527 t = netsnmp_udp_transport(ep, local);
1528 if (NULL == t)
1529 return NULL;
1530
1531 t2 = _transport_common(t, local);
1532 if (!t2) {
1533 netsnmp_transport_free(t);
1534 return NULL;
1535 }
1536
1537 if (!local) {
1538 /* dtls needs to bind the socket for SSL_write to work */
1539 if (connect(t->sock, (const struct sockaddr *)addr, sizeof(*addr)) < 0)
1540 snmp_log(LOG_ERR, "dtls: failed to connect\n");
1541 }
1542
1543 return t2;
1544 }
1545
1546
1547 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1548
1549 static char *
1550 netsnmp_dtlsudp6_fmtaddr(netsnmp_transport *t, const void *data, int len)
1551 {
1552 return netsnmp_dtlsudp_fmtaddr(t, data, len, "DTLSUDP6",
1553 netsnmp_ipv6_fmtaddr);
1554 }
1555
1556 /*
1557 * Open a DTLS-based transport for SNMP. Local is TRUE if addr is the local
1558 * address to bind to (i.e. this is a server-type session); otherwise addr is
1559 * the remote address to send things to.
1560 */
1561
1562 netsnmp_transport *
1563 netsnmp_dtlsudp6_transport(const struct netsnmp_ep *ep, int local)
1564 {
1565 const struct sockaddr_in6 *addr = &ep->a.sin6;
1566 netsnmp_transport *t, *t2;
1567
1568 DEBUGTRACETOK("dtlsudp");
1569
1570 t = netsnmp_udp6_transport(ep, local);
1571 if (NULL == t)
1572 return NULL;
1573
1574 t2 = _transport_common(t, local);
1575 if (!t2) {
1576 netsnmp_transport_free(t);
1577 return NULL;
1578 }
1579
1580 if (!local) {
1581 /* dtls needs to bind the socket for SSL_write to work */
1582 if (connect(t->sock, (const struct sockaddr *)addr, sizeof(*addr)) < 0)
1583 snmp_log(LOG_ERR, "dtls: failed to connect\n");
1584 }
1585
1586 /* XXX: Potentially set sock opts here (SO_SNDBUF/SO_RCV_BUF) */
1587 /* XXX: and buf size */
1588
1589 t2->f_fmtaddr = netsnmp_dtlsudp6_fmtaddr;
1590 t2->f_get_taddr = netsnmp_ipv6_get_taddr;
1591
1592 return t2;
1593 }
1594 #endif
1595
1596
1597 netsnmp_transport *
1598 netsnmp_dtlsudp_create_tstring(const char *str, int isserver,
1599 const char *default_target)
1600 {
1601 struct netsnmp_ep ep;
1602 netsnmp_transport *t;
1603 _netsnmpTLSBaseData *tlsdata;
1604 char buf[SPRINT_MAX_LEN], *cp;
1605
1606 if (netsnmp_sockaddr_in3(&ep, str, default_target))
1607 t = netsnmp_dtlsudp_transport(&ep, isserver);
1608 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1609 else if (netsnmp_sockaddr_in6_3(&ep, str, default_target))
1610 t = netsnmp_dtlsudp6_transport(&ep, isserver);
1611 #endif
1612 else
1613 return NULL;
1614
1615
1616 /* see if we can extract the remote hostname */
1617 if (!isserver && t && t->data && str) {
1618 tlsdata = t->data;
1619 /* search for a : */
1620 if (NULL != (cp = strrchr(str, ':'))) {
1621 sprintf(buf, "%.*s", (int) SNMP_MIN(cp - str, sizeof(buf) - 1),
1622 str);
1623 } else {
1624 /* else the entire spec is a host name only */
1625 strlcpy(buf, str, sizeof(buf));
1626 }
1627 tlsdata->their_hostname = strdup(buf);
1628 }
1629 return t;
1630 }
1631
1632
1633 netsnmp_transport *
1634 netsnmp_dtlsudp_create_ostring(const void *o, size_t o_len, int local)
1635 {
1636 struct netsnmp_ep ep;
1637
1638 memset(&ep, 0, sizeof(ep));
1639 if (netsnmp_ipv4_ostring_to_sockaddr(&ep.a.sin, o, o_len))
1640 return netsnmp_dtlsudp_transport(&ep, local);
1641 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1642 else if (netsnmp_ipv6_ostring_to_sockaddr(&ep.a.sin6, o, o_len))
1643 return netsnmp_dtlsudp6_transport(&ep, local);
1644 #endif
1645 else
1646 return NULL;
1647 }
1648
1649 void
1650 netsnmp_dtlsudp_ctor(void)
1651 {
1652 static const char indexname[] = "_netsnmp_addr_info";
1653 static const char *prefixes[] = { "dtlsudp", "dtls"
1654 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1655 , "dtlsudp6", "dtls6"
1656 #endif
1657 };
1658 int i, num_prefixes = sizeof(prefixes) / sizeof(char *);
1659 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1660 static const char indexname6[] = "_netsnmp_addr_info6";
1661 #endif
1662
1663 DEBUGMSGTL(("dtlsudp", "registering DTLS constructor\n"));
1664
1665 /* config settings */
1666
1667 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1668 if (!openssl_addr_index6)
1669 openssl_addr_index6 =
1670 SSL_get_ex_new_index(0, NETSNMP_REMOVE_CONST(void *, indexname6),
1671 NULL, NULL, NULL);
1672 #endif
1673
1674 dtlsudpDomain.name = netsnmpDTLSUDPDomain;
1675 dtlsudpDomain.name_length = netsnmpDTLSUDPDomain_len;
1676 dtlsudpDomain.prefix = calloc(num_prefixes + 1, sizeof(char *));
1677 for (i = 0; i < num_prefixes; ++ i)
1678 dtlsudpDomain.prefix[i] = prefixes[i];
1679
1680 dtlsudpDomain.f_create_from_tstring_new = netsnmp_dtlsudp_create_tstring;
1681 dtlsudpDomain.f_create_from_ostring = netsnmp_dtlsudp_create_ostring;
1682
1683 if (!openssl_addr_index)
1684 openssl_addr_index =
1685 SSL_get_ex_new_index(0, NETSNMP_REMOVE_CONST(void *, indexname),
1686 NULL, NULL, NULL);
1687
1688 netsnmp_tdomain_register(&dtlsudpDomain);
1689 }
1690
1691 /*
1692 * Much of the code below was taken from the OpenSSL example code
1693 * and is subject to the OpenSSL copyright.
1694 */
1695 #define NETSNMP_COOKIE_SECRET_LENGTH 16
1696 int cookie_initialized=0;
1697 unsigned char cookie_secret[NETSNMP_COOKIE_SECRET_LENGTH];
1698
1699 #ifdef HAVE_SSL_CTX_SET_COOKIE_GENERATE_CB
1700 int netsnmp_dtls_gen_cookie(SSL *ssl, unsigned char *cookie,
1701 unsigned int *cookie_len)
1702 {
1703 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
1704 unsigned int length, resultlength;
1705 bio_cache *cachep = NULL;
1706 const netsnmp_sockaddr_storage *peer;
1707
1708 /* Initialize a random secret */
1709 if (!cookie_initialized) {
1710 if (!RAND_bytes(cookie_secret, NETSNMP_COOKIE_SECRET_LENGTH)) {
1711 snmp_log(LOG_ERR, "dtls: error setting random cookie secret\n");
1712 return 0;
1713 }
1714 MAKE_MEM_DEFINED(cookie_secret, NETSNMP_COOKIE_SECRET_LENGTH);
1715 cookie_initialized = 1;
1716 }
1717
1718 DEBUGMSGT(("dtlsudp:cookie", "generating cookie...\n"));
1719
1720 /* Read peer information */
1721 cachep = SSL_get_ex_data(ssl, openssl_addr_index);
1722 if (!cachep) {
1723 snmp_log(LOG_ERR, "dtls: failed to get the peer address\n");
1724 return 0;
1725 }
1726 peer = &cachep->sas;
1727
1728 /* Create buffer with peer's address and port */
1729 length = 0;
1730 switch (peer->sa.sa_family) {
1731 case AF_INET:
1732 length += sizeof(struct in_addr);
1733 length += sizeof(peer->sin.sin_port);
1734 break;
1735 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1736 case AF_INET6:
1737 length += sizeof(struct in6_addr);
1738 length += sizeof(peer->sin6.sin6_port);
1739 break;
1740 #endif
1741 default:
1742 snmp_log(LOG_ERR, "dtls generating cookie: unknown family: %d\n",
1743 peer->sa.sa_family);
1744 return 0;
1745 }
1746 buffer = malloc(length);
1747 if (buffer == NULL) {
1748 snmp_log(LOG_ERR,"dtls: out of memory\n");
1749 return 0;
1750 }
1751
1752 switch (peer->sa.sa_family) {
1753 case AF_INET:
1754 memcpy(buffer,
1755 &peer->sin.sin_port,
1756 sizeof(peer->sin.sin_port));
1757 memcpy(buffer + sizeof(peer->sin.sin_port),
1758 &peer->sin.sin_addr,
1759 sizeof(struct in_addr));
1760 break;
1761 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1762 case AF_INET6:
1763 memcpy(buffer,
1764 &peer->sin6.sin6_port,
1765 sizeof(peer->sin6.sin6_port));
1766 memcpy(buffer + sizeof(peer->sin6.sin6_port),
1767 &peer->sin6.sin6_addr,
1768 sizeof(struct in6_addr));
1769 break;
1770 #endif
1771 default:
1772 snmp_log(LOG_ERR, "dtls: unknown address family generating a cookie\n");
1773 free(buffer);
1774 return 0;
1775 }
1776
1777 /* Calculate HMAC of buffer using the secret */
1778 HMAC(EVP_sha1(), cookie_secret, NETSNMP_COOKIE_SECRET_LENGTH,
1779 buffer, length, result, &resultlength);
1780 free(buffer);
1781
1782 memcpy(cookie, result, resultlength);
1783 *cookie_len = resultlength;
1784
1785 DEBUGMSGT(("9:dtlsudp:cookie", "generated %d byte cookie\n", *cookie_len));
1786
1787 return 1;
1788 }
1789
1790 int netsnmp_dtls_verify_cookie(SSL *ssl,
1791 SECOND_APPVERIFY_COOKIE_CB_ARG_QUALIFIER
1792 unsigned char *cookie,
1793 unsigned int cookie_len)
1794 {
1795 unsigned char *buffer, result[EVP_MAX_MD_SIZE];
1796 unsigned int length, resultlength, rc;
1797 bio_cache *cachep = NULL;
1798 const netsnmp_sockaddr_storage *peer;
1799
1800 /* If secret isn't initialized yet, the cookie can't be valid */
1801 if (!cookie_initialized)
1802 return 0;
1803
1804 DEBUGMSGT(("9:dtlsudp:cookie", "verifying %d byte cookie\n", cookie_len));
1805
1806 cachep = SSL_get_ex_data(ssl, openssl_addr_index);
1807 if (!cachep) {
1808 snmp_log(LOG_ERR, "dtls: failed to get the peer address\n");
1809 return 0;
1810 }
1811 peer = &cachep->sas;
1812
1813 /* Create buffer with peer's address and port */
1814 length = 0;
1815 switch (peer->sa.sa_family) {
1816 case AF_INET:
1817 length += sizeof(struct in_addr);
1818 length += sizeof(peer->sin.sin_port);
1819 break;
1820 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1821 case AF_INET6:
1822 length += sizeof(struct in6_addr);
1823 length += sizeof(peer->sin6.sin6_port);
1824 break;
1825 #endif
1826 default:
1827 snmp_log(LOG_ERR,
1828 "dtls: unknown address family %d generating a cookie\n",
1829 peer->sa.sa_family);
1830 return 0;
1831 }
1832 buffer = malloc(length);
1833 if (buffer == NULL) {
1834 snmp_log(LOG_ERR, "dtls: unknown address family generating a cookie\n");
1835 return 0;
1836 }
1837
1838 switch (peer->sa.sa_family) {
1839 case AF_INET:
1840 memcpy(buffer,
1841 &peer->sin.sin_port,
1842 sizeof(peer->sin.sin_port));
1843 memcpy(buffer + sizeof(peer->sin.sin_port),
1844 &peer->sin.sin_addr,
1845 sizeof(struct in_addr));
1846 break;
1847 #ifdef NETSNMP_TRANSPORT_UDPIPV6_DOMAIN
1848 case AF_INET6:
1849 memcpy(buffer,
1850 &peer->sin6.sin6_port,
1851 sizeof(peer->sin6.sin6_port));
1852 memcpy(buffer + sizeof(peer->sin6.sin6_port),
1853 &peer->sin6.sin6_addr,
1854 sizeof(struct in6_addr));
1855 break;
1856 #endif
1857 default:
1858 snmp_log(LOG_ERR,
1859 "dtls: unknown address family %d generating a cookie\n",
1860 peer->sa.sa_family);
1861 free(buffer);
1862 return 0;
1863 }
1864
1865 /* Calculate HMAC of buffer using the secret */
1866 HMAC(EVP_sha1(), cookie_secret, NETSNMP_COOKIE_SECRET_LENGTH,
1867 buffer, length, result, &resultlength);
1868 free(buffer);
1869
1870 if (cookie_len != resultlength || memcmp(result, cookie, resultlength) != 0)
1871 rc = 0;
1872 else {
1873 rc = 1;
1874 cachep->flags |= NETSNMP_BIO_HAVE_COOKIE;
1875 }
1876
1877 DEBUGMSGT(("dtlsudp:cookie", "verify cookie: %d\n", rc));
1878
1879 return rc;
1880 }
1881 #endif /* #ifdef HAVE_SSL_CTX_SET_COOKIE_GENERATE_CB */
1882
1883 #endif /* HAVE_LIBSSL_DTLS */