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