Debian Codegraph @

runtime/net.c

raw
1 /* net.c
2 * Implementation of network-related stuff.
3 *
4 * File begun on 2007-07-20 by RGerhards (extracted from syslogd.c)
5 * This file is under development and has not yet arrived at being fully
6 * self-contained and a real object. So far, it is mostly an excerpt
7 * of the "old" networking code without any modifications. However, it
8 * helps to have things at the right place one we go to the meat of it.
9 *
10 * Starting 2007-12-24, I have begun to shuffle more network-related code
11 * from syslogd.c to over here. I am not sure if it will stay here in the
12 * long term, but it is good to have it out of syslogd.c. Maybe this here is
13 * an interim location ;)
14 *
15 * Copyright 2007-2018 Rainer Gerhards and Adiscon GmbH.
16 *
17 * This file is part of rsyslog.
18 *
19 * Licensed under the Apache License, Version 2.0 (the "License");
20 * you may not use this file except in compliance with the License.
21 * You may obtain a copy of the License at
22 *
23 * http://www.apache.org/licenses/LICENSE-2.0
24 * -or-
25 * see COPYING.ASL20 in the source distribution
26 *
27 * Unless required by applicable law or agreed to in writing, software
28 * distributed under the License is distributed on an "AS IS" BASIS,
29 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30 * See the License for the specific language governing permissions and
31 * limitations under the License.
32 */
33 #include "config.h"
34
35 #include <stdio.h>
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <assert.h>
39 #include <errno.h>
40 #include <string.h>
41 #include <signal.h>
42 #include <ctype.h>
43 #include <netdb.h>
44 #include <fnmatch.h>
45 #include <fcntl.h>
46 #include <unistd.h>
47 #ifdef HAVE_GETIFADDRS
48 #include <ifaddrs.h>
49 #else
50 #include "compat/ifaddrs.h"
51 #endif /* HAVE_GETIFADDRS */
52 #include <sys/types.h>
53 #include <arpa/inet.h>
54
55 #include "rsyslog.h"
56 #include "syslogd-types.h"
57 #include "module-template.h"
58 #include "parse.h"
59 #include "srUtils.h"
60 #include "obj.h"
61 #include "errmsg.h"
62 #include "net.h"
63 #include "dnscache.h"
64 #include "prop.h"
65 #include "rsconf.h"
66
67 #ifdef OS_SOLARIS
68 #include <arpa/nameser_compat.h>
69 #define s6_addr32 _S6_un._S6_u32
70 typedef unsigned int u_int32_t;
71 #endif
72
73 MODULE_TYPE_LIB
74 MODULE_TYPE_NOKEEP;
75
76 /* static data */
77 DEFobjStaticHelpers;
78 DEFobjCurrIf(glbl) DEFobjCurrIf(prop)
79
80 /* support for defining allowed TCP and UDP senders. We use the same
81 * structure to implement this (a linked list), but we define two different
82 * list roots, one for UDP and one for TCP.
83 * rgerhards, 2005-09-26
84 */
85 /* All of the five below are read-only after startup */
86 struct AllowedSenders *pAllowedSenders_UDP = NULL; /* the roots of the allowed sender */
87 struct AllowedSenders *pAllowedSenders_TCP = NULL; /* lists. If NULL, all senders are ok! */
88 static struct AllowedSenders *pLastAllowedSenders_UDP = NULL; /* and now the pointers to the last */
89 static struct AllowedSenders *pLastAllowedSenders_TCP = NULL; /* element in the respective list */
90 #ifdef USE_GSSAPI
91 struct AllowedSenders *pAllowedSenders_GSS = NULL;
92 static struct AllowedSenders *pLastAllowedSenders_GSS = NULL;
93 #endif
94
95 /* ------------------------------ begin permitted peers code ------------------------------ */
96
97
98 /* sets the correct allow root pointer based on provided type
99 * rgerhards, 2008-12-01
100 */
101 static rsRetVal setAllowRoot(struct AllowedSenders **ppAllowRoot, uchar *pszType) {
102 DEFiRet;
103
104 if (!strcmp((char *)pszType, "UDP"))
105 *ppAllowRoot = pAllowedSenders_UDP;
106 else if (!strcmp((char *)pszType, "TCP"))
107 *ppAllowRoot = pAllowedSenders_TCP;
108 #ifdef USE_GSSAPI
109 else if (!strcmp((char *)pszType, "GSS"))
110 *ppAllowRoot = pAllowedSenders_GSS;
111 #endif
112 else {
113 dbgprintf("program error: invalid allowed sender ID '%s', denying...\n", pszType);
114 ABORT_FINALIZE(RS_RET_CODE_ERR); /* everything is invalid for an invalid type */
115 }
116
117 finalize_it:
118 RETiRet;
119 }
120 /* re-initializes (sets to NULL) the correct allow root pointer
121 * rgerhards, 2009-01-12
122 */
123 static rsRetVal reinitAllowRoot(uchar *pszType) {
124 DEFiRet;
125
126 if (!strcmp((char *)pszType, "UDP"))
127 pAllowedSenders_UDP = NULL;
128 else if (!strcmp((char *)pszType, "TCP"))
129 pAllowedSenders_TCP = NULL;
130 #ifdef USE_GSSAPI
131 else if (!strcmp((char *)pszType, "GSS"))
132 pAllowedSenders_GSS = NULL;
133 #endif
134 else {
135 dbgprintf("program error: invalid allowed sender ID '%s', denying...\n", pszType);
136 ABORT_FINALIZE(RS_RET_CODE_ERR); /* everything is invalid for an invalid type */
137 }
138
139 finalize_it:
140 RETiRet;
141 }
142
143
144 /* add a wildcard entry to this permitted peer. Entries are always
145 * added at the tail of the list. pszStr and lenStr identify the wildcard
146 * entry to be added. Note that the string is NOT \0 terminated, so
147 * we must rely on lenStr for when it is finished.
148 * rgerhards, 2008-05-27
149 */
150 static rsRetVal AddPermittedPeerWildcard(permittedPeers_t *pPeer, uchar *pszStr, size_t lenStr) {
151 permittedPeerWildcard_t *pNew = NULL;
152 size_t iSrc;
153 size_t iDst;
154 DEFiRet;
155
156 assert(pPeer != NULL);
157 assert(pszStr != NULL);
158
159 CHKmalloc(pNew = calloc(1, sizeof(*pNew)));
160
161 if (lenStr == 0) { /* empty domain components are permitted */
162 pNew->wildcardType = PEER_WILDCARD_EMPTY_COMPONENT;
163 FINALIZE;
164 } else {
165 /* alloc memory for the domain component. We may waste a byte or
166 * two, but that's ok.
167 */
168 CHKmalloc(pNew->pszDomainPart = malloc(lenStr + 1));
169 }
170
171 if (pszStr[0] == '*') {
172 pNew->wildcardType = PEER_WILDCARD_AT_START;
173 iSrc = 1; /* skip '*' */
174 } else {
175 iSrc = 0;
176 }
177
178 for (iDst = 0; iSrc < lenStr && pszStr[iSrc] != '*'; ++iSrc, ++iDst) {
179 pNew->pszDomainPart[iDst] = pszStr[iSrc];
180 }
181
182 if (iSrc < lenStr) {
183 if (iSrc + 1 == lenStr && pszStr[iSrc] == '*') {
184 if (pNew->wildcardType == PEER_WILDCARD_AT_START) {
185 ABORT_FINALIZE(RS_RET_INVALID_WILDCARD);
186 } else {
187 pNew->wildcardType = PEER_WILDCARD_AT_END;
188 }
189 } else {
190 /* we have an invalid wildcard, something follows the asterisk! */
191 ABORT_FINALIZE(RS_RET_INVALID_WILDCARD);
192 }
193 }
194
195 if (lenStr == 1 && pNew->wildcardType == PEER_WILDCARD_AT_START) {
196 pNew->wildcardType = PEER_WILDCARD_MATCH_ALL;
197 }
198
199 /* if we reach this point, we had a valid wildcard. We now need to
200 * properly terminate the domain component string.
201 */
202 pNew->pszDomainPart[iDst] = '\0';
203 pNew->lenDomainPart = strlen((char *)pNew->pszDomainPart);
204
205 finalize_it:
206 if (iRet != RS_RET_OK) {
207 if (pNew != NULL) {
208 if (pNew->pszDomainPart != NULL) free(pNew->pszDomainPart);
209 free(pNew);
210 }
211 } else {
212 /* enqueue the element */
213 if (pPeer->pWildcardRoot == NULL) {
214 pPeer->pWildcardRoot = pNew;
215 pPeer->pWildcardLast = pNew;
216 } else {
217 pPeer->pWildcardLast->pNext = pNew;
218 }
219 pPeer->pWildcardLast = pNew;
220 }
221
222 RETiRet;
223 }
224
225
226 /* Destruct a permitted peer's wildcard list -- rgerhards, 2008-05-27 */
227 static rsRetVal DestructPermittedPeerWildcards(permittedPeers_t *pPeer) {
228 permittedPeerWildcard_t *pCurr;
229 permittedPeerWildcard_t *pDel;
230 DEFiRet;
231
232 assert(pPeer != NULL);
233
234 for (pCurr = pPeer->pWildcardRoot; pCurr != NULL; /*EMPTY*/) {
235 pDel = pCurr;
236 pCurr = pCurr->pNext;
237 free(pDel->pszDomainPart);
238 free(pDel);
239 }
240
241 pPeer->pWildcardRoot = NULL;
242 pPeer->pWildcardLast = NULL;
243
244 RETiRet;
245 }
246
247
248 /* add a permitted peer. PermittedPeers is an interim solution until we can provide
249 * access control via enhanced RainerScript methods.
250 * Note: the provided string is handed over to this function, caller must
251 * no longer access it. -- rgerhards, 2008-05-19
252 */
253 static rsRetVal AddPermittedPeer(permittedPeers_t **ppRootPeer, uchar *pszID) {
254 permittedPeers_t *pNew = NULL;
255 DEFiRet;
256
257 assert(ppRootPeer != NULL);
258 assert(pszID != NULL);
259
260 CHKmalloc(pNew = calloc(1, sizeof(permittedPeers_t))); /* we use calloc() for consistency with "real" objects */
261 CHKmalloc(pNew->pszID = (uchar *)strdup((char *)pszID));
262
263 if (*ppRootPeer != NULL) {
264 pNew->pNext = *ppRootPeer;
265 }
266 *ppRootPeer = pNew;
267
268 finalize_it:
269 if (iRet != RS_RET_OK) {
270 if (pNew != NULL) free(pNew);
271 }
272 RETiRet;
273 }
274
275
276 /* Destruct a permitted peers list -- rgerhards, 2008-05-19 */
277 static rsRetVal DestructPermittedPeers(permittedPeers_t **ppRootPeer) {
278 permittedPeers_t *pCurr;
279 permittedPeers_t *pDel;
280 DEFiRet;
281
282 assert(ppRootPeer != NULL);
283
284 for (pCurr = *ppRootPeer; pCurr != NULL; /*EMPTY*/) {
285 pDel = pCurr;
286 pCurr = pCurr->pNext;
287 DestructPermittedPeerWildcards(pDel);
288 free(pDel->pszID);
289 free(pDel);
290 }
291
292 *ppRootPeer = NULL;
293
294 RETiRet;
295 }
296
297
298 /* Compile a wildcard. The function first checks if there is a wildcard
299 * present and compiles it only if so ;) It sets the etryType status
300 * accordingly.
301 * rgerhards, 2008-05-27
302 */
303 static rsRetVal PermittedPeerWildcardCompile(permittedPeers_t *pPeer) {
304 uchar *pC;
305 uchar *pStart;
306 DEFiRet;
307
308 assert(pPeer != NULL);
309 assert(pPeer->pszID != NULL);
310
311 /* first check if we have a wildcard */
312 for (pC = pPeer->pszID; *pC != '\0' && *pC != '*'; ++pC) /*EMPTY, just skip*/
313 ;
314
315 if (*pC == '\0') {
316 /* no wildcard found, we are mostly done */
317 pPeer->etryType = PERM_PEER_TYPE_PLAIN;
318 FINALIZE;
319 }
320
321 /* if we reach this point, the string contains wildcards. So let's
322 * compile the structure. To do so, we must parse from dot to dot
323 * and create a wildcard entry for each domain component we find.
324 * We must also flag problems if we have an asterisk in the middle
325 * of the text (it is supported at the start or end only).
326 */
327 pPeer->etryType = PERM_PEER_TYPE_WILDCARD;
328 pC = pPeer->pszID;
329 while (*pC != '\0') {
330 pStart = pC;
331 /* find end of domain component */
332 for (; *pC != '\0' && *pC != '.'; ++pC) /*EMPTY, just skip*/
333 ;
334 CHKiRet(AddPermittedPeerWildcard(pPeer, pStart, pC - pStart));
335 /* now check if we have an empty component at end of string */
336 if (*pC == '.' && *(pC + 1) == '\0') {
337 /* pStart is a dummy, it is not used if length is 0 */
338 CHKiRet(AddPermittedPeerWildcard(pPeer, pStart, 0));
339 }
340 if (*pC != '\0') ++pC;
341 }
342
343 finalize_it:
344 if (iRet != RS_RET_OK) {
345 LogError(0, iRet, "error compiling wildcard expression '%s'", pPeer->pszID);
346 }
347 RETiRet;
348 }
349
350
351 /* Do a (potential) wildcard match. The function first checks if the wildcard
352 * has already been compiled and, if not, compiles it. If the peer entry in
353 * question does NOT contain a wildcard, a simple strcmp() is done.
354 * *pbIsMatching is set to 0 if there is no match and something else otherwise.
355 * rgerhards, 2008-05-27 */
356 static rsRetVal PermittedPeerWildcardMatch(permittedPeers_t *const pPeer,
357 const uchar *pszNameToMatch,
358 int *const pbIsMatching) {
359 const permittedPeerWildcard_t *pWildcard;
360 const uchar *pC;
361 size_t iWildcard, iName; /* work indexes for backward comparisons */
362 DEFiRet;
363
364 assert(pPeer != NULL);
365 assert(pszNameToMatch != NULL);
366 assert(pbIsMatching != NULL);
367
368 if (pPeer->etryType == PERM_PEER_TYPE_UNDECIDED) {
369 PermittedPeerWildcardCompile(pPeer);
370 }
371
372 if (pPeer->etryType == PERM_PEER_TYPE_PLAIN) {
373 *pbIsMatching = !strcmp((char *)pPeer->pszID, (char *)pszNameToMatch);
374 FINALIZE;
375 }
376
377 /* we have a wildcard, so we need to extract the domain components and
378 * check then against the provided wildcards.
379 */
380 pWildcard = pPeer->pWildcardRoot;
381 pC = pszNameToMatch;
382 while (*pC != '\0') {
383 if (pWildcard == NULL) {
384 /* we have more domain components than we have wildcards --> no match */
385 *pbIsMatching = 0;
386 FINALIZE;
387 }
388 const uchar *const pStart = pC; /* start of current domain component */
389 while (*pC != '\0' && *pC != '.') {
390 ++pC;
391 }
392
393 /* got the component, now do the match */
394 switch (pWildcard->wildcardType) {
395 case PEER_WILDCARD_NONE:
396 if (pWildcard->lenDomainPart != (size_t)(pC - pStart) ||
397 strncmp((char *)pStart, (char *)pWildcard->pszDomainPart, pC - pStart)) {
398 *pbIsMatching = 0;
399 FINALIZE;
400 }
401 break;
402 case PEER_WILDCARD_AT_START:
403 /* we need to do the backwards-matching manually */
404 if (pWildcard->lenDomainPart > (size_t)(pC - pStart)) {
405 *pbIsMatching = 0;
406 FINALIZE;
407 }
408 iName = (size_t)(pC - pStart) - pWildcard->lenDomainPart;
409 iWildcard = 0;
410 while (iWildcard < pWildcard->lenDomainPart) {
411 // I give up, I see now way to remove false positive -- rgerhards, 2017-10-23
412 #ifndef __clang_analyzer__
413 if (pWildcard->pszDomainPart[iWildcard] != pStart[iName]) {
414 *pbIsMatching = 0;
415 FINALIZE;
416 }
417 #endif
418 ++iName;
419 ++iWildcard;
420 }
421 break;
422 case PEER_WILDCARD_AT_END:
423 if (pWildcard->lenDomainPart > (size_t)(pC - pStart) ||
424 strncmp((char *)pStart, (char *)pWildcard->pszDomainPart, pWildcard->lenDomainPart)) {
425 *pbIsMatching = 0;
426 FINALIZE;
427 }
428 break;
429 case PEER_WILDCARD_MATCH_ALL:
430 /* everything is OK, just continue */
431 break;
432 case PEER_WILDCARD_EMPTY_COMPONENT:
433 if (pC - pStart > 0) {
434 /* if it is not empty, it is no match... */
435 *pbIsMatching = 0;
436 FINALIZE;
437 }
438 break;
439 default:
440 // We need to satisfy compiler which does not properly handle enum
441 break;
442 }
443 pWildcard = pWildcard->pNext; /* we processed this entry */
444
445 /* skip '.' if we had it and so prepare for next iteration */
446 if (*pC == '.') ++pC;
447 }
448
449 if (pWildcard != NULL) {
450 /* we have more domain components than in the name to be
451 * checked. So this is no match.
452 */
453 *pbIsMatching = 0;
454 FINALIZE;
455 }
456
457 *pbIsMatching = 1; /* finally... it matches ;) */
458
459 finalize_it:
460 RETiRet;
461 }
462
463
464 /* ------------------------------ end permitted peers code ------------------------------ */
465
466
467 /* Code for handling allowed/disallowed senders
468 */
469 static void MaskIP6(struct in6_addr *addr, uint8_t bits) {
470 register uint8_t i;
471
472 assert(addr != NULL);
473 assert(bits <= 128);
474
475 i = bits / 32;
476 if (bits % 32) addr->s6_addr32[i++] &= htonl(0xffffffff << (32 - (bits % 32)));
477 for (; i < (sizeof addr->s6_addr32) / 4; i++) addr->s6_addr32[i] = 0;
478 }
479
480 static void MaskIP4(struct in_addr *addr, uint8_t bits) {
481 assert(addr != NULL);
482 assert(bits <= 32);
483
484 addr->s_addr &= htonl(0xffffffff << (32 - bits));
485 }
486
487 #define SIN(sa) ((struct sockaddr_in *)(void *)(sa))
488 #define SIN6(sa) ((struct sockaddr_in6 *)(void *)(sa))
489
490
491 /* This is a cancel-safe getnameinfo() version, because we learned
492 * (via drd/valgrind) that getnameinfo() seems to have some issues
493 * when being cancelled, at least if the module was dlloaded.
494 * rgerhards, 2008-09-30
495 */
496 static int mygetnameinfo(
497 const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) {
498 int iCancelStateSave;
499 int i;
500
501 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &iCancelStateSave);
502 i = getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
503 pthread_setcancelstate(iCancelStateSave, NULL);
504 return i;
505 }
506
507
508 /* This function adds an allowed sender entry to the ACL linked list.
509 * In any case, a single entry is added. If an error occurs, the
510 * function does its error reporting itself. All validity checks
511 * must already have been done by the caller.
512 * This is a helper to AddAllowedSender().
513 * rgerhards, 2007-07-17
514 */
515 static rsRetVal AddAllowedSenderEntry(struct AllowedSenders **ppRoot,
516 struct AllowedSenders **ppLast,
517 struct NetAddr *iAllow,
518 uint8_t iSignificantBits) {
519 struct AllowedSenders *pEntry = NULL;
520
521 assert(ppRoot != NULL);
522 assert(ppLast != NULL);
523 assert(iAllow != NULL);
524
525 if ((pEntry = (struct AllowedSenders *)calloc(1, sizeof(struct AllowedSenders))) == NULL) {
526 return RS_RET_OUT_OF_MEMORY; /* no options left :( */
527 }
528
529 memcpy(&(pEntry->allowedSender), iAllow, sizeof(struct NetAddr));
530 pEntry->pNext = NULL;
531 pEntry->SignificantBits = iSignificantBits;
532
533 /* enqueue */
534 if (*ppRoot == NULL) {
535 *ppRoot = pEntry;
536 } else {
537 (*ppLast)->pNext = pEntry;
538 }
539 *ppLast = pEntry;
540
541 return RS_RET_OK;
542 }
543
544 /* function to clear the allowed sender structure in cases where
545 * it must be freed (occurs most often when HUPed).
546 * rgerhards, 2008-12-02: revamped this code when we fixed the interface
547 * definition. Now an iterative algorithm is used.
548 */
549 static void clearAllowedSenders(uchar *pszType) {
550 struct AllowedSenders *pPrev;
551 struct AllowedSenders *pCurr = NULL;
552
553 if (setAllowRoot(&pCurr, pszType) != RS_RET_OK) return; /* if something went wrong, so let's leave */
554
555 while (pCurr != NULL) {
556 pPrev = pCurr;
557 pCurr = pCurr->pNext;
558 /* now delete the entry we are right now processing */
559 if (F_ISSET(pPrev->allowedSender.flags, ADDR_NAME))
560 free(pPrev->allowedSender.addr.HostWildcard);
561 else
562 free(pPrev->allowedSender.addr.NetAddr);
563 free(pPrev);
564 }
565
566 /* indicate root pointer is de-init (was forgotten previously, resulting in
567 * all kinds of interesting things) -- rgerhards, 2009-01-12
568 */
569 reinitAllowRoot(pszType);
570 }
571
572
573 /* function to add an allowed sender to the allowed sender list. The
574 * root of the list is caller-provided, so it can be used for all
575 * supported lists. The caller must provide a pointer to the root,
576 * as it eventually needs to be updated. Also, a pointer to the
577 * pointer to the last element must be provided (to speed up adding
578 * list elements).
579 * rgerhards, 2005-09-26
580 * If a hostname is given there are possible multiple entries
581 * added (all addresses from that host).
582 */
583 static rsRetVal AddAllowedSender(struct AllowedSenders **ppRoot,
584 struct AllowedSenders **ppLast,
585 struct NetAddr *iAllow,
586 uint8_t iSignificantBits) {
587 struct addrinfo *restmp = NULL;
588 DEFiRet;
589
590 assert(ppRoot != NULL);
591 assert(ppLast != NULL);
592 assert(iAllow != NULL);
593
594 if (!F_ISSET(iAllow->flags, ADDR_NAME)) {
595 if (iSignificantBits == 0)
596 /* we handle this seperatly just to provide a better
597 * error message.
598 */
599 LogError(0, NO_ERRCODE,
600 "You can not specify 0 bits of the netmask, this would "
601 "match ALL systems. If you really intend to do that, "
602 "remove all $AllowedSender directives.");
603
604 switch (iAllow->addr.NetAddr->sa_family) {
605 case AF_INET:
606 if ((iSignificantBits < 1) || (iSignificantBits > 32)) {
607 LogError(0, NO_ERRCODE, "Invalid number of bits (%d) in IPv4 address - adjusted to 32",
608 (int)iSignificantBits);
609 iSignificantBits = 32;
610 }
611
612 MaskIP4(&(SIN(iAllow->addr.NetAddr)->sin_addr), iSignificantBits);
613 break;
614 case AF_INET6:
615 if ((iSignificantBits < 1) || (iSignificantBits > 128)) {
616 LogError(0, NO_ERRCODE, "Invalid number of bits (%d) in IPv6 address - adjusted to 128",
617 iSignificantBits);
618 iSignificantBits = 128;
619 }
620
621 MaskIP6(&(SIN6(iAllow->addr.NetAddr)->sin6_addr), iSignificantBits);
622 break;
623 default:
624 /* rgerhards, 2007-07-16: We have an internal program error in this
625 * case. However, there is not much we can do against it right now. Of
626 * course, we could abort, but that would probably cause more harm
627 * than good. So we continue to run. We simply do not add this line - the
628 * worst thing that happens is that one host will not be allowed to
629 * log.
630 */
631 LogError(0, NO_ERRCODE, "Internal error caused AllowedSender to be ignored, AF = %d",
632 iAllow->addr.NetAddr->sa_family);
633 ABORT_FINALIZE(RS_RET_ERR);
634 }
635 /* OK, entry constructed, now lets add it to the ACL list */
636 iRet = AddAllowedSenderEntry(ppRoot, ppLast, iAllow, iSignificantBits);
637 } else {
638 /* we need to process a hostname ACL */
639 if (glbl.GetDisableDNS(loadConf)) {
640 LogError(0, NO_ERRCODE, "Ignoring hostname based ACLs because DNS is disabled.");
641 ABORT_FINALIZE(RS_RET_OK);
642 }
643
644 if (!strchr(iAllow->addr.HostWildcard, '*') && !strchr(iAllow->addr.HostWildcard, '?') &&
645 loadConf->globals.ACLDontResolve == 0) {
646 /* single host - in this case, we pull its IP addresses from DNS
647 * and add IP-based ACLs.
648 */
649 struct addrinfo hints, *res;
650 struct NetAddr allowIP;
651
652 memset(&hints, 0, sizeof(struct addrinfo));
653 hints.ai_family = AF_UNSPEC;
654 hints.ai_socktype = SOCK_DGRAM;
655 #ifdef AI_ADDRCONFIG /* seems not to be present on all systems */
656 hints.ai_flags = AI_ADDRCONFIG;
657 #endif
658
659 if (getaddrinfo(iAllow->addr.HostWildcard, NULL, &hints, &res) != 0) {
660 LogError(0, NO_ERRCODE, "DNS error: Can't resolve \"%s\"", iAllow->addr.HostWildcard);
661
662 if (loadConf->globals.ACLAddHostnameOnFail) {
663 LogError(0, NO_ERRCODE,
664 "Adding hostname \"%s\" to ACL as a wildcard "
665 "entry.",
666 iAllow->addr.HostWildcard);
667 iRet = AddAllowedSenderEntry(ppRoot, ppLast, iAllow, iSignificantBits);
668 FINALIZE;
669 } else {
670 LogError(0, NO_ERRCODE, "Hostname \"%s\" WON\'T be added to ACL.", iAllow->addr.HostWildcard);
671 ABORT_FINALIZE(RS_RET_NOENTRY);
672 }
673 }
674
675 restmp = res;
676 for (; res != NULL; res = res->ai_next) {
677 switch (res->ai_family) {
678 case AF_INET: /* add IPv4 */
679 iSignificantBits = 32;
680 allowIP.flags = 0;
681 if ((allowIP.addr.NetAddr = malloc(res->ai_addrlen)) == NULL) {
682 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
683 }
684 memcpy(allowIP.addr.NetAddr, res->ai_addr, res->ai_addrlen);
685
686 if ((iRet = AddAllowedSenderEntry(ppRoot, ppLast, &allowIP, iSignificantBits)) != RS_RET_OK) {
687 free(allowIP.addr.NetAddr);
688 FINALIZE;
689 }
690 break;
691 case AF_INET6: /* IPv6 - but need to check if it is a v6-mapped IPv4 */
692 if (IN6_IS_ADDR_V4MAPPED(&SIN6(res->ai_addr)->sin6_addr)) {
693 /* extract & add IPv4 */
694
695 iSignificantBits = 32;
696 allowIP.flags = 0;
697 if ((allowIP.addr.NetAddr = (struct sockaddr *)malloc(sizeof(struct sockaddr))) == NULL) {
698 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
699 }
700 SIN(allowIP.addr.NetAddr)->sin_family = AF_INET;
701 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
702 SIN(allowIP.addr.NetAddr)->sin_len = sizeof(struct sockaddr_in);
703 #endif
704 SIN(allowIP.addr.NetAddr)->sin_port = 0;
705 memcpy(&(SIN(allowIP.addr.NetAddr)->sin_addr.s_addr),
706 &(SIN6(res->ai_addr)->sin6_addr.s6_addr32[3]), sizeof(in_addr_t));
707
708 if ((iRet = AddAllowedSenderEntry(ppRoot, ppLast, &allowIP, iSignificantBits)) !=
709 RS_RET_OK) {
710 free(allowIP.addr.NetAddr);
711 FINALIZE;
712 }
713 } else {
714 /* finally add IPv6 */
715
716 iSignificantBits = 128;
717 allowIP.flags = 0;
718 if ((allowIP.addr.NetAddr = malloc(res->ai_addrlen)) == NULL) {
719 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
720 }
721 memcpy(allowIP.addr.NetAddr, res->ai_addr, res->ai_addrlen);
722
723 if ((iRet = AddAllowedSenderEntry(ppRoot, ppLast, &allowIP, iSignificantBits)) !=
724 RS_RET_OK) {
725 free(allowIP.addr.NetAddr);
726 FINALIZE;
727 }
728 }
729 break;
730 default:
731 // We need to satisfy compiler which does not properly handle enum
732 break;
733 }
734 }
735 } else {
736 /* wildcards in hostname - we need to add a text-based ACL.
737 * For this, we already have everything ready and just need
738 * to pass it along...
739 */
740 iRet = AddAllowedSenderEntry(ppRoot, ppLast, iAllow, iSignificantBits);
741 }
742 }
743
744 finalize_it:
745 if (restmp != NULL) {
746 freeaddrinfo(restmp);
747 }
748 RETiRet;
749 }
750
751
752 static const char *SENDER_TEXT[4] = {"", "UDP", "TCP", "GSS"};
753 /* Print an allowed sender list. The caller must tell us which one.
754 * iListToPrint = 1 means UDP, 2 means TCP
755 * rgerhards, 2005-09-27
756 */
757 static void PrintAllowedSenders(int iListToPrint) {
758 struct AllowedSenders *pSender;
759 uchar szIP[64];
760 #ifdef USE_GSSAPI
761 #define iListToPrint_MAX 3
762 #else
763 #define iListToPrint_MAX 2
764 #endif
765 assert((iListToPrint > 0) && (iListToPrint <= iListToPrint_MAX));
766
767 dbgprintf("Allowed %s Senders:\n", SENDER_TEXT[iListToPrint]);
768
769 pSender = (iListToPrint == 1) ? pAllowedSenders_UDP :
770 #ifdef USE_GSSAPI
771 (iListToPrint == 3) ? pAllowedSenders_GSS
772 :
773 #endif
774 pAllowedSenders_TCP;
775 if (pSender == NULL) {
776 dbgprintf("\tNo restrictions set.\n");
777 } else {
778 while (pSender != NULL) {
779 if (F_ISSET(pSender->allowedSender.flags, ADDR_NAME))
780 dbgprintf("\t%s\n", pSender->allowedSender.addr.HostWildcard);
781 else {
782 if (mygetnameinfo(pSender->allowedSender.addr.NetAddr, SALEN(pSender->allowedSender.addr.NetAddr),
783 (char *)szIP, 64, NULL, 0, NI_NUMERICHOST) == 0) {
784 dbgprintf("\t%s/%u\n", szIP, pSender->SignificantBits);
785 } else {
786 /* getnameinfo() failed - but as this is only a
787 * debug function, we simply spit out an error and do
788 * not care much about it.
789 */
790 dbgprintf(
791 "\tERROR in getnameinfo() - something may be wrong "
792 "- ignored for now\n");
793 }
794 }
795 pSender = pSender->pNext;
796 }
797 }
798 }
799
800
801 /* parse an allowed sender config line and add the allowed senders
802 * (if the line is correct).
803 * rgerhards, 2005-09-27
804 */
805 static rsRetVal addAllowedSenderLine(char *pName, uchar **ppRestOfConfLine) {
806 struct AllowedSenders **ppRoot;
807 struct AllowedSenders **ppLast;
808 rsParsObj *pPars;
809 rsRetVal iRet;
810 struct NetAddr *uIP = NULL;
811 int iBits;
812
813 assert(pName != NULL);
814 assert(ppRestOfConfLine != NULL);
815 assert(*ppRestOfConfLine != NULL);
816
817 if (!strcasecmp(pName, "udp")) {
818 ppRoot = &pAllowedSenders_UDP;
819 ppLast = &pLastAllowedSenders_UDP;
820 } else if (!strcasecmp(pName, "tcp")) {
821 ppRoot = &pAllowedSenders_TCP;
822 ppLast = &pLastAllowedSenders_TCP;
823 #ifdef USE_GSSAPI
824 } else if (!strcasecmp(pName, "gss")) {
825 ppRoot = &pAllowedSenders_GSS;
826 ppLast = &pLastAllowedSenders_GSS;
827 #endif
828 } else {
829 LogError(0, RS_RET_ERR,
830 "Invalid protocol '%s' in allowed sender "
831 "list, line ignored",
832 pName);
833 return RS_RET_ERR;
834 }
835
836 /* OK, we now know the protocol and have valid list pointers.
837 * So let's process the entries. We are using the parse class
838 * for this.
839 */
840 /* create parser object starting with line string without leading colon */
841 if ((iRet = rsParsConstructFromSz(&pPars, (uchar *)*ppRestOfConfLine) != RS_RET_OK)) {
842 LogError(0, iRet, "Error %d constructing parser object - ignoring allowed sender list", iRet);
843 return (iRet);
844 }
845
846 while (!parsIsAtEndOfParseString(pPars)) {
847 if (parsPeekAtCharAtParsPtr(pPars) == '#') break; /* a comment-sign stops processing of line */
848 /* now parse a single IP address */
849 if ((iRet = parsAddrWithBits(pPars, &uIP, &iBits)) != RS_RET_OK) {
850 LogError(0, iRet,
851 "Error %d parsing address in allowed sender"
852 "list - ignoring.",
853 iRet);
854 rsParsDestruct(pPars);
855 return (iRet);
856 }
857 if ((iRet = AddAllowedSender(ppRoot, ppLast, uIP, iBits)) != RS_RET_OK) {
858 if (iRet == RS_RET_NOENTRY) {
859 LogError(0, iRet,
860 "Error %d adding allowed sender entry "
861 "- ignoring.",
862 iRet);
863 } else {
864 LogError(0, iRet,
865 "Error %d adding allowed sender entry "
866 "- terminating, nothing more will be added.",
867 iRet);
868 rsParsDestruct(pPars);
869 free(uIP);
870 return (iRet);
871 }
872 }
873 free(uIP); /* copy stored in AllowedSenders list */
874 }
875
876 /* cleanup */
877 *ppRestOfConfLine += parsGetCurrentPosition(pPars);
878 return rsParsDestruct(pPars);
879 }
880
881
882 /* compares a host to an allowed sender list entry. Handles all subleties
883 * including IPv4/v6 as well as domain name wildcards.
884 * This is a helper to isAllowedSender.
885 * Returns 0 if they do not match, 1 if they match and 2 if a DNS name would have been required.
886 * contributed 2007-07-16 by [email protected]
887 */
888 static int MaskCmp(struct NetAddr *pAllow, uint8_t bits, struct sockaddr *pFrom, const char *pszFromHost, int bChkDNS) {
889 assert(pAllow != NULL);
890 assert(pFrom != NULL);
891
892 if (F_ISSET(pAllow->flags, ADDR_NAME)) {
893 if (bChkDNS == 0) return 2;
894 dbgprintf("MaskCmp: host=\"%s\"; pattern=\"%s\"\n", pszFromHost, pAllow->addr.HostWildcard);
895
896 #if !defined(FNM_CASEFOLD)
897 /* TODO: I don't know if that then works, seen on HP UX, what I have not in lab... ;) */
898 return (fnmatch(pAllow->addr.HostWildcard, pszFromHost, FNM_NOESCAPE) == 0);
899 #else
900 return (fnmatch(pAllow->addr.HostWildcard, pszFromHost, FNM_NOESCAPE | FNM_CASEFOLD) == 0);
901 #endif
902 } else { /* We need to compare an IP address */
903 switch (pFrom->sa_family) {
904 case AF_INET:
905 if (AF_INET == pAllow->addr.NetAddr->sa_family)
906 return ((SIN(pFrom)->sin_addr.s_addr & htonl(0xffffffff << (32 - bits))) ==
907 SIN(pAllow->addr.NetAddr)->sin_addr.s_addr);
908 else
909 return 0;
910 break;
911 case AF_INET6:
912 switch (pAllow->addr.NetAddr->sa_family) {
913 case AF_INET6: {
914 struct in6_addr ip, net;
915 register uint8_t i;
916
917 memcpy(&ip, &(SIN6(pFrom))->sin6_addr, sizeof(struct in6_addr));
918 memcpy(&net, &(SIN6(pAllow->addr.NetAddr))->sin6_addr, sizeof(struct in6_addr));
919
920 i = bits / 32;
921 if (bits % 32) ip.s6_addr32[i++] &= htonl(0xffffffff << (32 - (bits % 32)));
922 for (; i < (sizeof ip.s6_addr32) / 4; i++) ip.s6_addr32[i] = 0;
923
924 return (memcmp(ip.s6_addr, net.s6_addr, sizeof ip.s6_addr) == 0 &&
925 (SIN6(pAllow->addr.NetAddr)->sin6_scope_id != 0
926 ? SIN6(pFrom)->sin6_scope_id == SIN6(pAllow->addr.NetAddr)->sin6_scope_id
927 : 1));
928 }
929 case AF_INET: {
930 struct in6_addr *ip6 = &(SIN6(pFrom))->sin6_addr;
931 struct in_addr *net = &(SIN(pAllow->addr.NetAddr))->sin_addr;
932
933 if ((ip6->s6_addr32[3] & (u_int32_t)htonl((0xffffffff << (32 - bits)))) == net->s_addr &&
934 #if BYTE_ORDER == LITTLE_ENDIAN
935 (ip6->s6_addr32[2] == (u_int32_t)0xffff0000) &&
936 #else
937 (ip6->s6_addr32[2] == (u_int32_t)0x0000ffff) &&
938 #endif
939 (ip6->s6_addr32[1] == 0) && (ip6->s6_addr32[0] == 0))
940 return 1;
941 else
942 return 0;
943 }
944 default:
945 /* Unsupported AF */
946 return 0;
947 }
948 /* fallthrough */
949 default:
950 /* Unsupported AF */
951 return 0;
952 }
953 }
954 }
955
956
957 /* check if a sender is allowed. The root of the the allowed sender.
958 * list must be proveded by the caller. As such, this function can be
959 * used to check both UDP and TCP allowed sender lists.
960 * returns 1, if the sender is allowed, 0 if not and 2 if we could not
961 * obtain a result because we would need a dns name, which we don't have
962 * (2 was added rgerhards, 2009-11-16).
963 * rgerhards, 2005-09-26
964 */
965 static int isAllowedSender2(uchar *pszType, struct sockaddr *pFrom, const char *pszFromHost, int bChkDNS) {
966 struct AllowedSenders *pAllow;
967 struct AllowedSenders *pAllowRoot = NULL;
968 int bNeededDNS = 0; /* partial check because we could not resolve DNS? */
969 int ret;
970
971 assert(pFrom != NULL);
972
973 if (setAllowRoot(&pAllowRoot, pszType) != RS_RET_OK)
974 return 0; /* if something went wrong, we deny access - that's the better choice... */
975
976 if (pAllowRoot == NULL) return 1; /* checking disabled, everything is valid! */
977
978 /* now we loop through the list of allowed senders. As soon as
979 * we find a match, we return back (indicating allowed). We loop
980 * until we are out of allowed senders. If so, we fall through the
981 * loop and the function's terminal return statement will indicate
982 * that the sender is disallowed.
983 */
984 for (pAllow = pAllowRoot; pAllow != NULL; pAllow = pAllow->pNext) {
985 ret = MaskCmp(&(pAllow->allowedSender), pAllow->SignificantBits, pFrom, pszFromHost, bChkDNS);
986 if (ret == 1)
987 return 1;
988 else if (ret == 2)
989 bNeededDNS = 2;
990 }
991 return bNeededDNS;
992 }
993
994
995 /* legacy API, not to be used any longer */
996 static int isAllowedSender(uchar *pszType, struct sockaddr *pFrom, const char *pszFromHost) {
997 return isAllowedSender2(pszType, pFrom, pszFromHost, 1);
998 }
999
1000
1001 /* The following #ifdef sequence is a small compatibility
1002 * layer. It tries to work around the different availality
1003 * levels of SO_BSDCOMPAT on linuxes...
1004 * I borrowed this code from
1005 * http://www.erlang.org/ml-archive/erlang-questions/200307/msg00037.html
1006 * It still needs to be a bit better adapted to rsyslog.
1007 * rgerhards 2005-09-19
1008 */
1009 #include <sys/utsname.h>
1010 static int should_use_so_bsdcompat(void) {
1011 #ifndef OS_BSD
1012 static int use_so_bsdcompat = -1;
1013
1014 /* we guard the init code just by an atomic fetch to local variable. This still
1015 * is racy, but the worst that can happen is that we do the very same init twice.
1016 * This does hurt less than locking a mutex.
1017 */
1018 const int local_use_so_bsdcompat = PREFER_FETCH_32BIT(use_so_bsdcompat);
1019 if (local_use_so_bsdcompat == -1) {
1020 struct utsname myutsname;
1021 unsigned int version, patchlevel;
1022
1023 if (uname(&myutsname) < 0) {
1024 char errStr[1024];
1025 dbgprintf("uname: %s\r\n", rs_strerror_r(errno, errStr, sizeof(errStr)));
1026 PREFER_STORE_1_TO_INT(&use_so_bsdcompat);
1027 FINALIZE;
1028 }
1029 /* Format is <version>.<patchlevel>.<sublevel><extraversion>
1030 * where the first three are unsigned integers and the last
1031 * is an arbitrary string. We only care about the first two. */
1032 if (sscanf(myutsname.release, "%u.%u", &version, &patchlevel) != 2) {
1033 dbgprintf("uname: unexpected release '%s'\r\n", myutsname.release);
1034 PREFER_STORE_1_TO_INT(&use_so_bsdcompat);
1035 FINALIZE;
1036 }
1037 /* SO_BSCOMPAT is deprecated and triggers warnings in 2.5
1038 * kernels. It is a no-op in 2.4 but not in 2.2 kernels. */
1039 if (version > 2 || (version == 2 && patchlevel >= 5)) {
1040 PREFER_STORE_0_TO_INT(&use_so_bsdcompat);
1041 FINALIZE;
1042 }
1043 }
1044 finalize_it:
1045 return PREFER_FETCH_32BIT(use_so_bsdcompat);
1046 #else /* #ifndef OS_BSD */
1047 return 1;
1048 #endif /* #ifndef OS_BSD */
1049 }
1050 #ifndef SO_BSDCOMPAT
1051 /* this shall prevent compiler errors due to undfined name */
1052 #define SO_BSDCOMPAT 0
1053 #endif
1054
1055
1056 /* print out which socket we are listening on. This is only
1057 * a debug aid. rgerhards, 2007-07-02
1058 */
1059 static void debugListenInfo(int fd, char *type) {
1060 const char *szFamily;
1061 int port;
1062 union {
1063 struct sockaddr_storage sa;
1064 struct sockaddr_in sa4;
1065 struct sockaddr_in6 sa6;
1066 } sockaddr;
1067 socklen_t saLen = sizeof(sockaddr.sa);
1068
1069 if (getsockname(fd, (struct sockaddr *)&sockaddr.sa, &saLen) == 0) {
1070 switch (sockaddr.sa.ss_family) {
1071 case PF_INET:
1072 szFamily = "IPv4";
1073 port = ntohs(sockaddr.sa4.sin_port);
1074 break;
1075 case PF_INET6:
1076 szFamily = "IPv6";
1077 port = ntohs(sockaddr.sa6.sin6_port);
1078 break;
1079 default:
1080 szFamily = "other";
1081 port = -1;
1082 break;
1083 }
1084 dbgprintf("Listening on %s syslogd socket %d (%s/port %d).\n", type, fd, szFamily, port);
1085 return;
1086 }
1087
1088 /* we can not obtain peer info. We are just providing
1089 * debug info, so this is no reason to break the program
1090 * or do any serious error reporting.
1091 */
1092 dbgprintf("Listening on syslogd socket %d - could not obtain peer info.\n", fd);
1093 }
1094
1095
1096 /* Return a printable representation of a host addresses. If
1097 * a parameter is NULL, it is not set. rgerhards, 2013-01-22
1098 */
1099 static rsRetVal cvthname(struct sockaddr_storage *f, prop_t **localName, prop_t **fqdn, prop_t **ip) {
1100 DEFiRet;
1101 assert(f != NULL);
1102 iRet = dnscacheLookup(f, fqdn, NULL, localName, ip);
1103 RETiRet;
1104 }
1105
1106
1107 /* get the name of the local host. A pointer to a character pointer is passed
1108 * in, which on exit points to the local hostname. This buffer is dynamically
1109 * allocated and must be free()ed by the caller. If the functions returns an
1110 * error, the pointer is NULL.
1111 * This function always tries to return a FQDN, even so be quering DNS. So it
1112 * is safe to assume for the caller that when the function does not return
1113 * a FQDN, it simply is not available. The domain part of that string is
1114 * normalized to lower case. The hostname is kept in mixed case for historic
1115 * reasons.
1116 */
1117 #define EMPTY_HOSTNAME_REPLACEMENT "localhost-empty-hostname"
1118 static rsRetVal getLocalHostname(rsconf_t *const pConf, uchar **ppName) {
1119 DEFiRet;
1120 char hnbuf[8192];
1121 uchar *fqdn = NULL;
1122 int empty_hostname = 1;
1123
1124 if (gethostname(hnbuf, sizeof(hnbuf)) != 0) {
1125 RS_COPY_LITERAL(hnbuf, EMPTY_HOSTNAME_REPLACEMENT);
1126 } else {
1127 /* now guard against empty hostname
1128 * see https://github.com/rsyslog/rsyslog/issues/1040
1129 */
1130 if (hnbuf[0] == '\0') {
1131 RS_COPY_LITERAL(hnbuf, EMPTY_HOSTNAME_REPLACEMENT);
1132 } else {
1133 empty_hostname = 0;
1134 hnbuf[sizeof(hnbuf) - 1] = '\0'; /* be on the safe side... */
1135 }
1136 }
1137
1138 char *dot = strstr(hnbuf, ".");
1139 struct addrinfo *res = NULL;
1140 if (!empty_hostname && dot == NULL && pConf != NULL && !glbl.GetDisableDNS(pConf)) {
1141 /* we need to (try) to find the real name via resolver */
1142 struct addrinfo flags;
1143 memset(&flags, 0, sizeof(flags));
1144 flags.ai_flags = AI_CANONNAME;
1145 int error = getaddrinfo((char *)hnbuf, NULL, &flags, &res);
1146 if (error != 0 && error != EAI_NONAME && error != EAI_AGAIN && error != EAI_FAIL) {
1147 /* If we get one of errors above, network is probably
1148 * not working yet, so we fall back to local hostname below
1149 */
1150 LogError(0, RS_RET_ERR,
1151 "getaddrinfo failed obtaining local "
1152 "hostname - using '%s' instead; error: %s",
1153 hnbuf, gai_strerror(error));
1154 }
1155 if (res != NULL) {
1156 /* When AI_CANONNAME is set first member of res linked-list */
1157 /* should contain what we need */
1158 if (res->ai_canonname != NULL && res->ai_canonname[0] != '\0') {
1159 CHKmalloc(fqdn = (uchar *)strdup(res->ai_canonname));
1160 dot = strstr((char *)fqdn, ".");
1161 }
1162 }
1163 }
1164
1165 if (fqdn == NULL) {
1166 /* already was FQDN or we could not obtain a better one */
1167 CHKmalloc(fqdn = (uchar *)strdup(hnbuf));
1168 }
1169
1170 if (dot != NULL)
1171 for (char *p = dot + 1; *p; ++p) *p = tolower(*p);
1172
1173 *ppName = fqdn;
1174 finalize_it:
1175 if (res != NULL) {
1176 freeaddrinfo(res);
1177 }
1178 RETiRet;
1179 }
1180
1181
1182 /* closes the UDP listen sockets (if they exist) and frees
1183 * all dynamically assigned memory.
1184 */
1185 static void closeUDPListenSockets(int *pSockArr) {
1186 register int i;
1187
1188 assert(pSockArr != NULL);
1189 if (pSockArr != NULL) {
1190 for (i = 0; i < *pSockArr; i++) close(pSockArr[i + 1]);
1191 free(pSockArr);
1192 }
1193 }
1194
1195
1196 /* create a single UDP socket and bail out if an error occurs.
1197 * This is called from a loop inside create_udp_socket which
1198 * iterates through potentially multiple sockets. NOT to be
1199 * used elsewhere.
1200 */
1201 static rsRetVal ATTR_NONNULL(1, 2) create_single_udp_socket(int *const s, /* socket */
1202 struct addrinfo *const r,
1203 const uchar *const hostname,
1204 const int bIsServer,
1205 const int rcvbuf,
1206 const int sndbuf,
1207 const int ipfreebind,
1208 const char *const device) {
1209 const int on = 1;
1210 int sockflags;
1211 int actrcvbuf;
1212 int actsndbuf;
1213 socklen_t optlen;
1214 char errStr[1024];
1215 DEFiRet;
1216
1217 assert(r != NULL); // does NOT work with -O2 or higher due to ATTR_NONNULL!
1218 assert(s != NULL);
1219
1220 #if defined(_AIX)
1221 /* AIXPORT : socktype will be SOCK_DGRAM, as set in hints before */
1222 *s = socket(r->ai_family, SOCK_DGRAM, r->ai_protocol);
1223 #else
1224 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
1225 #endif
1226 if (*s < 0) {
1227 if (!(r->ai_family == PF_INET6 && errno == EAFNOSUPPORT)) {
1228 LogError(errno, NO_ERRCODE, "create_udp_socket(), socket");
1229 /* it is debateble if PF_INET with EAFNOSUPPORT should
1230 * also be ignored...
1231 */
1232 }
1233 ABORT_FINALIZE(RS_RET_ERR);
1234 }
1235
1236 #ifdef IPV6_V6ONLY
1237 if (r->ai_family == AF_INET6) {
1238 int ion = 1;
1239 if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&ion, sizeof(ion)) < 0) {
1240 LogError(errno, RS_RET_ERR, "error creating UDP socket - setsockopt");
1241 ABORT_FINALIZE(RS_RET_ERR);
1242 }
1243 }
1244 #endif
1245
1246 if (device) {
1247 #if defined(SO_BINDTODEVICE)
1248 if (setsockopt(*s, SOL_SOCKET, SO_BINDTODEVICE, device, strlen(device) + 1) < 0)
1249 #endif
1250 {
1251 LogError(errno, RS_RET_ERR, "create UDP socket bound to device failed");
1252 ABORT_FINALIZE(RS_RET_ERR);
1253 }
1254 }
1255
1256 if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) {
1257 LogError(errno, RS_RET_ERR, "create UDP socket failed to set REUSEADDR");
1258 ABORT_FINALIZE(RS_RET_ERR);
1259 }
1260
1261 /* We need to enable BSD compatibility. Otherwise an attacker
1262 * could flood our log files by sending us tons of ICMP errors.
1263 */
1264 /* AIXPORT : SO_BSDCOMPAT socket option is deprecated, and its usage
1265 * has been discontinued on most unixes, AIX does not support this option,
1266 * hence avoid the call.
1267 */
1268 #if !defined(OS_BSD) && !defined(__hpux) && !defined(_AIX)
1269 if (should_use_so_bsdcompat()) {
1270 if (setsockopt(*s, SOL_SOCKET, SO_BSDCOMPAT, (char *)&on, sizeof(on)) < 0) {
1271 LogError(errno, RS_RET_ERR, "create UDP socket failed to set BSDCOMPAT");
1272 ABORT_FINALIZE(RS_RET_ERR);
1273 }
1274 }
1275 #endif
1276 if (bIsServer) {
1277 DBGPRINTF("net.c: trying to set server socket %d to non-blocking mode\n", *s);
1278 if ((sockflags = fcntl(*s, F_GETFL)) != -1) {
1279 sockflags |= O_NONBLOCK;
1280 /* SETFL could fail too, so get it caught by the subsequent
1281 * error check.
1282 */
1283 sockflags = fcntl(*s, F_SETFL, sockflags);
1284 }
1285 if (sockflags == -1) {
1286 LogError(errno, RS_RET_ERR, "net.c: socket %d fcntl(O_NONBLOCK)", *s);
1287 ABORT_FINALIZE(RS_RET_ERR);
1288 }
1289 }
1290
1291 if (sndbuf != 0) {
1292 #if defined(SO_SNDBUFFORCE)
1293 if (setsockopt(*s, SOL_SOCKET, SO_SNDBUFFORCE, &sndbuf, sizeof(sndbuf)) < 0)
1294 #endif
1295 {
1296 /* if we fail, try to do it the regular way. Experiments show that at
1297 * least some platforms do not return an error here, but silently set
1298 * it to the max permitted value. So we do our error check a bit
1299 * differently by querying the size below.
1300 */
1301 if (setsockopt(*s, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf)) != 0) {
1302 /* keep Coverity happy */
1303 DBGPRINTF(
1304 "setsockopt in %s:%d failed - this is expected and "
1305 "handled at later stages\n",
1306 __FILE__, __LINE__);
1307 }
1308 }
1309 /* report socket buffer sizes */
1310 optlen = sizeof(actsndbuf);
1311 if (getsockopt(*s, SOL_SOCKET, SO_SNDBUF, &actsndbuf, &optlen) == 0) {
1312 LogMsg(0, NO_ERRCODE, LOG_INFO, "socket %d, actual os socket sndbuf size is %d", *s, actsndbuf);
1313 if (sndbuf != 0 && actsndbuf / 2 != sndbuf) {
1314 LogError(errno, NO_ERRCODE,
1315 "could not set os socket sndbuf size %d for socket %d, "
1316 "value now is %d",
1317 sndbuf, *s, actsndbuf / 2);
1318 }
1319 } else {
1320 DBGPRINTF("could not obtain os socket rcvbuf size for socket %d: %s\n", *s,
1321 rs_strerror_r(errno, errStr, sizeof(errStr)));
1322 }
1323 }
1324
1325 if (rcvbuf != 0) {
1326 #if defined(SO_RCVBUFFORCE)
1327 if (setsockopt(*s, SOL_SOCKET, SO_RCVBUFFORCE, &rcvbuf, sizeof(rcvbuf)) < 0)
1328 #endif
1329 {
1330 /* if we fail, try to do it the regular way. Experiments show that at
1331 * least some platforms do not return an error here, but silently set
1332 * it to the max permitted value. So we do our error check a bit
1333 * differently by querying the size below.
1334 */
1335 if (setsockopt(*s, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) != 0) {
1336 /* keep Coverity happy */
1337 DBGPRINTF(
1338 "setsockopt in %s:%d failed - this is expected and "
1339 "handled at later stages\n",
1340 __FILE__, __LINE__);
1341 }
1342 }
1343 optlen = sizeof(actrcvbuf);
1344 if (getsockopt(*s, SOL_SOCKET, SO_RCVBUF, &actrcvbuf, &optlen) == 0) {
1345 LogMsg(0, NO_ERRCODE, LOG_INFO, "socket %d, actual os socket rcvbuf size %d\n", *s, actrcvbuf);
1346 if (rcvbuf != 0 && actrcvbuf / 2 != rcvbuf) {
1347 LogError(errno, NO_ERRCODE, "cannot set os socket rcvbuf size %d for socket %d, value now is %d",
1348 rcvbuf, *s, actrcvbuf / 2);
1349 }
1350 } else {
1351 DBGPRINTF("could not obtain os socket rcvbuf size for socket %d: %s\n", *s,
1352 rs_strerror_r(errno, errStr, sizeof(errStr)));
1353 }
1354 }
1355
1356 if (bIsServer) {
1357 /* rgerhards, 2007-06-22: if we run on a kernel that does not support
1358 * the IPV6_V6ONLY socket option, we need to use a work-around. On such
1359 * systems the IPv6 socket does also accept IPv4 sockets. So an IPv4
1360 * socket can not listen on the same port as an IPv6 socket. The only
1361 * workaround is to ignore the "socket in use" error. This is what we
1362 * do if we have to.
1363 */
1364 if ((bind(*s, r->ai_addr, r->ai_addrlen) < 0)
1365 #ifndef IPV6_V6ONLY
1366 && (errno != EADDRINUSE)
1367 #endif
1368 ) {
1369 if (errno == EADDRNOTAVAIL && ipfreebind != IPFREEBIND_DISABLED) {
1370 if (setsockopt(*s, IPPROTO_IP, IP_FREEBIND, &on, sizeof(on)) < 0) {
1371 LogError(errno, RS_RET_ERR, "setsockopt(IP_FREEBIND)");
1372 } else if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
1373 LogError(errno, RS_RET_ERR, "bind with IP_FREEBIND");
1374 } else {
1375 if (ipfreebind >= IPFREEBIND_ENABLED_WITH_LOG)
1376 LogMsg(0, RS_RET_OK_WARN, LOG_WARNING, "bound address %s IP free", hostname);
1377 FINALIZE;
1378 }
1379 }
1380 ABORT_FINALIZE(RS_RET_ERR);
1381 }
1382 }
1383
1384 finalize_it:
1385 if (iRet != RS_RET_OK) {
1386 if (*s != -1) {
1387 close(*s);
1388 *s = -1;
1389 }
1390 }
1391 RETiRet;
1392 }
1393
1394 /* creates the UDP listen sockets
1395 * hostname and/or pszPort may be NULL, but not both!
1396 * bIsServer indicates if a server socket should be created
1397 * 1 - server, 0 - client
1398 * Note: server sockets are created in non-blocking mode, client ones
1399 * are blocking.
1400 * param rcvbuf indicates desired rcvbuf size; 0 means OS default,
1401 * similar for sndbuf.
1402 */
1403 static int *create_udp_socket(uchar *hostname,
1404 uchar *pszPort,
1405 const int bIsServer,
1406 const int rcvbuf,
1407 const int sndbuf,
1408 const int ipfreebind,
1409 char *device) {
1410 struct addrinfo hints, *res, *r;
1411 int error, maxs, *s, *socks;
1412 rsRetVal localRet;
1413
1414 assert(!((pszPort == NULL) && (hostname == NULL))); /* one of them must be non-NULL */
1415 memset(&hints, 0, sizeof(hints));
1416 if (bIsServer)
1417 hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV;
1418 else
1419 hints.ai_flags = AI_NUMERICSERV;
1420 hints.ai_family = glbl.GetDefPFFamily(runConf);
1421 hints.ai_socktype = SOCK_DGRAM;
1422 #if defined(_AIX)
1423 /* AIXPORT : SOCK_DGRAM has the protocol IPPROTO_UDP
1424 * getaddrinfo needs this hint on AIX
1425 */
1426 hints.ai_protocol = IPPROTO_UDP;
1427 #endif
1428 error = getaddrinfo((char *)hostname, (char *)pszPort, &hints, &res);
1429 if (error) {
1430 LogError(0, NO_ERRCODE, "%s", gai_strerror(error));
1431 LogError(0, NO_ERRCODE, "UDP message reception disabled due to error logged in last message.\n");
1432 return NULL;
1433 }
1434
1435 /* Count max number of sockets we may open */
1436 for (maxs = 0, r = res; r != NULL; r = r->ai_next, maxs++) /* EMPTY */
1437 ;
1438 socks = malloc((maxs + 1) * sizeof(int));
1439 if (socks == NULL) {
1440 LogError(0, RS_RET_OUT_OF_MEMORY,
1441 "couldn't allocate memory for UDP "
1442 "sockets, suspending UDP message reception");
1443 freeaddrinfo(res);
1444 return NULL;
1445 }
1446
1447 *socks = 0; /* num of sockets counter at start of array */
1448 s = socks + 1;
1449 for (r = res; r != NULL; r = r->ai_next) {
1450 localRet = create_single_udp_socket(s, r, hostname, bIsServer, rcvbuf, sndbuf, ipfreebind, device);
1451 if (localRet == RS_RET_OK) {
1452 (*socks)++;
1453 s++;
1454 }
1455 }
1456
1457 if (res != NULL) freeaddrinfo(res);
1458
1459 if (Debug && *socks != maxs)
1460 dbgprintf(
1461 "We could initialize %d UDP listen sockets out of %d we received "
1462 "- this may or may not be an error indication.\n",
1463 *socks, maxs);
1464
1465 if (*socks == 0) {
1466 LogError(0, NO_ERRCODE,
1467 "No UDP socket could successfully be initialized, "
1468 "some functionality may be disabled.\n");
1469 /* we do NOT need to close any sockets, because there were none... */
1470 free(socks);
1471 return (NULL);
1472 }
1473
1474 return (socks);
1475 }
1476
1477
1478 /* check if two provided socket addresses point to the same host. Note that the
1479 * length of the sockets must be provided as third parameter. This is necessary to
1480 * compare non IPv4/v6 hosts, in which case we do a simple memory compare of the
1481 * address structure (in that case, the same host may not reliably be detected).
1482 * Note that we need to do the comparison not on the full structure, because it contains things
1483 * like the port, which we do not need to look at when thinking about hostnames. So we look
1484 * at the relevant fields, what means a somewhat more complicated processing.
1485 * Also note that we use a non-standard calling interface, as this is much more natural and
1486 * it looks extremely unlikely that we get an exception of any kind here. What we
1487 * return is mimiced after memcmp(), and as such useful for building binary trees
1488 * (the order relation may be a bit arbritrary, but at least it is consistent).
1489 * rgerhards, 2009-09-03
1490 */
1491 static int CmpHost(struct sockaddr_storage *s1, struct sockaddr_storage *s2, size_t socklen) {
1492 int ret;
1493
1494 if (((struct sockaddr *)s1)->sa_family != ((struct sockaddr *)s2)->sa_family) {
1495 ret = memcmp(s1, s2, socklen);
1496 goto finalize_it;
1497 }
1498
1499 if (((struct sockaddr *)s1)->sa_family == AF_INET) {
1500 if (((struct sockaddr_in *)s1)->sin_addr.s_addr == ((struct sockaddr_in *)s2)->sin_addr.s_addr) {
1501 ret = 0;
1502 } else if (((struct sockaddr_in *)s1)->sin_addr.s_addr < ((struct sockaddr_in *)s2)->sin_addr.s_addr) {
1503 ret = -1;
1504 } else {
1505 ret = 1;
1506 }
1507 } else if (((struct sockaddr *)s1)->sa_family == AF_INET6) {
1508 /* IPv6 addresses are always 16 octets long */
1509 ret =
1510 memcmp(((struct sockaddr_in6 *)s1)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)s2)->sin6_addr.s6_addr, 16);
1511 } else {
1512 ret = memcmp(s1, s2, socklen);
1513 }
1514
1515 finalize_it:
1516 return ret;
1517 }
1518
1519
1520 /* check if restrictions (ALCs) exists. The goal of this function is to disable the
1521 * somewhat time-consuming ACL checks if no restrictions are defined (the usual case).
1522 * This also permits to gain some speedup by using firewall-based ACLs instead of
1523 * rsyslog ACLs (the recommended method.
1524 * rgerhards, 2009-11-16
1525 */
1526 static rsRetVal HasRestrictions(uchar *pszType, int *bHasRestrictions) {
1527 struct AllowedSenders *pAllowRoot = NULL;
1528 DEFiRet;
1529
1530 CHKiRet(setAllowRoot(&pAllowRoot, pszType));
1531
1532 *bHasRestrictions = (pAllowRoot == NULL) ? 0 : 1;
1533
1534 finalize_it:
1535 if (iRet != RS_RET_OK) {
1536 *bHasRestrictions = 1; /* in this case it is better to check individually */
1537 DBGPRINTF("Error %d trying to obtain ACL restriction state of '%s'\n", iRet, pszType);
1538 }
1539 RETiRet;
1540 }
1541
1542
1543 /* return the IP address (IPv4/6) for the provided interface. Returns
1544 * RS_RET_NOT_FOUND if interface can not be found in interface list.
1545 * The family must be correct (AF_INET vs. AF_INET6, AF_UNSPEC means
1546 * either of *these two*).
1547 * The function re-queries the interface list (at least in theory).
1548 * However, it caches entries in order to avoid too-frequent requery.
1549 * rgerhards, 2012-03-06
1550 */
1551 static rsRetVal getIFIPAddr(uchar *szif, int family, uchar *pszbuf, int lenBuf) {
1552 #ifdef _AIX
1553 struct ifaddrs_rsys *ifaddrs = NULL;
1554 struct ifaddrs_rsys *ifa;
1555 #else
1556 struct ifaddrs *ifaddrs = NULL;
1557 struct ifaddrs *ifa;
1558 #endif
1559 union {
1560 struct sockaddr *sa;
1561 struct sockaddr_in *ipv4;
1562 struct sockaddr_in6 *ipv6;
1563 } savecast;
1564 void *pAddr;
1565 DEFiRet;
1566
1567 if (getifaddrs(&ifaddrs) != 0) {
1568 ABORT_FINALIZE(RS_RET_ERR);
1569 }
1570
1571 for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
1572 if (strcmp(ifa->ifa_name, (char *)szif)) continue;
1573 savecast.sa = ifa->ifa_addr;
1574 if ((family == AF_INET6 || family == AF_UNSPEC) && ifa->ifa_addr->sa_family == AF_INET6) {
1575 pAddr = &(savecast.ipv6->sin6_addr);
1576 inet_ntop(AF_INET6, pAddr, (char *)pszbuf, lenBuf);
1577 break;
1578 } else if (/* (family == AF_INET || family == AF_UNSPEC)
1579 &&*/
1580 ifa->ifa_addr->sa_family == AF_INET) {
1581 pAddr = &(savecast.ipv4->sin_addr);
1582 inet_ntop(AF_INET, pAddr, (char *)pszbuf, lenBuf);
1583 break;
1584 }
1585 }
1586
1587 if (ifaddrs != NULL) freeifaddrs(ifaddrs);
1588
1589 if (ifa == NULL) iRet = RS_RET_NOT_FOUND;
1590
1591 finalize_it:
1592 RETiRet;
1593 }
1594
1595
1596 /* queryInterface function
1597 * rgerhards, 2008-03-05
1598 */
1599 BEGINobjQueryInterface(net)
1600 CODESTARTobjQueryInterface(net);
1601 if (pIf->ifVersion != netCURR_IF_VERSION) { /* check for current version, increment on each change */
1602 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
1603 }
1604
1605 /* ok, we have the right interface, so let's fill it
1606 * Please note that we may also do some backwards-compatibility
1607 * work here (if we can support an older interface version - that,
1608 * of course, also affects the "if" above).
1609 */
1610 pIf->cvthname = cvthname;
1611 /* things to go away after proper modularization */
1612 pIf->addAllowedSenderLine = addAllowedSenderLine;
1613 pIf->PrintAllowedSenders = PrintAllowedSenders;
1614 pIf->clearAllowedSenders = clearAllowedSenders;
1615 pIf->debugListenInfo = debugListenInfo;
1616 pIf->create_udp_socket = create_udp_socket;
1617 pIf->closeUDPListenSockets = closeUDPListenSockets;
1618 pIf->isAllowedSender = isAllowedSender;
1619 pIf->isAllowedSender2 = isAllowedSender2;
1620 pIf->should_use_so_bsdcompat = should_use_so_bsdcompat;
1621 pIf->getLocalHostname = getLocalHostname;
1622 pIf->AddPermittedPeer = AddPermittedPeer;
1623 pIf->DestructPermittedPeers = DestructPermittedPeers;
1624 pIf->PermittedPeerWildcardMatch = PermittedPeerWildcardMatch;
1625 pIf->CmpHost = CmpHost;
1626 pIf->HasRestrictions = HasRestrictions;
1627 pIf->GetIFIPAddr = getIFIPAddr;
1628
1629 pIf->netns_save = netns_save;
1630 pIf->netns_restore = netns_restore;
1631 pIf->netns_switch = netns_switch;
1632 pIf->netns_socket = netns_socket;
1633 finalize_it:
1634 ENDobjQueryInterface(net)
1635
1636
1637 /* exit our class
1638 * rgerhards, 2008-03-10
1639 */
1640 BEGINObjClassExit(net, OBJ_IS_LOADABLE_MODULE) /* CHANGE class also in END MACRO! */
1641 CODESTARTObjClassExit(net);
1642 /* release objects we no longer need */
1643 objRelease(glbl, CORE_COMPONENT);
1644 objRelease(prop, CORE_COMPONENT);
1645 ENDObjClassExit(net)
1646
1647
1648 /* Initialize the net class. Must be called as the very first method
1649 * before anything else is called inside this class.
1650 * rgerhards, 2008-02-19
1651 */
1652 BEGINAbstractObjClassInit(net, 1, OBJ_IS_CORE_MODULE) /* class, version */
1653 /* request objects we use */
1654 CHKiRet(objUse(glbl, CORE_COMPONENT));
1655 CHKiRet(objUse(prop, CORE_COMPONENT));
1656
1657 /* set our own handlers */
1658 ENDObjClassInit(net)
1659
1660
1661 /* --------------- here now comes the plumbing that makes as a library module --------------- */
1662
1663
1664 BEGINmodExit
1665 CODESTARTmodExit;
1666 netClassExit();
1667 ENDmodExit
1668
1669
1670 BEGINqueryEtryPt
1671 CODESTARTqueryEtryPt;
1672 CODEqueryEtryPt_STD_LIB_QUERIES;
1673 ENDqueryEtryPt
1674
1675
1676 BEGINmodInit()
1677 CODESTARTmodInit;
1678 *ipIFVersProvided = CURR_MOD_IF_VERSION; /* we only support the current interface specification */
1679
1680 /* Initialize all classes that are in our module - this includes ourselfs */
1681 CHKiRet(netClassInit(pModInfo)); /* must be done after tcps_sess, as we use it */
1682 ENDmodInit
1683 /* vi:set ai:
1684 */