chiark / gitweb /
linux.c (parseaddr_ipv6): Fix operator spacing.
[yaid] / linux.c
CommitLineData
9dcdc856
MW
1/* -*-c-*-
2 *
bf4d9761 3 * Discover the owner of a connection (Linux version)
9dcdc856
MW
4 *
5 * (c) 2012 Straylight/Edgeware
6 */
7
8/*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of Yet Another Ident Daemon (YAID).
11 *
12 * YAID is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * YAID is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with YAID; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27/*----- Header files ------------------------------------------------------*/
28
9da480be 29#include "yaid.h"
9dcdc856 30
c3794524
MW
31#include <linux/netlink.h>
32#include <linux/rtnetlink.h>
33
9dcdc856
MW
34/*----- Static variables --------------------------------------------------*/
35
c3794524 36static FILE *natfp; /* File handle for NAT table */
b093b41d
MW
37
38/*----- Address-type operations -------------------------------------------*/
39
bf4d9761
MW
40struct addrops_sys {
41 const char *procfile;
2a9b8d4a 42 const char *nfl3name;
bf4d9761 43 int (*parseaddr)(char **, union addr *);
9dcdc856
MW
44};
45
3b1bed1d 46#define PROCFILE_IPV4 "/proc/net/tcp"
2a9b8d4a 47#define NFL3NAME_IPV4 "ipv4"
3b1bed1d 48
bf4d9761 49static int parseaddr_ipv4(char **pp, union addr *a)
9da480be 50 { a->ipv4.s_addr = strtoul(*pp, pp, 16); return (0); }
9dcdc856 51
3b1bed1d 52#define PROCFILE_IPV6 "/proc/net/tcp6"
2a9b8d4a 53#define NFL3NAME_IPV6 "ipv6"
9dcdc856 54
bf4d9761 55static int parseaddr_ipv6(char **pp, union addr *a)
9da480be
MW
56{
57 int i, j;
58 unsigned long y;
59 char *p = *pp;
60 unsigned x;
61
c3794524 62 /* The format is byteswapped in a really annoying way. */
9da480be
MW
63 for (i = 0; i < 4; i++) {
64 y = 0;
65 for (j = 0; j < 8; j++) {
66 if ('0' <= *p && *p <= '9') x = *p - '0';
e9c4f66d
MW
67 else if ('a' <= *p && *p <= 'f') x = *p - 'a' + 10;
68 else if ('A' <= *p && *p <= 'F') x = *p - 'A' + 10;
9da480be
MW
69 else return (-1);
70 y = (y << 4) | x;
71 p++;
72 }
73 a->ipv6.s6_addr32[i] = y;
74 }
75 *pp = p;
76 return (0);
77}
78
3b1bed1d
MW
79#define DEFOPSYS(ty, TY) \
80 const struct addrops_sys addrops_sys_##ty = { \
2a9b8d4a 81 PROCFILE_##TY, NFL3NAME_##TY, parseaddr_##ty \
3b1bed1d
MW
82 };
83ADDRTYPES(DEFOPSYS)
84#undef DEFOPSYS
9dcdc856
MW
85
86/*----- Main code ---------------------------------------------------------*/
87
c3794524
MW
88/* Store in A the default gateway address for the given address family.
89 * Return zero on success, or nonzero on error.
90 */
77fb54ff 91static int get_default_gw(int af, union addr *a)
9dcdc856 92{
9da480be
MW
93 int fd;
94 char buf[32768];
95 struct nlmsghdr *nlmsg;
96 struct rtgenmsg *rtgen;
97 const struct rtattr *rta;
98 const struct rtmsg *rtm;
99 ssize_t n, nn;
c63b1d0a 100 int rc = -1;
9da480be
MW
101 static unsigned long seq = 0x48b4aec4;
102
c3794524 103 /* Open a netlink socket for interrogating the kernel. */
9da480be
MW
104 if ((fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
105 die(1, "failed to create netlink socket: %s", strerror(errno));
106
c3794524
MW
107 /* We want to read the routing table. There doesn't seem to be a good way
108 * to do this without just crawling through the whole thing.
109 */
9da480be
MW
110 nlmsg = (struct nlmsghdr *)buf;
111 assert(NLMSG_SPACE(sizeof(*rtgen)) < sizeof(buf));
112 nlmsg->nlmsg_len = NLMSG_LENGTH(sizeof(*rtgen));
113 nlmsg->nlmsg_type = RTM_GETROUTE;
114 nlmsg->nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT;
115 nlmsg->nlmsg_seq = ++seq;
116 nlmsg->nlmsg_pid = 0;
117
118 rtgen = (struct rtgenmsg *)NLMSG_DATA(nlmsg);
119 rtgen->rtgen_family = af;
120
121 if (write(fd, nlmsg, nlmsg->nlmsg_len) < 0)
122 die(1, "failed to send RTM_GETROUTE request: %s", strerror(errno));
9dcdc856 123
c3794524 124 /* Now we try to parse the answer. */
9da480be 125 for (;;) {
c3794524
MW
126
127 /* Not finished yet, so read another chunk of answer. */
9da480be
MW
128 if ((n = read(fd, buf, sizeof(buf))) < 0)
129 die(1, "failed to read RTM_GETROUTE response: %s", strerror(errno));
c3794524
MW
130
131 /* Start at the beginning of the response. */
9da480be 132 nlmsg = (struct nlmsghdr *)buf;
c3794524
MW
133
134 /* Make sure this looks plausible. The precise rules don't appear to be
135 * documented, so it seems advisable to fail messily if my understanding
136 * is wrong.
137 */
9da480be
MW
138 if (nlmsg->nlmsg_seq != seq) continue;
139 assert(nlmsg->nlmsg_flags & NLM_F_MULTI);
140
c3794524 141 /* Work through all of the individual routes. */
9da480be
MW
142 for (; NLMSG_OK(nlmsg, n); nlmsg = NLMSG_NEXT(nlmsg, n)) {
143 if (nlmsg->nlmsg_type == NLMSG_DONE) goto done;
144 if (nlmsg->nlmsg_type != RTM_NEWROUTE) continue;
145 rtm = (const struct rtmsg *)NLMSG_DATA(nlmsg);
146
c3794524
MW
147 /* If this record doesn't look interesting then skip it. */
148 if (rtm->rtm_family != af || /* wrong address family */
149 rtm->rtm_dst_len > 0 || /* specific destination */
150 rtm->rtm_src_len > 0 || /* specific source */
151 rtm->rtm_type != RTN_UNICAST || /* not for unicast */
152 rtm->rtm_scope != RT_SCOPE_UNIVERSE || /* wrong scope */
153 rtm->rtm_tos != 0) /* specific type of service */
9da480be 154 continue;
9dcdc856 155
c3794524 156 /* Trundle through the attributes and find the gateway address. */
9da480be
MW
157 for (rta = RTM_RTA(rtm), nn = RTM_PAYLOAD(nlmsg);
158 RTA_OK(rta, nn); rta = RTA_NEXT(rta, nn)) {
c3794524
MW
159
160 /* Got one. We're all done. Except that we should carry on reading
161 * to the end, or something bad will happen.
162 */
9da480be
MW
163 if (rta->rta_type == RTA_GATEWAY) {
164 assert(RTA_PAYLOAD(rta) <= sizeof(*a));
165 memcpy(a, RTA_DATA(rta), RTA_PAYLOAD(rta));
c63b1d0a 166 rc = 0;
9da480be
MW
167 }
168 }
169 }
170 }
9dcdc856 171
9da480be
MW
172done:
173 close(fd);
174 return (rc);
9dcdc856
MW
175}
176
c3794524
MW
177/* Find out who is responsible for the connection described in the query Q.
178 * Write the answer to Q. Errors are logged and reported via the query
179 * structure.
180 */
9da480be 181void identify(struct query *q)
9dcdc856 182{
9dcdc856
MW
183 FILE *fp = 0;
184 dstr d = DSTR_INIT;
185 char *p, *pp;
186 struct socket s[4];
187 int i;
9da480be 188 int gwp = 0;
9dcdc856
MW
189 unsigned fl;
190#define F_SADDR 1u
191#define F_SPORT 2u
192#define F_DADDR 4u
193#define F_DPORT 8u
194#define F_ALL (F_SADDR | F_SPORT | F_DADDR | F_DPORT)
195#define F_ESTAB 16u
196 uid_t uid;
197 enum { LOC, REM, ST, UID, NFIELD };
198 int f, ff[NFIELD];
199
c3794524
MW
200 /* If we have a default gateway, and it matches the remote address then
201 * this may be a proxy connection from our NAT, so remember this, and don't
202 * inspect the remote addresses in the TCP tables.
203 */
c63b1d0a 204 if (!get_default_gw(q->ao->af, &s[0].addr) &&
bf4d9761 205 q->ao->addreq(&s[0].addr, &q->s[R].addr))
9da480be
MW
206 gwp = 1;
207
c3794524 208 /* Open the relevant TCP connection table. */
bf4d9761 209 if ((fp = fopen(q->ao->sys->procfile, "r")) == 0) {
9dcdc856 210 logmsg(q, LOG_ERR, "failed to open `%s' for reading: %s",
bf4d9761 211 q->ao->sys->procfile, strerror(errno));
9dcdc856
MW
212 goto err_unk;
213 }
214
c3794524
MW
215 /* Initially, PP points into a string containing whitespace-separated
216 * fields. Point P to the next field, null-terminate it, and advance PP
217 * so that we can read the next field in the next call.
218 */
9dcdc856
MW
219#define NEXTFIELD do { \
220 for (p = pp; isspace((unsigned char)*p); p++); \
221 for (pp = p; *pp && !isspace((unsigned char)*pp); pp++); \
222 if (*pp) *pp++ = 0; \
223} while (0)
224
c3794524 225 /* Read the header line from the file. */
9dcdc856
MW
226 if (dstr_putline(&d, fp) == EOF) {
227 logmsg(q, LOG_ERR, "failed to read header line from `%s': %s",
bf4d9761
MW
228 q->ao->sys->procfile,
229 ferror(fp) ? strerror(errno) : "unexpected EOF");
9dcdc856
MW
230 goto err_unk;
231 }
232
c3794524
MW
233 /* Now scan the header line to identify which columns the various
234 * interesting fields are in. Store these in the map `ff'. Problems:
235 * `tx_queue rx_queue' and `tr tm->when' are both really single columns in
236 * disguise; and the remote address column has a different heading
237 * depending on which address family we're using. Rather than dispatch,
238 * just recognize both of them.
239 */
9dcdc856
MW
240 for (i = 0; i < NFIELD; i++) ff[i] = -1;
241 pp = d.buf;
242 for (f = 0;; f++) {
243 NEXTFIELD; if (!*p) break;
244 if (strcmp(p, "local_address") == 0)
245 ff[LOC] = f;
246 else if (strcmp(p, "rem_address") == 0 ||
247 strcmp(p, "remote_address") == 0)
248 ff[REM] = f;
249 else if (strcmp(p, "uid") == 0)
250 ff[UID] = f;
251 else if (strcmp(p, "st") == 0)
252 ff[ST] = f;
253 else if (strcmp(p, "rx_queue") == 0 ||
254 strcmp(p, "tm->when") == 0)
255 f--;
256 }
c3794524
MW
257
258 /* Make sure that we found all of the fields we actually want. */
9dcdc856
MW
259 for (i = 0; i < NFIELD; i++) {
260 if (ff[i] < 0) {
261 logmsg(q, LOG_ERR, "failed to find required fields in `%s'",
bf4d9761 262 q->ao->sys->procfile);
9dcdc856
MW
263 goto err_unk;
264 }
265 }
266
c3794524 267 /* Work through the lines in the file. */
9dcdc856 268 for (;;) {
c3794524
MW
269
270 /* Read a line, and prepare to scan the fields. */
9dcdc856
MW
271 DRESET(&d);
272 if (dstr_putline(&d, fp) == EOF) break;
273 pp = d.buf;
274 uid = -1;
c3794524
MW
275
276 /* Work through the fields. If an address field fails to match then we
277 * skip this record. If the state field isn't 1 (`ESTABLISHED') then
278 * skip the record. If it's the UID, then remember it: if we get all the
279 * way to the end then we've won.
280 */
9dcdc856
MW
281 for (f = 0;; f++) {
282 NEXTFIELD; if (!*p) break;
283 if (f == ff[LOC]) { i = L; goto compare; }
284 else if (f == ff[REM]) { i = R; goto compare; }
285 else if (f == ff[UID]) uid = atoi(p);
286 else if (f == ff[ST]) {
287 if (strtol(p, 0, 16) != 1) goto next_row;
288 }
289 continue;
290
291 compare:
c3794524
MW
292 /* Compare an address (in the current field) with the local or remote
293 * address in the query, as indicated by `i'. The address field looks
294 * like `ADDR:PORT', where the ADDR is in some mad format which
295 * `sys->parseaddr' knows how to unpick. If the remote address in the
296 * query is our gateway then don't check the remote address in the
297 * field (but do check the port number).
298 */
223e3e2b 299 if (q->ao->sys->parseaddr(&p, &s[i].addr)) goto next_row;
9dcdc856 300 if (*p != ':') break; p++;
223e3e2b 301 s[i].port = strtoul(p, 0, 16);
c3794524 302 if ((i == R && gwp) ?
223e3e2b
MW
303 q->s[R].port != s[i].port :
304 !sockeq(q->ao, &q->s[i], &s[i]))
9da480be 305 goto next_row;
9dcdc856 306 }
c3794524
MW
307
308 /* We got to the end, and everything matched. If we found a UID then
223e3e2b
MW
309 * we're done. If the apparent remote address is our gateway then copy
310 * the true one into the query structure.
c3794524 311 */
9dcdc856 312 if (uid != -1) {
9da480be
MW
313 q->resp = R_UID;
314 q->u.uid = uid;
223e3e2b 315 if (gwp) q->s[R].addr = s[i].addr;
9dcdc856
MW
316 goto done;
317 }
318 next_row:;
319 }
320
c3794524 321 /* We got to the end of the file and didn't find anything. */
9dcdc856 322 if (ferror(fp)) {
b093b41d
MW
323 logmsg(q, LOG_ERR, "failed to read connection table `%s': %s",
324 q->ao->sys->procfile, strerror(errno));
9dcdc856
MW
325 goto err_unk;
326 }
327
c3794524
MW
328 /* If we opened the NAT table file, and we're using IPv4, then check to see
329 * whether we should proxy the connection. At least the addresses in this
330 * file aren't crazy.
331 */
2a9b8d4a 332 if (natfp) {
c3794524
MW
333
334 /* Start again from the beginning. */
b093b41d 335 rewind(natfp);
9dcdc856 336
c3794524 337 /* Read a line at a time. */
9dcdc856 338 for (;;) {
c3794524
MW
339
340 /* Read the line. */
9dcdc856 341 DRESET(&d);
b093b41d 342 if (dstr_putline(&d, natfp) == EOF) break;
9dcdc856 343 pp = d.buf;
2a9b8d4a 344
c3794524 345 /* Check that this is for the right protocol. */
2a9b8d4a
MW
346 NEXTFIELD; if (!*p) break;
347 if (strcmp(p, q->ao->sys->nfl3name)) continue;
348 NEXTFIELD; if (!*p) break;
9dcdc856
MW
349 NEXTFIELD; if (!*p) break;
350 if (strcmp(p, "tcp") != 0) continue;
c3794524
MW
351
352 /* Parse the other fields. Each line has two src/dst pairs, for the
353 * outgoing and incoming directions. Depending on exactly what kind of
354 * NAT is in use, either the outgoing source or the incoming
355 * destination might be the client we're after. Collect all of the
356 * addresses and sort out the mess later.
357 */
9dcdc856
MW
358 i = 0;
359 fl = 0;
360 for (;;) {
361 NEXTFIELD; if (!*p) break;
362 if (strcmp(p, "ESTABLISHED") == 0)
363 fl |= F_ESTAB;
364 else if (strncmp(p, "src=", 4) == 0) {
2a9b8d4a 365 inet_pton(q->ao->af, p + 4, &s[i].addr);
9dcdc856
MW
366 fl |= F_SADDR;
367 } else if (strncmp(p, "dst=", 4) == 0) {
2a9b8d4a 368 inet_pton(q->ao->af, p + 4, &s[i + 1].addr);
9dcdc856
MW
369 fl |= F_DADDR;
370 } else if (strncmp(p, "sport=", 6) == 0) {
371 s[i].port = atoi(p + 6);
372 fl |= F_SPORT;
373 } else if (strncmp(p, "dport=", 6) == 0) {
374 s[i + 1].port = atoi(p + 6);
375 fl |= F_DPORT;
376 }
377 if ((fl & F_ALL) == F_ALL) {
378 fl &= ~F_ALL;
379 if (i < 4) i += 2;
380 else break;
381 }
382 }
383
384#ifdef notdef
385 {
c3794524 386 /* Print the record we found. */
9dcdc856
MW
387 dstr dd = DSTR_INIT;
388 dstr_putf(&dd, "%sestab ", (fl & F_ESTAB) ? " " : "!");
bf4d9761 389 dputsock(&dd, q->ao, &s[0]);
9dcdc856 390 dstr_puts(&dd, "<->");
bf4d9761 391 dputsock(&dd, q->ao, &s[1]);
9dcdc856 392 dstr_puts(&dd, " | ");
bf4d9761 393 dputsock(&dd, q->ao, &s[2]);
9dcdc856 394 dstr_puts(&dd, "<->");
bf4d9761 395 dputsock(&dd, q->ao, &s[3]);
9dcdc856
MW
396 printf("parsed: %s\n", dd.buf);
397 dstr_destroy(&dd);
398 }
399#endif
400
c3794524 401 /* If the connection isn't ESTABLISHED then skip it. */
9dcdc856
MW
402 if (!(fl & F_ESTAB)) continue;
403
c3794524
MW
404 /* Now we try to piece together what's going on. One of these
405 * addresses will be us. So let's just try to find it.
406 */
9dcdc856 407 for (i = 0; i < 4; i++)
bf4d9761 408 if (sockeq(q->ao, &s[i], &q->s[L])) goto found_local;
9dcdc856 409 continue;
c3794524 410
9dcdc856 411 found_local:
c3794524
MW
412 /* So address `i' is us. In that case, we expect the other address in
413 * the same direction, and the same address in the opposite direction,
414 * to match each other and be the remote address in the query.
415 */
bf4d9761
MW
416 if (!sockeq(q->ao, &s[i^1], &s[i^2]) ||
417 !sockeq(q->ao, &s[i^1], &q->s[R]))
9dcdc856 418 continue;
c3794524
MW
419
420 /* We win. The remaining address must be the client host. We should
421 * proxy this query.
422 */
9da480be
MW
423 q->resp = R_NAT;
424 q->u.nat = s[i^3];
9dcdc856
MW
425 goto done;
426 }
427
2a9b8d4a 428 /* Reached the end of the NAT file. */
b093b41d 429 if (ferror(natfp)) {
2a9b8d4a 430 logmsg(q, LOG_ERR, "failed to read `/proc/net/nf_conntrack': %s",
9dcdc856
MW
431 strerror(errno));
432 goto err_unk;
433 }
434 }
435
436#undef NEXTFIELD
437
c3794524 438 /* We didn't find a match anywhere. How unfortunate. */
b093b41d 439 logmsg(q, LOG_NOTICE, "connection not found");
9da480be
MW
440 q->resp = R_ERROR;
441 q->u.error = E_NOUSER;
9dcdc856 442 goto done;
c3794524 443
9dcdc856 444err_unk:
c3794524
MW
445 /* Something went wrong and the protocol can't express what. We should
446 * have logged what the problem actually was.
447 */
9da480be
MW
448 q->resp = R_ERROR;
449 q->u.error = E_UNKNOWN;
c3794524 450
9dcdc856 451done:
c3794524 452 /* All done. */
9dcdc856 453 dstr_destroy(&d);
60150b4c 454 if (fp) fclose(fp);
9dcdc856
MW
455}
456
c3794524 457/* Initialize the system-specific code. */
b093b41d
MW
458void init_sys(void)
459{
2a9b8d4a 460 if ((natfp = fopen("/proc/net/nf_conntrack", "r")) == 0 &&
b093b41d 461 errno != ENOENT) {
2a9b8d4a 462 die(1, "failed to open `/proc/net/nf_conntrack' for reading: %s",
b093b41d
MW
463 strerror(errno));
464 }
465}
466
9dcdc856 467/*----- That's all, folks -------------------------------------------------*/