3 * Discover the owner of a connection (Linux version)
5 * (c) 2012 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Yet Another Ident Daemon (YAID).
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.
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.
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.
27 /*----- Header files ------------------------------------------------------*/
31 #include <linux/netlink.h>
32 #include <linux/rtnetlink.h>
34 /*----- Static variables --------------------------------------------------*/
36 static FILE *natfp
; /* File handle for NAT table */
38 /*----- Address-type operations -------------------------------------------*/
43 int (*parseaddr
)(char **, union addr
*);
46 #define PROCFILE_IPV4 "/proc/net/tcp"
47 #define NFL3NAME_IPV4 "ipv4"
49 static int parseaddr_ipv4(char **pp
, union addr
*a
)
50 { a
->ipv4
.s_addr
= strtoul(*pp
, pp
, 16); return (0); }
52 #define PROCFILE_IPV6 "/proc/net/tcp6"
53 #define NFL3NAME_IPV6 "ipv6"
55 static int parseaddr_ipv6(char **pp
, union addr
*a
)
62 /* The format is byteswapped in a really annoying way. */
63 for (i
= 0; i
< 4; i
++) {
65 for (j
= 0; j
< 8; j
++) {
66 if ('0' <= *p
&& *p
<= '9') x
= *p
- '0';
67 else if ('a' <= *p
&& *p
<= 'f') x
= *p
- 'a'+ 10;
68 else if ('A' <= *p
&& *p
<= 'F') x
= *p
- 'A'+ 10;
73 a
->ipv6
.s6_addr32
[i
] = y
;
79 #define DEFOPSYS(ty, TY) \
80 const struct addrops_sys addrops_sys_##ty = { \
81 PROCFILE_##TY, NFL3NAME_##TY, parseaddr_##ty \
86 /*----- Main code ---------------------------------------------------------*/
88 /* Store in A the default gateway address for the given address family.
89 * Return zero on success, or nonzero on error.
91 static int get_default_gw(int af
, union addr
*a
)
95 struct nlmsghdr
*nlmsg
;
96 struct rtgenmsg
*rtgen
;
97 const struct rtattr
*rta
;
98 const struct rtmsg
*rtm
;
101 static unsigned long seq
= 0x48b4aec4;
103 /* Open a netlink socket for interrogating the kernel. */
104 if ((fd
= socket(AF_NETLINK
, SOCK_DGRAM
, NETLINK_ROUTE
)) < 0)
105 die(1, "failed to create netlink socket: %s", strerror(errno
));
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.
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;
118 rtgen
= (struct rtgenmsg
*)NLMSG_DATA(nlmsg
);
119 rtgen
->rtgen_family
= af
;
121 if (write(fd
, nlmsg
, nlmsg
->nlmsg_len
) < 0)
122 die(1, "failed to send RTM_GETROUTE request: %s", strerror(errno
));
124 /* Now we try to parse the answer. */
127 /* Not finished yet, so read another chunk of answer. */
128 if ((n
= read(fd
, buf
, sizeof(buf
))) < 0)
129 die(1, "failed to read RTM_GETROUTE response: %s", strerror(errno
));
131 /* Start at the beginning of the response. */
132 nlmsg
= (struct nlmsghdr
*)buf
;
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
138 if (nlmsg
->nlmsg_seq
!= seq
) continue;
139 assert(nlmsg
->nlmsg_flags
& NLM_F_MULTI
);
141 /* Work through all of the individual routes. */
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
);
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 */
156 /* Trundle through the attributes and find the gateway address. */
157 for (rta
= RTM_RTA(rtm
), nn
= RTM_PAYLOAD(nlmsg
);
158 RTA_OK(rta
, nn
); rta
= RTA_NEXT(rta
, nn
)) {
160 /* Got one. We're all done. Except that we should carry on reading
161 * to the end, or something bad will happen.
163 if (rta
->rta_type
== RTA_GATEWAY
) {
164 assert(RTA_PAYLOAD(rta
) <= sizeof(*a
));
165 memcpy(a
, RTA_DATA(rta
), RTA_PAYLOAD(rta
));
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
181 void identify(struct query
*q
)
194 #define F_ALL (F_SADDR | F_SPORT | F_DADDR | F_DPORT)
197 enum { LOC
, REM
, ST
, UID
, NFIELD
};
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.
204 if (get_default_gw(q
->ao
->af
, &s
[0].addr
) &&
205 q
->ao
->addreq(&s
[0].addr
, &q
->s
[R
].addr
))
208 /* Open the relevant TCP connection table. */
209 if ((fp
= fopen(q
->ao
->sys
->procfile
, "r")) == 0) {
210 logmsg(q
, LOG_ERR
, "failed to open `%s' for reading: %s",
211 q
->ao
->sys
->procfile
, strerror(errno
));
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.
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; \
225 /* Read the header line from the file. */
226 if (dstr_putline(&d
, fp
) == EOF
) {
227 logmsg(q
, LOG_ERR
, "failed to read header line from `%s': %s",
228 q
->ao
->sys
->procfile
,
229 ferror(fp
) ?
strerror(errno
) : "unexpected EOF");
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.
240 for (i
= 0; i
< NFIELD
; i
++) ff
[i
] = -1;
243 NEXTFIELD
; if (!*p
) break;
244 if (strcmp(p
, "local_address") == 0)
246 else if (strcmp(p
, "rem_address") == 0 ||
247 strcmp(p
, "remote_address") == 0)
249 else if (strcmp(p
, "uid") == 0)
251 else if (strcmp(p
, "st") == 0)
253 else if (strcmp(p
, "rx_queue") == 0 ||
254 strcmp(p
, "tm->when") == 0)
258 /* Make sure that we found all of the fields we actually want. */
259 for (i
= 0; i
< NFIELD
; i
++) {
261 logmsg(q
, LOG_ERR
, "failed to find required fields in `%s'",
262 q
->ao
->sys
->procfile
);
267 /* Work through the lines in the file. */
270 /* Read a line, and prepare to scan the fields. */
272 if (dstr_putline(&d
, fp
) == EOF
) break;
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.
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
;
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).
299 if (q
->ao
->sys
->parseaddr(&p
, &s
[0].addr
)) goto next_row
;
300 if (*p
!= ':') break; p
++;
301 s
[0].port
= strtoul(p
, 0, 16);
302 if ((i
== R
&& gwp
) ?
303 q
->s
[R
].port
!= s
[0].port
:
304 !sockeq(q
->ao
, &q
->s
[i
], &s
[0]))
308 /* We got to the end, and everything matched. If we found a UID then
319 /* We got to the end of the file and didn't find anything. */
321 logmsg(q
, LOG_ERR
, "failed to read connection table `%s': %s",
322 q
->ao
->sys
->procfile
, strerror(errno
));
326 /* If we opened the NAT table file, and we're using IPv4, then check to see
327 * whether we should proxy the connection. At least the addresses in this
332 /* Start again from the beginning. */
335 /* Read a line at a time. */
340 if (dstr_putline(&d
, natfp
) == EOF
) break;
343 /* Check that this is for the right protocol. */
344 NEXTFIELD
; if (!*p
) break;
345 if (strcmp(p
, q
->ao
->sys
->nfl3name
)) continue;
346 NEXTFIELD
; if (!*p
) break;
347 NEXTFIELD
; if (!*p
) break;
348 if (strcmp(p
, "tcp") != 0) continue;
350 /* Parse the other fields. Each line has two src/dst pairs, for the
351 * outgoing and incoming directions. Depending on exactly what kind of
352 * NAT is in use, either the outgoing source or the incoming
353 * destination might be the client we're after. Collect all of the
354 * addresses and sort out the mess later.
359 NEXTFIELD
; if (!*p
) break;
360 if (strcmp(p
, "ESTABLISHED") == 0)
362 else if (strncmp(p
, "src=", 4) == 0) {
363 inet_pton(q
->ao
->af
, p
+ 4, &s
[i
].addr
);
365 } else if (strncmp(p
, "dst=", 4) == 0) {
366 inet_pton(q
->ao
->af
, p
+ 4, &s
[i
+ 1].addr
);
368 } else if (strncmp(p
, "sport=", 6) == 0) {
369 s
[i
].port
= atoi(p
+ 6);
371 } else if (strncmp(p
, "dport=", 6) == 0) {
372 s
[i
+ 1].port
= atoi(p
+ 6);
375 if ((fl
& F_ALL
) == F_ALL
) {
384 /* Print the record we found. */
386 dstr_putf(&dd
, "%sestab ", (fl
& F_ESTAB
) ?
" " : "!");
387 dputsock(&dd
, q
->ao
, &s
[0]);
388 dstr_puts(&dd
, "<->");
389 dputsock(&dd
, q
->ao
, &s
[1]);
390 dstr_puts(&dd
, " | ");
391 dputsock(&dd
, q
->ao
, &s
[2]);
392 dstr_puts(&dd
, "<->");
393 dputsock(&dd
, q
->ao
, &s
[3]);
394 printf("parsed: %s\n", dd
.buf
);
399 /* If the connection isn't ESTABLISHED then skip it. */
400 if (!(fl
& F_ESTAB
)) continue;
402 /* Now we try to piece together what's going on. One of these
403 * addresses will be us. So let's just try to find it.
405 for (i
= 0; i
< 4; i
++)
406 if (sockeq(q
->ao
, &s
[i
], &q
->s
[L
])) goto found_local
;
410 /* So address `i' is us. In that case, we expect the other address in
411 * the same direction, and the same address in the opposite direction,
412 * to match each other and be the remote address in the query.
414 if (!sockeq(q
->ao
, &s
[i
^1], &s
[i
^2]) ||
415 !sockeq(q
->ao
, &s
[i
^1], &q
->s
[R
]))
418 /* We win. The remaining address must be the client host. We should
426 /* Reached the end of the NAT file. */
428 logmsg(q
, LOG_ERR
, "failed to read `/proc/net/nf_conntrack': %s",
436 /* We didn't find a match anywhere. How unfortunate. */
437 logmsg(q
, LOG_NOTICE
, "connection not found");
439 q
->u
.error
= E_NOUSER
;
443 /* Something went wrong and the protocol can't express what. We should
444 * have logged what the problem actually was.
447 q
->u
.error
= E_UNKNOWN
;
455 /* Initialize the system-specific code. */
458 if ((natfp
= fopen("/proc/net/nf_conntrack", "r")) == 0 &&
460 die(1, "failed to open `/proc/net/nf_conntrack' for reading: %s",
465 /*----- That's all, folks -------------------------------------------------*/