Debian Codegraph @

runtime/dnscache.c

raw
1 /* dnscache.c
2 * Implementation of a real DNS cache
3 *
4 * File begun on 2011-06-06 by RGerhards
5 * The initial implementation is far from being optimal. The idea is to
6 * first get somethting that'S functionally OK, and then evolve the algorithm.
7 * In any case, even the initial implementaton is far faster than what we had
8 * before. -- rgerhards, 2011-06-06
9 *
10 * Copyright 2011-2019 by Rainer Gerhards and Adiscon GmbH.
11 *
12 * This file is part of the rsyslog runtime library.
13 *
14 * Licensed under the Apache License, Version 2.0 (the "License");
15 * you may not use this file except in compliance with the License.
16 * You may obtain a copy of the License at
17 *
18 * http://www.apache.org/licenses/LICENSE-2.0
19 * -or-
20 * see COPYING.ASL20 in the source distribution
21 *
22 * Unless required by applicable law or agreed to in writing, software
23 * distributed under the License is distributed on an "AS IS" BASIS,
24 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 * See the License for the specific language governing permissions and
26 * limitations under the License.
27 */
28 #include "config.h"
29
30 #include "rsyslog.h"
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <signal.h>
34 #include <netdb.h>
35 #include <unistd.h>
36 #include <ctype.h>
37
38 #include "syslogd-types.h"
39 #include "glbl.h"
40 #include "errmsg.h"
41 #include "obj.h"
42 #include "unicode-helper.h"
43 #include "net.h"
44 #include "hashtable.h"
45 #include "prop.h"
46 #include "dnscache.h"
47 #include "rsconf.h"
48
49 /* module data structures */
50 struct dnscache_entry_s {
51 struct sockaddr_storage addr;
52 prop_t *fqdn;
53 prop_t *fqdnLowerCase;
54 prop_t *localName; /* only local name, without domain part (if configured so) */
55 prop_t *ip;
56 time_t validUntil;
57 struct dnscache_entry_s *next;
58 unsigned nUsed;
59 };
60 typedef struct dnscache_entry_s dnscache_entry_t;
61 struct dnscache_s {
62 pthread_rwlock_t rwlock;
63 struct hashtable *ht;
64 unsigned nEntries;
65 };
66 typedef struct dnscache_s dnscache_t;
67
68
69 /* static data */
70 DEFobjStaticHelpers;
71 DEFobjCurrIf(glbl) DEFobjCurrIf(prop) static dnscache_t dnsCache;
72 static prop_t *staticErrValue;
73
74
75 /* Our hash function.
76 */
77 static unsigned int hash_from_key_fn(void *k) {
78 int len = 0;
79 uchar *rkey; /* we treat this as opaque bytes */
80 unsigned hashval = 1;
81
82 switch (((struct sockaddr *)k)->sa_family) {
83 case AF_INET:
84 len = sizeof(struct in_addr);
85 rkey = (uchar *)&(((struct sockaddr_in *)k)->sin_addr);
86 break;
87 case AF_INET6:
88 len = sizeof(struct in6_addr);
89 rkey = (uchar *)&(((struct sockaddr_in6 *)k)->sin6_addr);
90 break;
91 default:
92 dbgprintf("hash_from_key_fn: unknown address family!\n");
93 len = 0;
94 rkey = NULL;
95 }
96 while (len--) {
97 /* the casts are done in order to prevent undefined behavior sanitizer
98 * from triggering warnings. Actually, it would be OK if we have just
99 * "random" truncation.
100 */
101 hashval = (unsigned)(hashval * (unsigned long long)33) + *rkey++;
102 }
103
104 if (((struct sockaddr *)k)->sa_family == AF_INET6) {
105 const uint32_t scope_id = ((struct sockaddr_in6 *)k)->sin6_scope_id;
106 for (size_t i = 0; i < sizeof(scope_id); ++i) {
107 hashval = (unsigned)(hashval * (unsigned long long)33) + ((scope_id >> (i * 8)) & 0xff);
108 }
109 }
110
111 return hashval;
112 }
113
114
115 static int key_equals_fn(void *key1, void *key2) {
116 int RetVal = 0;
117
118 if (((struct sockaddr *)key1)->sa_family != ((struct sockaddr *)key2)->sa_family) {
119 return 0;
120 }
121 switch (((struct sockaddr *)key1)->sa_family) {
122 case AF_INET:
123 RetVal = !memcmp(&((struct sockaddr_in *)key1)->sin_addr, &((struct sockaddr_in *)key2)->sin_addr,
124 sizeof(struct in_addr));
125 break;
126 case AF_INET6:
127 RetVal = !memcmp(&((struct sockaddr_in6 *)key1)->sin6_addr, &((struct sockaddr_in6 *)key2)->sin6_addr,
128 sizeof(struct in6_addr)) &&
129 ((struct sockaddr_in6 *)key1)->sin6_scope_id == ((struct sockaddr_in6 *)key2)->sin6_scope_id;
130 break;
131 default:
132 // No action needed for other cases
133 break;
134 }
135
136 return RetVal;
137 }
138
139 /* destruct a cache entry.
140 * Precondition: entry must already be unlinked from list
141 */
142 static void ATTR_NONNULL() entryDestruct(dnscache_entry_t *const etry) {
143 if (etry->fqdn != NULL) prop.Destruct(&etry->fqdn);
144 if (etry->fqdnLowerCase != NULL) prop.Destruct(&etry->fqdnLowerCase);
145 if (etry->localName != NULL) prop.Destruct(&etry->localName);
146 if (etry->ip != NULL) prop.Destruct(&etry->ip);
147 free(etry);
148 }
149
150 /* init function (must be called once) */
151 rsRetVal dnscacheInit(void) {
152 DEFiRet;
153 if ((dnsCache.ht = create_hashtable(100, hash_from_key_fn, key_equals_fn, (void (*)(void *))entryDestruct)) ==
154 NULL) {
155 DBGPRINTF("dnscache: error creating hash table!\n");
156 ABORT_FINALIZE(RS_RET_ERR); // TODO: make this degrade, but run!
157 }
158 dnsCache.nEntries = 0;
159 pthread_rwlock_init(&dnsCache.rwlock, NULL);
160 CHKiRet(objGetObjInterface(&obj)); /* this provides the root pointer for all other queries */
161 CHKiRet(objUse(glbl, CORE_COMPONENT));
162 CHKiRet(objUse(prop, CORE_COMPONENT));
163
164 prop.Construct(&staticErrValue);
165 prop.SetString(staticErrValue, (uchar *)"???", 3);
166 prop.ConstructFinalize(staticErrValue);
167 finalize_it:
168 RETiRet;
169 }
170
171 /* deinit function (must be called once) */
172 rsRetVal dnscacheDeinit(void) {
173 DEFiRet;
174 prop.Destruct(&staticErrValue);
175 hashtable_destroy(dnsCache.ht, 1); /* 1 => free all values automatically */
176 pthread_rwlock_destroy(&dnsCache.rwlock);
177 objRelease(glbl, CORE_COMPONENT);
178 objRelease(prop, CORE_COMPONENT);
179 RETiRet;
180 }
181
182
183 /* This is a cancel-safe getnameinfo() version, because we learned
184 * (via drd/valgrind) that getnameinfo() seems to have some issues
185 * when being cancelled, at least if the module was dlloaded.
186 * rgerhards, 2008-09-30
187 */
188 static int mygetnameinfo(
189 const struct sockaddr *sa, socklen_t salen, char *host, size_t hostlen, char *serv, size_t servlen, int flags) {
190 int iCancelStateSave;
191 int i;
192
193 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &iCancelStateSave);
194 i = getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
195 pthread_setcancelstate(iCancelStateSave, NULL);
196 return i;
197 }
198
199
200 /* get only the local part of the hostname and set it in cache entry */
201 static void setLocalHostName(dnscache_entry_t *etry) {
202 uchar *fqdnLower;
203 uchar *p;
204 int i;
205 uchar hostbuf[NI_MAXHOST];
206
207 if (glbl.GetPreserveFQDN()) {
208 prop.AddRef(etry->fqdnLowerCase);
209 etry->localName = etry->fqdnLowerCase;
210 goto done;
211 }
212
213 /* strip domain, if configured for this entry */
214 fqdnLower = propGetSzStr(etry->fqdnLowerCase);
215 p = (uchar *)strchr((char *)fqdnLower, '.'); /* find start of domain name "machine.example.com" */
216 if (p == NULL) { /* do we have a domain part? */
217 prop.AddRef(etry->fqdnLowerCase); /* no! */
218 etry->localName = etry->fqdnLowerCase;
219 goto done;
220 }
221
222 i = p - fqdnLower; /* length of hostname */
223 memcpy(hostbuf, fqdnLower, i);
224 hostbuf[i] = '\0';
225
226 /* at this point, we have not found anything, so we again use the
227 * already-created complete full name property.
228 */
229 prop.AddRef(etry->fqdnLowerCase);
230 etry->localName = etry->fqdnLowerCase;
231 done:
232 return;
233 }
234
235
236 /* resolve an address.
237 *
238 * Please see http://www.hmug.org/man/3/getnameinfo.php (under Caveats)
239 * for some explanation of the code found below. We do by default not
240 * discard message where we detected malicouos DNS PTR records. However,
241 * there is a user-configurabel option that will tell us if
242 * we should abort. For this, the return value tells the caller if the
243 * message should be processed (1) or discarded (0).
244 */
245 static rsRetVal ATTR_NONNULL() resolveAddr(struct sockaddr_storage *addr, dnscache_entry_t *etry) {
246 DEFiRet;
247 int error;
248 sigset_t omask, nmask;
249 struct addrinfo hints, *res;
250 char szIP[NI_MAXHOST];
251 char fqdnBuf[NI_MAXHOST];
252 rs_size_t fqdnLen;
253 rs_size_t i;
254
255 error = mygetnameinfo((struct sockaddr *)addr, SALEN((struct sockaddr *)addr), (char *)szIP, sizeof(szIP), NULL, 0,
256 NI_NUMERICHOST);
257 if (error) {
258 dbgprintf("Malformed from address %s\n", gai_strerror(error));
259 ABORT_FINALIZE(RS_RET_INVALID_SOURCE);
260 }
261
262 if (!glbl.GetDisableDNS(runConf)) {
263 sigemptyset(&nmask);
264 sigaddset(&nmask, SIGHUP);
265 pthread_sigmask(SIG_BLOCK, &nmask, &omask);
266
267 error = mygetnameinfo((struct sockaddr *)addr, SALEN((struct sockaddr *)addr), fqdnBuf, NI_MAXHOST, NULL, 0,
268 NI_NAMEREQD);
269
270 if (error == 0) {
271 memset(&hints, 0, sizeof(struct addrinfo));
272 hints.ai_flags = AI_NUMERICHOST;
273
274 /* we now do a lookup once again. This one should fail,
275 * because we should not have obtained a non-numeric address. If
276 * we got a numeric one, someone messed with DNS!
277 */
278 if (getaddrinfo(fqdnBuf, NULL, &hints, &res) == 0) {
279 freeaddrinfo(res);
280 /* OK, we know we have evil. The question now is what to do about
281 * it. One the one hand, the message might probably be intended
282 * to harm us. On the other hand, losing the message may also harm us.
283 * Thus, the behaviour is controlled by the $DropMsgsWithMaliciousDnsPTRRecords
284 * option. If it tells us we should discard, we do so, else we proceed,
285 * but log an error message together with it.
286 * time being, we simply drop the name we obtained and use the IP - that one
287 * is OK in any way. We do also log the error message. rgerhards, 2007-07-16
288 */
289 if (glbl.GetDropMalPTRMsgs(runConf) == 1) {
290 LogError(0, RS_RET_MALICIOUS_ENTITY,
291 "Malicious PTR record, message dropped "
292 "IP = \"%s\" HOST = \"%s\"",
293 szIP, fqdnBuf);
294 pthread_sigmask(SIG_SETMASK, &omask, NULL);
295 ABORT_FINALIZE(RS_RET_MALICIOUS_ENTITY);
296 }
297
298 /* Please note: we deal with a malicous entry. Thus, we have crafted
299 * the snprintf() below so that all text is in front of the entry - maybe
300 * it contains characters that make the message unreadable
301 * (OK, I admit this is more or less impossible, but I am paranoid...)
302 * rgerhards, 2007-07-16
303 */
304 LogError(0, NO_ERRCODE,
305 "Malicious PTR record (message accepted, but used IP "
306 "instead of PTR name: IP = \"%s\" HOST = \"%s\"",
307 szIP, fqdnBuf);
308
309 error = 1; /* that will trigger using IP address below. */
310 } else { /* we have a valid entry, so let's create the respective properties */
311 fqdnLen = strlen(fqdnBuf);
312 prop.CreateStringProp(&etry->fqdn, (uchar *)fqdnBuf, fqdnLen);
313 for (i = 0; i < fqdnLen; ++i) fqdnBuf[i] = tolower(fqdnBuf[i]);
314 prop.CreateStringProp(&etry->fqdnLowerCase, (uchar *)fqdnBuf, fqdnLen);
315 }
316 }
317 pthread_sigmask(SIG_SETMASK, &omask, NULL);
318 }
319
320
321 finalize_it:
322 if (iRet != RS_RET_OK) {
323 RS_COPY_LITERAL(szIP, "?error.obtaining.ip?");
324 error = 1; /* trigger hostname copies below! */
325 }
326
327 prop.CreateStringProp(&etry->ip, (uchar *)szIP, strlen(szIP));
328
329 if (error || glbl.GetDisableDNS(runConf)) {
330 dbgprintf("Host name for your address (%s) unknown\n", szIP);
331 prop.AddRef(etry->ip);
332 etry->fqdn = etry->ip;
333 prop.AddRef(etry->ip);
334 etry->fqdnLowerCase = etry->ip;
335 }
336
337 setLocalHostName(etry);
338
339 RETiRet;
340 }
341
342
343 static rsRetVal ATTR_NONNULL() addEntry(struct sockaddr_storage *const addr, dnscache_entry_t **const pEtry) {
344 int r;
345 dnscache_entry_t *etry = NULL;
346 DEFiRet;
347
348 /* entry still does not exist, so add it */
349 struct sockaddr_storage *const keybuf = malloc(sizeof(struct sockaddr_storage));
350 CHKmalloc(keybuf);
351 CHKmalloc(etry = malloc(sizeof(dnscache_entry_t)));
352 resolveAddr(addr, etry);
353 assert(etry != NULL);
354 memcpy(&etry->addr, addr, SALEN((struct sockaddr *)addr));
355 etry->nUsed = 0;
356 if (runConf->globals.dnscacheEnableTTL) {
357 etry->validUntil = time(NULL) + runConf->globals.dnscacheDefaultTTL;
358 }
359
360 memcpy(keybuf, addr, sizeof(struct sockaddr_storage));
361
362 r = hashtable_insert(dnsCache.ht, keybuf, etry);
363 if (r == 0) {
364 DBGPRINTF("dnscache: inserting element failed\n");
365 }
366 *pEtry = etry;
367
368 finalize_it:
369 if (iRet != RS_RET_OK) {
370 free(keybuf);
371 }
372 RETiRet;
373 }
374
375
376 static rsRetVal ATTR_NONNULL(1, 5) findEntry(struct sockaddr_storage *const addr,
377 prop_t **const fqdn,
378 prop_t **const fqdnLowerCase,
379 prop_t **const localName,
380 prop_t **const ip) {
381 DEFiRet;
382
383 pthread_rwlock_rdlock(&dnsCache.rwlock);
384 dnscache_entry_t *etry = hashtable_search(dnsCache.ht, addr);
385 DBGPRINTF("findEntry: 1st lookup found %p\n", etry);
386
387 if (etry == NULL || (runConf->globals.dnscacheEnableTTL && (etry->validUntil <= time(NULL)))) {
388 pthread_rwlock_unlock(&dnsCache.rwlock);
389 pthread_rwlock_wrlock(&dnsCache.rwlock);
390 etry = hashtable_search(dnsCache.ht, addr); /* re-query, might have changed */
391 DBGPRINTF("findEntry: 2nd lookup found %p\n", etry);
392 if (etry == NULL || (runConf->globals.dnscacheEnableTTL && (etry->validUntil <= time(NULL)))) {
393 if (etry != NULL) {
394 DBGPRINTF(
395 "hashtable: entry timed out, discarding it; "
396 "valid until %lld, now %lld\n",
397 (long long)etry->validUntil, (long long)time(NULL));
398 dnscache_entry_t *const deleted = hashtable_remove(dnsCache.ht, addr);
399 if (deleted != etry) {
400 LogError(0, RS_RET_INTERNAL_ERROR,
401 "dnscache %d: removed different "
402 "hashtable entry than expected - please report issue; "
403 "rsyslog version is %s",
404 __LINE__, VERSION);
405 }
406 entryDestruct(etry);
407 }
408 /* now entry doesn't exist in any case, so let's (re)create it */
409 CHKiRet(addEntry(addr, &etry));
410 }
411 }
412
413 prop.AddRef(etry->ip);
414 *ip = etry->ip;
415 if (fqdn != NULL) {
416 prop.AddRef(etry->fqdn);
417 *fqdn = etry->fqdn;
418 }
419 if (fqdnLowerCase != NULL) {
420 prop.AddRef(etry->fqdnLowerCase);
421 *fqdnLowerCase = etry->fqdnLowerCase;
422 }
423 if (localName != NULL) {
424 prop.AddRef(etry->localName);
425 *localName = etry->localName;
426 }
427
428 finalize_it:
429 pthread_rwlock_unlock(&dnsCache.rwlock);
430 RETiRet;
431 }
432
433
434 /* This is the main function: it looks up an entry and returns it's name
435 * and IP address. If the entry is not yet inside the cache, it is added.
436 * If the entry can not be resolved, an error is reported back. If fqdn
437 * or fqdnLowerCase are NULL, they are not set.
438 */
439 rsRetVal ATTR_NONNULL(1, 5) dnscacheLookup(struct sockaddr_storage *const addr,
440 prop_t **const fqdn,
441 prop_t **const fqdnLowerCase,
442 prop_t **const localName,
443 prop_t **const ip) {
444 DEFiRet;
445
446 iRet = findEntry(addr, fqdn, fqdnLowerCase, localName, ip);
447
448 if (iRet != RS_RET_OK) {
449 DBGPRINTF("dnscacheLookup failed with iRet %d\n", iRet);
450 prop.AddRef(staticErrValue);
451 *ip = staticErrValue;
452 if (fqdn != NULL) {
453 prop.AddRef(staticErrValue);
454 *fqdn = staticErrValue;
455 }
456 if (fqdnLowerCase != NULL) {
457 prop.AddRef(staticErrValue);
458 *fqdnLowerCase = staticErrValue;
459 }
460 if (localName != NULL) {
461 prop.AddRef(staticErrValue);
462 *localName = staticErrValue;
463 }
464 }
465 RETiRet;
466 }