Debian Codegraph @

snmplib/transports/snmpTLSTCPDomain.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 * See the following web pages for useful documentation on this transport:
7 * http://www.net-snmp.org/wiki/index.php/TUT:Using_TLS
8 * http://www.net-snmp.org/wiki/index.php/Using_DTLS
9 */
10 #include <net-snmp/net-snmp-config.h>
11
12 #include <net-snmp/net-snmp-features.h>
13
14 netsnmp_feature_require(cert_util);
15
16 #include <stdio.h>
17 #include <sys/types.h>
18 #include <ctype.h>
19 #include <errno.h>
20
21 #ifdef HAVE_STRING_H
22 #include <string.h>
23 #else
24 #include <strings.h>
25 #endif
26 #ifdef HAVE_STDLIB_H
27 #include <stdlib.h>
28 #endif
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
34 #endif
35 #ifdef HAVE_NETINET_IN_H
36 #include <netinet/in.h>
37 #endif
38 #ifdef HAVE_ARPA_INET_H
39 #include <arpa/inet.h>
40 #endif
41 #ifdef HAVE_NETDB_H
42 #include <netdb.h>
43 #endif
44 #ifdef HAVE_SYS_UIO_H
45 #include <sys/uio.h>
46 #endif
47
48 #ifdef HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
50 #endif
51
52 #include "../memcheck.h"
53
54 #include <net-snmp/types.h>
55 #include <net-snmp/output_api.h>
56 #include <net-snmp/config_api.h>
57 #include <net-snmp/library/snmp_assert.h>
58 #include <net-snmp/library/snmpIPv4BaseDomain.h>
59 #include <net-snmp/library/snmpSocketBaseDomain.h>
60 #include <net-snmp/library/snmpTLSBaseDomain.h>
61 #include <net-snmp/library/snmpTLSTCPDomain.h>
62 #include <net-snmp/library/system.h>
63 #include <net-snmp/library/tools.h>
64 #include <net-snmp/library/cert_util.h>
65 #include <net-snmp/library/snmp_openssl.h>
66 #include <net-snmp/library/callback.h>
67
68 #include "openssl/bio.h"
69 #include "openssl/ssl.h"
70 #include "openssl/err.h"
71
72 #ifndef INADDR_NONE
73 #define INADDR_NONE -1
74 #endif
75
76 #define WE_ARE_SERVER 0
77 #define WE_ARE_CLIENT 1
78
79 oid netsnmpTLSTCPDomain[] = { TRANSPORT_DOMAIN_TLS_TCP_IP };
80 size_t netsnmpTLSTCPDomain_len = OID_LENGTH(netsnmpTLSTCPDomain);
81
82 static netsnmp_tdomain tlstcpDomain;
83
84 /*
85 * Return a string representing the address in data, or else the "far end"
86 * address if data is NULL.
87 */
88
89 static char *
90 netsnmp_tlstcp_fmtaddr(netsnmp_transport *t, const void *data, int len)
91 {
92 if (t && !data) {
93 data = t->data;
94 len = t->data_length;
95 }
96
97 switch (data ? len : 0) {
98 case sizeof(netsnmp_indexed_addr_pair):
99 return netsnmp_ipv4_fmtaddr("TLSTCP", t, data, len);
100 case sizeof(netsnmp_tmStateReference): {
101 const netsnmp_tmStateReference *r = data;
102 const netsnmp_indexed_addr_pair *p = &r->addresses;
103
104 return netsnmp_ipv4_fmtaddr("TLSTCP", t, p, sizeof(*p));
105 }
106 case sizeof(_netsnmpTLSBaseData): {
107 const _netsnmpTLSBaseData *b = data;
108 char *buf;
109
110 if (asprintf(&buf, "TLSTCP: %s", b->addr_string) < 0)
111 buf = NULL;
112 return buf;
113 }
114 case 0:
115 return strdup("TLSTCP: unknown");
116 default: {
117 char *buf;
118
119 if (asprintf(&buf, "TLSTCP: len %d", len) < 0)
120 buf = NULL;
121 return buf;
122 }
123 }
124 }
125
126 static void netsnmp_tlstcp_get_taddr(struct netsnmp_transport_s *t,
127 void **addr, size_t *addr_len)
128 {
129 *addr_len = t->remote_length;
130 *addr = netsnmp_memdup(t->remote, *addr_len);
131 }
132
133 /*
134 * You can write something into opaque that will subsequently get passed back
135 * to your send function if you like. For instance, you might want to
136 * remember where a PDU came from, so that you can send a reply there...
137 */
138
139 static int
140 netsnmp_tlstcp_copy(const netsnmp_transport *oldt, netsnmp_transport *newt)
141 {
142 _netsnmpTLSBaseData *oldtlsdata = (_netsnmpTLSBaseData *) oldt->data;
143 _netsnmpTLSBaseData *newtlsdata = (_netsnmpTLSBaseData *) newt->data;
144 oldtlsdata->accepted_bio = NULL;
145 oldtlsdata->ssl = NULL;
146 newtlsdata->ssl_context = NULL;
147
148 if (oldtlsdata->addr_string)
149 newtlsdata->addr_string = strdup(oldtlsdata->addr_string);
150 if (oldtlsdata->securityName)
151 newtlsdata->securityName = strdup(oldtlsdata->securityName);
152 if (oldtlsdata->our_identity)
153 newtlsdata->our_identity = strdup(oldtlsdata->our_identity);
154 if (oldtlsdata->their_identity)
155 newtlsdata->their_identity = strdup(oldtlsdata->their_identity);
156 if (oldtlsdata->their_fingerprint)
157 newtlsdata->their_fingerprint = strdup(oldtlsdata->their_fingerprint);
158 if (oldtlsdata->their_hostname)
159 newtlsdata->their_hostname = strdup(oldtlsdata->their_hostname);
160 if (oldtlsdata->trust_cert)
161 newtlsdata->trust_cert = strdup(oldtlsdata->trust_cert);
162 if (oldtlsdata->addr)
163 newtlsdata->addr = netsnmp_memdup(oldtlsdata->addr,
164 sizeof(*oldtlsdata->addr));
165
166 return 0;
167 }
168
169 static int
170 netsnmp_tlstcp_recv(netsnmp_transport *t, void *buf, int size,
171 void **opaque, int *olength)
172 {
173 int rc = -1;
174 netsnmp_tmStateReference *tmStateRef = NULL;
175 _netsnmpTLSBaseData *tlsdata;
176
177 if (NULL == t || t->sock < 0 || NULL == t->data) {
178 snmp_log(LOG_ERR,
179 "tlstcp received an invalid invocation with missing data\n");
180 DEBUGMSGTL(("tlstcp", "recvfrom fd %d err %d (\"%s\")\n",
181 (t ? t->sock : -1), errno, strerror(errno)));
182 if (t)
183 DEBUGMSGTL(("tlstcp", " tdata = %p", t->data));
184 DEBUGMSGTL(("tlstcp", "\n"));
185 return -1;
186 }
187
188 /* RFC5953 Section 5.1.2 step 1:
189 1) Determine the tlstmSessionID for the incoming message. The
190 tlstmSessionID MUST be a unique session identifier for this
191 (D)TLS connection. The contents and format of this identifier
192 are implementation-dependent as long as it is unique to the
193 session. A session identifier MUST NOT be reused until all
194 references to it are no longer in use. The tmSessionID is
195 equal to the tlstmSessionID discussed in Section 5.1.1.
196 tmSessionID refers to the session identifier when stored in the
197 tmStateReference and tlstmSessionID refers to the session
198 identifier when stored in the LCD. They MUST always be equal
199 when processing a given session's traffic.
200 */
201 /* For this implementation we use the t->data memory pointer as
202 the sessionID. As it's a pointer to session specific data tied
203 with the transport object we know it'll never be realloated
204 (ie, duplicated) until release by this transport object and is
205 safe to use as a unique session identifier. */
206
207 tlsdata = t->data;
208 if (NULL == tlsdata->ssl) {
209 snmp_log(LOG_ERR,
210 "tlstcp received an invalid invocation without ssl data\n");
211 return -1;
212 }
213
214 /* RFC5953 Section 5.1.2 step 1, part2:
215 * This part (incrementing the counter) is done in the
216 netsnmp_tlstcp_accept function.
217 */
218
219
220 /* RFC5953 Section 5.1.2 step 2:
221 * Create a tmStateReference cache for the subsequent reference and
222 assign the following values within it:
223
224 tmTransportDomain = snmpTLSTCPDomain or snmpDTLSUDPDomain as
225 appropriate.
226
227 tmTransportAddress = The address the message originated from.
228
229 tmSecurityLevel = The derived tmSecurityLevel for the session,
230 as discussed in Section 3.1.2 and Section 5.3.
231
232 tmSecurityName = The fderived tmSecurityName for the session as
233 discussed in Section 5.3. This value MUST
234 be constant during the lifetime of the
235 session.
236
237 tmSessionID = The tlstmSessionID described in step 1 above.
238 */
239
240 /* Implementation notes:
241 * - The tmTransportDomain is represented by the transport object
242 * - The tmpSessionID is represented by the tlsdata pointer (as
243 discussed above)
244 * - The following items are handled later in netsnmp_tlsbase_wrapup_recv:
245 - tmSecurityLevel
246 - tmSecurityName
247 - tmSessionID
248 */
249
250 /* create a tmStateRef cache for slow fill-in */
251 tmStateRef = SNMP_MALLOC_TYPEDEF(netsnmp_tmStateReference);
252
253 if (tmStateRef == NULL) {
254 *opaque = NULL;
255 *olength = 0;
256 return -1;
257 }
258
259 /* Set the transportDomain */
260 memcpy(tmStateRef->transportDomain,
261 netsnmpTLSTCPDomain, sizeof(netsnmpTLSTCPDomain[0]) *
262 netsnmpTLSTCPDomain_len);
263 tmStateRef->transportDomainLen = netsnmpTLSTCPDomain_len;
264
265 /* Set the tmTransportAddress */
266 tmStateRef->have_addresses = 1;
267
268 /* RFC5953 Section 5.1.2 step 1:
269 * 3) The incomingMessage and incomingMessageLength are assigned values
270 from the (D)TLS processing.
271 */
272
273 /* Implementation notes:
274 - incomingMessage = buf pointer
275 - incomingMessageLength = rc
276 */
277
278 /* read the packet from openssl */
279 do {
280 rc = SSL_read(tlsdata->ssl, buf, size);
281 MAKE_MEM_DEFINED(&rc, sizeof(rc));
282 if (rc > 0)
283 MAKE_MEM_DEFINED(buf, rc);
284 if (rc == 0) {
285 /* XXX closed connection */
286 DEBUGMSGTL(("tlstcp", "remote side closed connection\n"));
287 /* XXX: openssl cleanup */
288 SNMP_FREE(tmStateRef);
289 return -1;
290 }
291 if (rc == -1) {
292 int err = SSL_get_error(tlsdata->ssl, rc);
293 if (err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE) {
294 /* error detected */
295 _openssl_log_error(rc, tlsdata->ssl, "SSL_read");
296 SNMP_FREE(tmStateRef);
297 return rc;
298 }
299 }
300 /* retry read for SSL_ERROR_WANT_READ || SSL_ERROR_WANT_WRITE */
301 } while (rc <= 0);
302
303 DEBUGMSGTL(("tlstcp", "received %d decoded bytes from tls\n", rc));
304
305 /* log the packet */
306 DEBUGIF("tlstcp") {
307 char *str = netsnmp_tlstcp_fmtaddr(t, NULL, 0);
308 DEBUGMSGTL(("tlstcp",
309 "recvfrom fd %d got %d bytes (from %s)\n",
310 t->sock, rc, str));
311 free(str);
312 }
313
314 /* Other wrap-up things common to TLS and DTLS */
315 if (netsnmp_tlsbase_wrapup_recv(tmStateRef, tlsdata, opaque, olength) !=
316 SNMPERR_SUCCESS)
317 return SNMPERR_GENERR;
318
319 /* RFC5953 Section 5.1.2 step 1:
320 * 4) The TLS Transport Model passes the transportDomain,
321 transportAddress, incomingMessage, and incomingMessageLength to
322 the Dispatcher using the receiveMessage ASI:
323 */
324
325 /* In our implementation, this is done simply by returning */
326 return rc;
327 }
328
329
330
331 static int
332 netsnmp_tlstcp_send(netsnmp_transport *t, const void *buf, int size,
333 void **opaque, int *olength)
334 {
335 int rc = -1;
336 const netsnmp_tmStateReference *tmStateRef = NULL;
337 _netsnmpTLSBaseData *tlsdata;
338
339 DEBUGTRACETOK("tlstcp");
340
341 /* RFC5953 section 5.2:
342 1) If tmStateReference does not refer to a cache containing values
343 for tmTransportDomain, tmTransportAddress, tmSecurityName,
344 tmRequestedSecurityLevel, and tmSameSecurity, then increment the
345 snmpTlstmSessionInvalidCaches counter, discard the message, and
346 return the error indication in the statusInformation. Processing
347 of this message stops.
348 */
349 /* Implementation Notes: the tmStateReference is stored in the opaque ptr */
350 if (opaque != NULL && *opaque != NULL &&
351 *olength == sizeof(netsnmp_tmStateReference)) {
352 tmStateRef = (const netsnmp_tmStateReference *) *opaque;
353 } else {
354 snmp_log(LOG_ERR, "TLSTCP was called with an invalid state; possibly the wrong security model is in use. It should be 'tsm'.\n");
355 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONINVALIDCACHES);
356 return SNMPERR_GENERR;
357 }
358
359 /* RFC5953 section 5.2:
360 2) Extract the tmSessionID, tmTransportDomain, tmTransportAddress,
361 tmSecurityName, tmRequestedSecurityLevel, and tmSameSecurity
362 values from the tmStateReference. Note: The tmSessionID value
363 may be undefined if no session exists yet over which the message
364 can be sent.
365 */
366 /* Implementation Notes:
367 - Our session will always exist by now as it's created when the
368 transport object is created. Auto-session creation is handled
369 higher in the stack.
370 - We don't "extract" per say since we just leave the data in
371 the structure.
372 - The sessionID is stored in the t->data memory pointer.
373 */
374
375 /* RFC5953 section 5.2:
376 3) If tmSameSecurity is true and either tmSessionID is undefined or
377 refers to a session that is no longer open then increment the
378 snmpTlstmSessionNoSessions counter, discard the message and
379 return the error indication in the statusInformation. Processing
380 of this message stops.
381 */
382 /* Implementation Notes:
383 - We would never get here if the sessionID was either undefined
384 or different. We tie packets directly to the transport
385 object and it could never be sent back over a different
386 transport, which is what the above text is trying to prevent.
387 */
388
389 /* RFC5953 section 5.2:
390 4) If tmSameSecurity is false and tmSessionID refers to a session
391 that is no longer available then an implementation SHOULD open a
392 new session using the openSession() ASI (described in greater
393 detail in step 5b). Instead of opening a new session an
394 implementation MAY return a snmpTlstmSessionNoSessions error to
395 the calling module and stop processing of the message.
396 */
397 /* Implementation Notes:
398 - We would never get here if the sessionID was either undefined
399 or different. We tie packets directly to the transport
400 object and it could never be sent back over a different
401 transport, which is what the above text is trying to prevent.
402 - Auto-connections are handled higher in the Net-SNMP library stack
403 */
404
405 /* RFC5953 section 5.2:
406 5) If tmSessionID is undefined, then use tmTransportDomain,
407 tmTransportAddress, tmSecurityName and tmRequestedSecurityLevel
408 to see if there is a corresponding entry in the LCD suitable to
409 send the message over.
410
411 5a) If there is a corresponding LCD entry, then this session
412 will be used to send the message.
413
414 5b) If there is not a corresponding LCD entry, then open a
415 session using the openSession() ASI (discussed further in
416 Section 5.3.1). Implementations MAY wish to offer message
417 buffering to prevent redundant openSession() calls for the
418 same cache entry. If an error is returned from
419 openSession(), then discard the message, discard the
420 tmStateReference, increment the snmpTlstmSessionOpenErrors,
421 return an error indication to the calling module and stop
422 processing of the message.
423 */
424 /* Implementation Notes:
425 - We would never get here if the sessionID was either undefined
426 or different. We tie packets directly to the transport
427 object and it could never be sent back over a different
428 transport, which is what the above text is trying to prevent.
429 - Auto-connections are handled higher in the Net-SNMP library stack
430 */
431
432 /* our session pointer is functionally t->data */
433 if (NULL == t->data) {
434 snmp_log(LOG_ERR, "netsnmp_tlstcp_send received no incoming data\n");
435 return -1;
436 }
437
438 tlsdata = t->data;
439
440 if (tlsdata->ssl == NULL) {
441 snmp_log(LOG_ERR, "tlstcp_send was called without a SSL connection.\n");
442 return SNMPERR_GENERR;
443 }
444
445 /* If the first packet and we have no secname, then copy the
446 important securityName data into the longer-lived session
447 reference information. */
448 if ((tlsdata->flags & NETSNMP_TLSBASE_IS_CLIENT) &&
449 !tlsdata->securityName && tmStateRef && tmStateRef->securityNameLen > 0)
450 tlsdata->securityName = strdup(tmStateRef->securityName);
451
452
453 /* RFC5953 section 5.2:
454 6) Using either the session indicated by the tmSessionID if there
455 was one or the session resulting from a previous step (4 or 5),
456 pass the outgoingMessage to (D)TLS for encapsulation and
457 transmission.
458 */
459 rc = SSL_write(tlsdata->ssl, buf, size);
460 DEBUGMSGTL(("tlstcp", "wrote %d bytes\n", size));
461 if (rc < 0) {
462 _openssl_log_error(rc, tlsdata->ssl, "SSL_write");
463 }
464
465 return rc;
466 }
467
468
469
470 static int
471 netsnmp_tlstcp_close(netsnmp_transport *t)
472 {
473 _netsnmpTLSBaseData *tlsdata;
474
475 if (NULL == t || NULL == t->data)
476 return -1;
477
478 /* RFC5953 Section 5.4. Closing a Session
479
480 1) Increment either the snmpTlstmSessionClientCloses or the
481 snmpTlstmSessionServerCloses counter as appropriate.
482 */
483 if (t->flags & NETSNMP_TLSBASE_IS_CLIENT)
484 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONCLIENTCLOSES);
485 else
486 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONSERVERCLOSES);
487
488 /* RFC5953 Section 5.4. Closing a Session
489 2) Look up the session using the tmSessionID.
490 */
491 tlsdata = (_netsnmpTLSBaseData *) t->data;
492
493 /* RFC5953 Section 5.4. Closing a Session
494 3) If there is no open session associated with the tmSessionID, then
495 closeSession processing is completed.
496 */
497 /* Implementation notes: if we have a non-zero tlsdata then it's
498 always true */
499
500 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
501 4) Have (D)TLS close the specified connection. This SHOULD include
502 sending a close_notify TLS Alert to inform the other side that
503 session cleanup may be performed.
504 */
505
506 DEBUGMSGTL(("tlstcp", "Shutting down SSL connection\n"));
507 if (tlsdata->ssl) {
508 SSL_shutdown(tlsdata->ssl);
509 }
510
511 netsnmp_tlsbase_free_tlsdata(tlsdata);
512
513 t->data = NULL;
514 return netsnmp_socketbase_close(t);
515 }
516
517 static int
518 netsnmp_tlstcp_accept(netsnmp_transport *t)
519 {
520 BIO *accepted_bio;
521 int rc;
522 SSL_CTX *ctx;
523 SSL *ssl;
524 _netsnmpTLSBaseData *tlsdata = NULL;
525
526 DEBUGMSGTL(("tlstcp", "netsnmp_tlstcp_accept called\n"));
527
528 tlsdata = (_netsnmpTLSBaseData *) t->data;
529
530 rc = BIO_do_accept(tlsdata->accept_bio);
531
532 if (rc <= 0) {
533 snmp_log(LOG_ERR, "BIO_do_accept failed\n");
534 _openssl_log_error(rc, NULL, "BIO_do_accept");
535 /* XXX: need to close the listening connection here? */
536 return -1;
537 }
538
539 tlsdata->accepted_bio = accepted_bio = BIO_pop(tlsdata->accept_bio);
540 if (!accepted_bio) {
541 snmp_log(LOG_ERR, "Failed to pop an accepted bio off the bio stack\n");
542 /* XXX: need to close the listening connection here? */
543 return -1;
544 }
545
546 /* create the OpenSSL TLS context */
547 ctx = tlsdata->ssl_context;
548
549 /* create the server's main SSL bio */
550 ssl = tlsdata->ssl = SSL_new(ctx);
551 if (!tlsdata->ssl) {
552 snmp_log(LOG_ERR, "TLSTCP: Failed to create a SSL BIO\n");
553 BIO_free(accepted_bio);
554 tlsdata->accepted_bio = NULL;
555 return -1;
556 }
557
558 SSL_set_bio(ssl, accepted_bio, accepted_bio);
559
560 if ((rc = SSL_accept(ssl)) <= 0) {
561 snmp_log(LOG_ERR, "TLSTCP: Failed SSL_accept\n");
562 _openssl_log_error(rc, ssl, "SSL_accept");
563 SSL_shutdown(tlsdata->ssl);
564 SSL_free(tlsdata->ssl);
565 tlsdata->accepted_bio = NULL; /* freed by SSL_free */
566 tlsdata->ssl = NULL;
567 return -1;
568 }
569
570 /*
571 * currently netsnmp_tlsbase_wrapup_recv is where we check for
572 * algorithm compliance, but for tls we know the algorithms
573 * at this point, so we could bail earlier...
574 */
575 #if 0 /* moved checks to netsnmp_tlsbase_wrapup_recv */
576 netsnmp_openssl_null_checks(tlsdata->ssl, &no_auth, NULL);
577 if (no_auth != 0) { /* null/unknown authentication */
578 /* xxx-rks: snmp_increment_statistic(STAT_???); */
579 snmp_log(LOG_ERR, "tlstcp: connection with NULL authentication\n");
580 SSL_shutdown(tlsdata->ssl);
581 SSL_free(tlsdata->ssl);
582 tlsdata->accepted_bio = NULL; /* freed by SSL_free */
583 tlsdata->ssl = NULL;
584 return -1;
585 }
586 #endif
587
588 /* RFC5953 Section 5.3.2: Accepting a Session as a Server
589 A (D)TLS server should accept new session connections from any client
590 that it is able to verify the client's credentials for. This is done
591 by authenticating the client's presented certificate through a
592 certificate path validation process (e.g. [RFC5280]) or through
593 certificate fingerprint verification using fingerprints configured in
594 the snmpTlstmCertToTSNTable. Afterward the server will determine the
595 identity of the remote entity using the following procedures.
596
597 The (D)TLS server identifies the authenticated identity from the
598 (D)TLS client's principal certificate using configuration information
599 from the snmpTlstmCertToTSNTable mapping table. The (D)TLS server
600 MUST request and expect a certificate from the client and MUST NOT
601 accept SNMP messages over the (D)TLS connection until the client has
602 sent a certificate and it has been authenticated. The resulting
603 derived tmSecurityName is recorded in the tmStateReference cache as
604 tmSecurityName. The details of the lookup process are fully
605 described in the DESCRIPTION clause of the snmpTlstmCertToTSNTable
606 MIB object. If any verification fails in any way (for example
607 because of failures in cryptographic verification or because of the
608 lack of an appropriate row in the snmpTlstmCertToTSNTable) then the
609 session establishment MUST fail, and the
610 snmpTlstmSessionInvalidClientCertificates object is incremented. If
611 the session can not be opened for any reason at all, including
612 cryptographic verification failures, then the
613 snmpTlstmSessionOpenErrors counter is incremented and processing
614 stops.
615
616 Servers that wish to support multiple principals at a particular port
617 SHOULD make use of a (D)TLS extension that allows server-side
618 principal selection like the Server Name Indication extension defined
619 in Section 3.1 of [RFC4366]. Supporting this will allow, for
620 example, sending notifications to a specific principal at a given TCP
621 or UDP port.
622 */
623 /* Implementation notes:
624 - we expect fingerprints to be stored in the transport config
625 - we do not currently support mulitple principals and only offer one
626 */
627 if ((rc = netsnmp_tlsbase_verify_client_cert(ssl, tlsdata))
628 != SNMPERR_SUCCESS) {
629 /* XXX: free needed memory */
630 snmp_log(LOG_ERR, "TLSTCP: Failed checking client certificate\n");
631 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONINVALIDCLIENTCERTIFICATES);
632 SSL_shutdown(tlsdata->ssl);
633 SSL_free(tlsdata->ssl);
634 tlsdata->accepted_bio = NULL; /* freed by SSL_free */
635 tlsdata->ssl = NULL;
636 return -1;
637 }
638
639
640 /* XXX: check acceptance criteria here */
641
642 DEBUGMSGTL(("tlstcp", "accept succeeded on sock %d\n", t->sock));
643
644 /* RFC5953 Section 5.1.2 step 1, part2::
645 * If this is the first message received through this session and
646 the session does not have an assigned tlstmSessionID yet then the
647 snmpTlstmSessionAccepts counter is incremented and a
648 tlstmSessionID for the session is created. This will only happen
649 on the server side of a connection because a client would have
650 already assigned a tlstmSessionID during the openSession()
651 invocation. Implementations may have performed the procedures
652 described in Section 5.3.2 prior to this point or they may
653 perform them now, but the procedures described in Section 5.3.2
654 MUST be performed before continuing beyond this point.
655 */
656 /* We're taking option 2 and incrementing the session accepts here
657 rather than upon receiving the first packet */
658 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONACCEPTS);
659
660 /* XXX: check that it returns something so we can free stuff? */
661 return BIO_get_fd(tlsdata->accepted_bio, NULL);
662 }
663
664 static netsnmp_transport *
665 netsnmp_tlstcp_open_client(netsnmp_transport *t)
666 {
667 _netsnmpTLSBaseData *tlsdata = t->data;
668 BIO *bio;
669 SSL_CTX *ctx;
670 SSL *ssl;
671 int rc = 0;
672 _netsnmp_verify_info *verify_info;
673
674 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
675 * 1) The snmpTlstmSessionOpens counter is incremented.
676 */
677 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENS);
678
679 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
680 2) The client selects the appropriate certificate and cipher_suites
681 for the key agreement based on the tmSecurityName and the
682 tmRequestedSecurityLevel for the session. For sessions being
683 established as a result of a SNMP-TARGET-MIB based operation, the
684 certificate will potentially have been identified via the
685 snmpTlstmParamsTable mapping and the cipher_suites will have to
686 be taken from system-wide or implementation-specific
687 configuration. If no row in the snmpTlstmParamsTable exists then
688 implementations MAY choose to establish the connection using a
689 default client certificate available to the application.
690 Otherwise, the certificate and appropriate cipher_suites will
691 need to be passed to the openSession() ASI as supplemental
692 information or configured through an implementation-dependent
693 mechanism. It is also implementation-dependent and possibly
694 policy-dependent how tmRequestedSecurityLevel will be used to
695 influence the security capabilities provided by the (D)TLS
696 connection. However this is done, the security capabilities
697 provided by (D)TLS MUST be at least as high as the level of
698 security indicated by the tmRequestedSecurityLevel parameter.
699 The actual security level of the session is reported in the
700 tmStateReference cache as tmSecurityLevel. For (D)TLS to provide
701 strong authentication, each principal acting as a command
702 generator SHOULD have its own certificate.
703 */
704 /*
705 Implementation notes: we do most of this in the
706 sslctx_client_setup The transport should have been
707 f_config()ed with the proper fingerprints to use (which is
708 stored in tlsdata), or we'll use the default identity
709 fingerprint if that can be found.
710 */
711
712 /* XXX: check securityLevel and ensure no NULL fingerprints are used */
713
714 /* set up the needed SSL context */
715 tlsdata->ssl_context = ctx = sslctx_client_setup(TLS_method(), tlsdata);
716 if (!ctx) {
717 snmp_log(LOG_ERR, "failed to create TLS context\n");
718 return NULL;
719 }
720
721 #ifdef SSL_CTX_set_max_proto_version
722 SSL_CTX_set_max_proto_version(tlsdata->ssl_context, 0);
723 #endif
724
725 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
726 3) Using the destTransportDomain and destTransportAddress values,
727 the client will initiate the (D)TLS handshake protocol to
728 establish session keys for message integrity and encryption.
729 */
730 /* Implementation note:
731 The transport domain and address are pre-processed by this point
732 */
733
734 /* Create a BIO connection for it */
735 DEBUGMSGTL(("tlstcp", "connecting to tlstcp %s\n",
736 tlsdata->addr_string));
737 t->remote = strdup(tlsdata->addr_string);
738 t->remote_length = strlen(tlsdata->addr_string) + 1;
739
740 bio = BIO_new_connect(tlsdata->addr_string);
741
742 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
743 3) continued:
744 If the attempt to establish a session is unsuccessful, then
745 snmpTlstmSessionOpenErrors is incremented, an error indication is
746 returned, and processing stops.
747 */
748
749 if (NULL == bio) {
750 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
751 snmp_log(LOG_ERR, "tlstcp: failed to create bio\n");
752 _openssl_log_error(rc, NULL, "BIO creation");
753 return NULL;
754 }
755
756 /* Tell the BIO to actually do the connection */
757 rc = BIO_do_connect(bio);
758 if (rc <= 0) {
759 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
760 snmp_log(LOG_ERR, "tlstcp: failed to connect to %s\n",
761 tlsdata->addr_string);
762 _openssl_log_error(rc, NULL, "BIO_do_connect");
763 BIO_free(bio);
764 return NULL;
765 }
766
767 /* Create the SSL layer on top of the socket bio */
768 ssl = tlsdata->ssl = SSL_new(ctx);
769 if (NULL == ssl) {
770 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
771 snmp_log(LOG_ERR, "tlstcp: failed to create a SSL connection\n");
772 BIO_free(bio);
773 return NULL;
774 }
775
776 /* Bind the SSL layer to the BIO */
777 SSL_set_bio(ssl, bio, bio);
778 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
779
780 verify_info = SNMP_MALLOC_TYPEDEF(_netsnmp_verify_info);
781 if (NULL == verify_info) {
782 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
783 snmp_log(LOG_ERR, "tlstcp: failed to create a SSL connection\n");
784 SSL_shutdown(ssl);
785 BIO_free(bio);
786 return NULL;
787 }
788
789 SSL_set_ex_data(ssl, tls_get_verify_info_index(), verify_info);
790
791 /* Then have SSL do it's connection over the BIO */
792 rc = SSL_connect(ssl);
793 if (rc <= 0) {
794 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONOPENERRORS);
795 snmp_log(LOG_ERR, "tlstcp: failed to ssl_connect\n");
796 BIO_free(bio);
797 return NULL;
798 }
799
800 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
801 3) continued:
802 If the session failed to open because the presented
803 server certificate was unknown or invalid then the
804 snmpTlstmSessionUnknownServerCertificate or
805 snmpTlstmSessionInvalidServerCertificates MUST be
806 incremented and a snmpTlstmServerCertificateUnknown or
807 snmpTlstmServerInvalidCertificate notification SHOULD be
808 sent as appropriate. Reasons for server certificate
809 invalidation includes, but is not limited to,
810 cryptographic validation failures and an unexpected
811 presented certificate identity.
812 */
813
814 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
815 4) The (D)TLS client MUST then verify that the (D)TLS server's
816 presented certificate is the expected certificate. The (D)TLS
817 client MUST NOT transmit SNMP messages until the server
818 certificate has been authenticated, the client certificate has
819 been transmitted and the TLS connection has been fully
820 established.
821
822 If the connection is being established from configuration based
823 on SNMP-TARGET-MIB configuration, then the snmpTlstmAddrTable
824 DESCRIPTION clause describes how the verification is done (using
825 either a certificate fingerprint, or an identity authenticated
826 via certification path validation).
827
828 If the connection is being established for reasons other than
829 configuration found in the SNMP-TARGET-MIB then configuration and
830 procedures outside the scope of this document should be followed.
831 Configuration mechanisms SHOULD be similar in nature to those
832 defined in the snmpTlstmAddrTable to ensure consistency across
833 management configuration systems. For example, a command-line
834 tool for generating SNMP GETs might support specifying either the
835 server's certificate fingerprint or the expected host name as a
836 command line argument.
837 */
838
839 /* Implementation notes:
840 - All remote certificate fingerprints are expected to be
841 stored in the transport's config information. This is
842 true both for CLI clients and TARGET-MIB sessions.
843 - netsnmp_tlsbase_verify_server_cert implements these checks
844 */
845 if (netsnmp_tlsbase_verify_server_cert(ssl, tlsdata) != SNMPERR_SUCCESS) {
846 /* XXX: unknown vs invalid; two counters */
847 snmp_increment_statistic(STAT_TLSTM_SNMPTLSTMSESSIONUNKNOWNSERVERCERTIFICATE);
848 snmp_log(LOG_ERR, "tlstcp: failed to verify ssl certificate\n");
849 SSL_shutdown(ssl);
850 BIO_free(bio);
851 return NULL;
852 }
853
854 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
855 5) (D)TLS provides assurance that the authenticated identity has
856 been signed by a trusted configured certification authority. If
857 verification of the server's certificate fails in any way (for
858 example because of failures in cryptographic verification or the
859 presented identity did not match the expected named entity) then
860 the session establishment MUST fail, the
861 snmpTlstmSessionInvalidServerCertificates object is incremented.
862 If the session can not be opened for any reason at all, including
863 cryptographic verification failures, then the
864 snmpTlstmSessionOpenErrors counter is incremented and processing
865 stops.
866
867 */
868 /* XXX: add snmpTlstmSessionInvalidServerCertificates on
869 crypto failure */
870
871 /* RFC5953 Section 5.3.1: Establishing a Session as a Client
872 6) The TLSTM-specific session identifier (tlstmSessionID) is set in
873 the tmSessionID of the tmStateReference passed to the TLS
874 Transport Model to indicate that the session has been established
875 successfully and to point to a specific (D)TLS connection for
876 future use. The tlstmSessionID is also stored in the LCD for
877 later lookup during processing of incoming messages
878 (Section 5.1.2).
879 */
880 /* Implementation notes:
881 - the tlsdata pointer is used as our session identifier, as
882 noted in the netsnmp_tlstcp_recv() function comments.
883 */
884
885 t->sock = BIO_get_fd(bio, NULL);
886
887 return t;
888 }
889
890 static netsnmp_transport *
891 netsnmp_tlstcp_open_server(netsnmp_transport *t)
892 {
893 _netsnmpTLSBaseData *tlsdata;
894 int rc;
895
896 tlsdata = t->data;
897
898 #ifndef NETSNMP_NO_LISTEN_SUPPORT
899 /* Create the socket bio */
900 DEBUGMSGTL(("tlstcp", "listening on tlstcp port %s\n",
901 tlsdata->addr_string));
902 tlsdata->accept_bio = BIO_new_accept(tlsdata->addr_string);
903 t->local = strdup(tlsdata->addr_string);
904 t->local_length = strlen(tlsdata->addr_string) + 1;
905 if (NULL == tlsdata->accept_bio) {
906 snmp_log(LOG_ERR, "TLSTCP: Failed to create a accept BIO\n");
907 return NULL;
908 }
909
910 /* openssl requires an initial accept to bind() the socket */
911 rc = BIO_do_accept(tlsdata->accept_bio);
912 if (rc <= 0) {
913 _openssl_log_error(rc, tlsdata->ssl, "BIO_do_accept");
914 snmp_log(LOG_ERR, "TLSTCP: Failed to do first accept on the TLS accept BIO\n");
915 return NULL;
916 }
917
918 /* create the OpenSSL TLS context */
919 tlsdata->ssl_context = sslctx_server_setup(TLS_method());
920 #ifdef SSL_CTX_set_max_proto_version
921 if (tlsdata->ssl_context)
922 SSL_CTX_set_max_proto_version(tlsdata->ssl_context, 0);
923 #endif
924
925 t->sock = BIO_get_fd(tlsdata->accept_bio, NULL);
926 t->flags |= NETSNMP_TRANSPORT_FLAG_LISTEN;
927 #else /* NETSNMP_NO_LISTEN_SUPPORT */
928 return NULL;
929 #endif /* NETSNMP_NO_LISTEN_SUPPORT */
930
931 return t;
932 }
933
934 netsnmp_transport *
935 netsnmp_tlstcp_open(netsnmp_transport *t)
936 {
937 _netsnmpTLSBaseData *tlsdata;
938
939 netsnmp_assert_or_return(t != NULL, NULL);
940 netsnmp_assert_or_return(t->data != NULL, NULL);
941 netsnmp_assert_or_return(sizeof(_netsnmpTLSBaseData) == t->data_length,
942 NULL);
943
944 tlsdata = t->data;
945
946 if (tlsdata->flags & NETSNMP_TLSBASE_IS_CLIENT)
947 return netsnmp_tlstcp_open_client(t);
948 else
949 return netsnmp_tlstcp_open_server(t);
950 }
951
952 /*
953 * Create a TLS-based transport for SNMP. Local is TRUE if addr is the local
954 * address to bind to (i.e. this is a server-type session); otherwise addr is
955 * the remote address to send things to.
956 */
957
958 netsnmp_transport *
959 netsnmp_tlstcp_transport(const char *addr_string, int isserver)
960 {
961 netsnmp_transport *t = NULL;
962 _netsnmpTLSBaseData *tlsdata;
963 char *cp;
964 char buf[SPRINT_MAX_LEN];
965
966 #ifdef NETSNMP_NO_LISTEN_SUPPORT
967 if (isserver)
968 return NULL;
969 #endif /* NETSNMP_NO_LISTEN_SUPPORT */
970
971 /* allocate our transport structure */
972 t = SNMP_MALLOC_TYPEDEF(netsnmp_transport);
973 if (NULL == t) {
974 return NULL;
975 }
976
977 /* allocate our TLS specific data */
978 if (NULL == (tlsdata = netsnmp_tlsbase_allocate_tlsdata(t, isserver)))
979 return NULL;
980
981 if (!isserver)
982 t->flags |= NETSNMP_TLSBASE_IS_CLIENT;
983
984 tlsdata->addr_string = strdup(addr_string);
985
986 /* see if we can extract the remote hostname */
987 if (!isserver && tlsdata && addr_string) {
988 /* search for a : */
989 if (NULL != (cp = strrchr(addr_string, ':'))) {
990 sprintf(buf, "%.*s",
991 (int) SNMP_MIN(cp - addr_string, sizeof(buf) - 1),
992 addr_string);
993 } else {
994 /* else the entire spec is a host name only */
995 strlcpy(buf, addr_string, sizeof(buf));
996 }
997 tlsdata->their_hostname = strdup(buf);
998 }
999
1000 t->data = tlsdata;
1001 t->data_length = sizeof(_netsnmpTLSBaseData);
1002
1003 /*
1004 * Set Domain
1005 */
1006 t->domain = netsnmpTLSTCPDomain;
1007 t->domain_length = netsnmpTLSTCPDomain_len;
1008
1009 /*
1010 * 16-bit length field, 8 byte TLS header, 20 byte IPv4 header
1011 */
1012
1013 t->msgMaxSize = 0xffff - 8 - 20;
1014 t->f_recv = netsnmp_tlstcp_recv;
1015 t->f_send = netsnmp_tlstcp_send;
1016 t->f_open = netsnmp_tlstcp_open;
1017 t->f_close = netsnmp_tlstcp_close;
1018 t->f_accept = netsnmp_tlstcp_accept;
1019 t->f_copy = netsnmp_tlstcp_copy;
1020 t->f_config = netsnmp_tlsbase_config;
1021 t->f_setup_session = netsnmp_tlsbase_session_init;
1022 t->f_fmtaddr = netsnmp_tlstcp_fmtaddr;
1023 t->f_get_taddr = netsnmp_tlstcp_get_taddr;
1024
1025 t->flags |= NETSNMP_TRANSPORT_FLAG_TUNNELED | NETSNMP_TRANSPORT_FLAG_STREAM;
1026
1027 return t;
1028 }
1029
1030 netsnmp_transport *
1031 netsnmp_tlstcp_create_tstring(const char *str, int local,
1032 const char *default_target)
1033 {
1034 char buf[SPRINT_MAX_LEN];
1035
1036 if (str == NULL || *str == '\0')
1037 str = default_target + 1; /* drop the leading : */
1038 else if (!strchr(str, ':')) {
1039 /* it's either :port or :address. Try to guess which. */
1040 const char *cp;
1041 int isport = 1;
1042 for(cp = str; *cp != '\0'; cp++) {
1043 /* if ALL numbers, it must be just a port */
1044 /* if it contains anything else, assume a host or ip address */
1045 if (!isdigit(0xFF & *cp)) {
1046 isport = 0;
1047 break;
1048 }
1049 }
1050 if (isport) {
1051 /* Just :NNN can be passed to openssl */
1052 snprintf(buf, sizeof(buf)-1, "0.0.0.0:%s", str);
1053 } else {
1054 /* add the default port */
1055 snprintf(buf, sizeof(buf)-1, "%s%s", str, default_target);
1056 }
1057 str = buf;
1058 }
1059 return netsnmp_tlstcp_transport(str, local);
1060 }
1061
1062
1063 netsnmp_transport *
1064 netsnmp_tlstcp_create_ostring(const void *o, size_t o_len, int local)
1065 {
1066 char buf[SPRINT_MAX_LEN];
1067
1068 /* ensure buf is big enough */
1069 if (o_len > SPRINT_MAX_LEN - 1)
1070 return NULL;
1071
1072 memcpy(buf, o, o_len);
1073 buf[o_len] = '\0';
1074
1075 return netsnmp_tlstcp_transport(buf, local);
1076 }
1077
1078 void
1079 netsnmp_tlstcp_ctor(void)
1080 {
1081 DEBUGMSGTL(("tlstcp", "registering TLS constructor\n"));
1082
1083 /* config settings */
1084
1085 tlstcpDomain.name = netsnmpTLSTCPDomain;
1086 tlstcpDomain.name_length = netsnmpTLSTCPDomain_len;
1087 tlstcpDomain.prefix = (const char**)calloc(3, sizeof(char *));
1088 tlstcpDomain.prefix[0] = "tlstcp";
1089 tlstcpDomain.prefix[1] = "tls";
1090
1091 tlstcpDomain.f_create_from_tstring_new = netsnmp_tlstcp_create_tstring;
1092 tlstcpDomain.f_create_from_ostring = netsnmp_tlstcp_create_ostring;
1093
1094 netsnmp_tdomain_register(&tlstcpDomain);
1095 }