chiark / gitweb /
linux.c, yaid.c, yaid.h: Open the NAT table just once at init time.
[yaid] / linux.c
1 /* -*-c-*-
2  *
3  * Discover the owner of a connection (Linux version)
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
29 #include "yaid.h"
30
31 /*----- Static variables --------------------------------------------------*/
32
33 static FILE *natfp;
34
35 /*----- Address-type operations -------------------------------------------*/
36
37 struct addrops_sys {
38   const char *procfile;
39   int (*parseaddr)(char **, union addr *);
40 };
41
42 #define PROCFILE_IPV4 "/proc/net/tcp"
43
44 static int parseaddr_ipv4(char **pp, union addr *a)
45   { a->ipv4.s_addr = strtoul(*pp, pp, 16); return (0); }
46
47 #define PROCFILE_IPV6 "/proc/net/tcp6"
48
49 static int parseaddr_ipv6(char **pp, union addr *a)
50 {
51   int i, j;
52   unsigned long y;
53   char *p = *pp;
54   unsigned x;
55
56   for (i = 0; i < 4; i++) {
57     y = 0;
58     for (j = 0; j < 8; j++) {
59       if ('0' <= *p && *p <= '9') x = *p - '0';
60       else if ('a' <= *p && *p <= 'f') x = *p - 'a'+ 10;
61       else if ('A' <= *p && *p <= 'F') x = *p - 'A'+ 10;
62       else return (-1);
63       y = (y << 4) | x;
64       p++;
65     }
66     a->ipv6.s6_addr32[i] = y;
67   }
68   *pp = p;
69   return (0);
70 }
71
72 #define DEFOPSYS(ty, TY)                                                \
73   const struct addrops_sys addrops_sys_##ty = {                         \
74     PROCFILE_##TY, parseaddr_##ty                                       \
75   };
76 ADDRTYPES(DEFOPSYS)
77 #undef DEFOPSYS
78
79 /*----- Main code ---------------------------------------------------------*/
80
81 int get_default_gw(int af, union addr *a)
82 {
83   int fd;
84   char buf[32768];
85   struct nlmsghdr *nlmsg;
86   struct rtgenmsg *rtgen;
87   const struct rtattr *rta;
88   const struct rtmsg *rtm;
89   ssize_t n, nn;
90   int rc = 0;
91   static unsigned long seq = 0x48b4aec4;
92
93   if ((fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0)
94     die(1, "failed to create netlink socket: %s", strerror(errno));
95
96   nlmsg = (struct nlmsghdr *)buf;
97   assert(NLMSG_SPACE(sizeof(*rtgen)) < sizeof(buf));
98   nlmsg->nlmsg_len = NLMSG_LENGTH(sizeof(*rtgen));
99   nlmsg->nlmsg_type = RTM_GETROUTE;
100   nlmsg->nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT;
101   nlmsg->nlmsg_seq = ++seq;
102   nlmsg->nlmsg_pid = 0;
103
104   rtgen = (struct rtgenmsg *)NLMSG_DATA(nlmsg);
105   rtgen->rtgen_family = af;
106
107   if (write(fd, nlmsg, nlmsg->nlmsg_len) < 0)
108     die(1, "failed to send RTM_GETROUTE request: %s", strerror(errno));
109
110   for (;;) {
111     if ((n = read(fd, buf, sizeof(buf))) < 0)
112       die(1, "failed to read RTM_GETROUTE response: %s", strerror(errno));
113     nlmsg = (struct nlmsghdr *)buf;
114     if (nlmsg->nlmsg_seq != seq) continue;
115     assert(nlmsg->nlmsg_flags & NLM_F_MULTI);
116
117     for (; NLMSG_OK(nlmsg, n); nlmsg = NLMSG_NEXT(nlmsg, n)) {
118       if (nlmsg->nlmsg_type == NLMSG_DONE) goto done;
119       if (nlmsg->nlmsg_type != RTM_NEWROUTE) continue;
120       rtm = (const struct rtmsg *)NLMSG_DATA(nlmsg);
121
122       if (rtm->rtm_family != af ||
123           rtm->rtm_dst_len > 0 ||
124           rtm->rtm_src_len > 0 ||
125           rtm->rtm_type != RTN_UNICAST ||
126           rtm->rtm_scope != RT_SCOPE_UNIVERSE ||
127           rtm->rtm_tos != 0)
128         continue;
129
130       for (rta = RTM_RTA(rtm), nn = RTM_PAYLOAD(nlmsg);
131            RTA_OK(rta, nn); rta = RTA_NEXT(rta, nn)) {
132         if (rta->rta_type == RTA_GATEWAY) {
133           assert(RTA_PAYLOAD(rta) <= sizeof(*a));
134           memcpy(a, RTA_DATA(rta), RTA_PAYLOAD(rta));
135           rc = 1;
136         }
137       }
138     }
139   }
140
141 done:
142   close(fd);
143   return (rc);
144 }
145
146 void identify(struct query *q)
147 {
148   FILE *fp = 0;
149   dstr d = DSTR_INIT;
150   char *p, *pp;
151   struct socket s[4];
152   int i;
153   int gwp = 0;
154   unsigned fl;
155 #define F_SADDR 1u
156 #define F_SPORT 2u
157 #define F_DADDR 4u
158 #define F_DPORT 8u
159 #define F_ALL (F_SADDR | F_SPORT | F_DADDR | F_DPORT)
160 #define F_ESTAB 16u
161   uid_t uid;
162   enum { LOC, REM, ST, UID, NFIELD };
163   int f, ff[NFIELD];
164
165   if (get_default_gw(q->ao->af, &s[0].addr) &&
166       q->ao->addreq(&s[0].addr, &q->s[R].addr))
167     gwp = 1;
168
169   if ((fp = fopen(q->ao->sys->procfile, "r")) == 0) {
170     logmsg(q, LOG_ERR, "failed to open `%s' for reading: %s",
171            q->ao->sys->procfile, strerror(errno));
172     goto err_unk;
173   }
174
175 #define NEXTFIELD do {                                                  \
176   for (p = pp; isspace((unsigned char)*p); p++);                        \
177   for (pp = p; *pp && !isspace((unsigned char)*pp); pp++);              \
178   if (*pp) *pp++ = 0;                                                   \
179 } while (0)
180
181   if (dstr_putline(&d, fp) == EOF) {
182     logmsg(q, LOG_ERR, "failed to read header line from `%s': %s",
183            q->ao->sys->procfile,
184            ferror(fp) ? strerror(errno) : "unexpected EOF");
185     goto err_unk;
186   }
187
188   for (i = 0; i < NFIELD; i++) ff[i] = -1;
189   pp = d.buf;
190   for (f = 0;; f++) {
191     NEXTFIELD; if (!*p) break;
192     if (strcmp(p, "local_address") == 0)
193       ff[LOC] = f;
194     else if (strcmp(p, "rem_address") == 0 ||
195              strcmp(p, "remote_address") == 0)
196       ff[REM] = f;
197     else if (strcmp(p, "uid") == 0)
198       ff[UID] = f;
199     else if (strcmp(p, "st") == 0)
200       ff[ST] = f;
201     else if (strcmp(p, "rx_queue") == 0 ||
202              strcmp(p, "tm->when") == 0)
203       f--;
204   }
205   for (i = 0; i < NFIELD; i++) {
206     if (ff[i] < 0) {
207       logmsg(q, LOG_ERR, "failed to find required fields in `%s'",
208              q->ao->sys->procfile);
209       goto err_unk;
210     }
211   }
212
213   for (;;) {
214     DRESET(&d);
215     if (dstr_putline(&d, fp) == EOF) break;
216     pp = d.buf;
217     uid = -1;
218     for (f = 0;; f++) {
219       NEXTFIELD; if (!*p) break;
220       if (f == ff[LOC]) { i = L; goto compare; }
221       else if (f == ff[REM]) { i = R; goto compare; }
222       else if (f == ff[UID]) uid = atoi(p);
223       else if (f == ff[ST]) {
224         if (strtol(p, 0, 16) != 1) goto next_row;
225       }
226       continue;
227
228     compare:
229       if (q->ao->sys->parseaddr(&p, &s[0].addr)) goto next_row;
230       if (*p != ':') break; p++;
231       s[0].port = strtoul(p, 0, 16);
232       if (!sockeq(q->ao, &q->s[i], &s[0]) &&
233           (i != R || !gwp || q->s[R].port != s[0].port))
234         goto next_row;
235     }
236     if (uid != -1) {
237       q->resp = R_UID;
238       q->u.uid = uid;
239       goto done;
240     }
241   next_row:;
242   }
243
244   if (ferror(fp)) {
245     logmsg(q, LOG_ERR, "failed to read connection table `%s': %s",
246            q->ao->sys->procfile, strerror(errno));
247     goto err_unk;
248   }
249
250   if (natfp && q->ao->af == AF_INET) {
251     rewind(natfp);
252
253     for (;;) {
254       DRESET(&d);
255       if (dstr_putline(&d, natfp) == EOF) break;
256       pp = d.buf;
257       NEXTFIELD; if (!*p) break;
258       if (strcmp(p, "tcp") != 0) continue;
259       i = 0;
260       fl = 0;
261       for (;;) {
262         NEXTFIELD; if (!*p) break;
263         if (strcmp(p, "ESTABLISHED") == 0)
264           fl |= F_ESTAB;
265         else if (strncmp(p, "src=", 4) == 0) {
266           inet_pton(AF_INET, p + 4, &s[i].addr);
267           fl |= F_SADDR;
268         } else if (strncmp(p, "dst=", 4) == 0) {
269           inet_pton(AF_INET, p + 4, &s[i + 1].addr);
270           fl |= F_DADDR;
271         } else if (strncmp(p, "sport=", 6) == 0) {
272           s[i].port = atoi(p + 6);
273           fl |= F_SPORT;
274         } else if (strncmp(p, "dport=", 6) == 0) {
275           s[i + 1].port = atoi(p + 6);
276           fl |= F_DPORT;
277         }
278         if ((fl & F_ALL) == F_ALL) {
279           fl &= ~F_ALL;
280           if (i < 4) i += 2;
281           else break;
282         }
283       }
284
285 #ifdef notdef
286       {
287         dstr dd = DSTR_INIT;
288         dstr_putf(&dd, "%sestab ", (fl & F_ESTAB) ? " " : "!");
289         dputsock(&dd, q->ao, &s[0]);
290         dstr_puts(&dd, "<->");
291         dputsock(&dd, q->ao, &s[1]);
292         dstr_puts(&dd, " | ");
293         dputsock(&dd, q->ao, &s[2]);
294         dstr_puts(&dd, "<->");
295         dputsock(&dd, q->ao, &s[3]);
296         printf("parsed: %s\n", dd.buf);
297         dstr_destroy(&dd);
298       }
299 #endif
300
301       if (!(fl & F_ESTAB)) continue;
302
303       for (i = 0; i < 4; i++)
304         if (sockeq(q->ao, &s[i], &q->s[L])) goto found_local;
305       continue;
306       putchar('.');
307     found_local:
308       if (!sockeq(q->ao, &s[i^1], &s[i^2]) ||
309           !sockeq(q->ao, &s[i^1], &q->s[R]))
310         continue;
311       q->resp = R_NAT;
312       q->u.nat = s[i^3];
313       goto done;
314     }
315
316     if (ferror(natfp)) {
317       logmsg(q, LOG_ERR, "failed to read `/proc/net/ip_conntrack': %s",
318              strerror(errno));
319       goto err_unk;
320     }
321   }
322
323 #undef NEXTFIELD
324
325   logmsg(q, LOG_NOTICE, "connection not found");
326   q->resp = R_ERROR;
327   q->u.error = E_NOUSER;
328   goto done;
329 err_unk:
330   q->resp = R_ERROR;
331   q->u.error = E_UNKNOWN;
332 done:
333   dstr_destroy(&d);
334   if (fp) fclose(fp);
335 }
336
337 void init_sys(void)
338 {
339   if ((natfp = fopen("/proc/net/ip_conntrack", "r")) == 0 &&
340       errno != ENOENT) {
341     die(1, "failed to open `/proc/net/ip_conntrack' for reading: %s",
342         strerror(errno));
343   }
344 }
345
346 /*----- That's all, folks -------------------------------------------------*/