xref: /netbsd-src/libexec/identd/ipf.c (revision 20e85ad185ab16980f1219a557c42e057edb42ea)
1 /* $NetBSD: ipf.c,v 1.1 2005/04/03 22:15:32 peter Exp $ */
2 
3 /*
4  * ipf.c - NAT lookup code for IP Filter.
5  *
6  * This software is in the public domain.
7  * Written by Peter Postma <peter@NetBSD.org>
8  */
9 
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/ioctl.h>
13 #include <sys/fcntl.h>
14 
15 #include <net/if.h>
16 #include <netinet/in.h>
17 #include <netinet/in_systm.h>
18 #include <netinet/ipl.h>
19 #include <netinet/ip_compat.h>
20 #include <netinet/ip_fil.h>
21 #include <netinet/ip_nat.h>
22 
23 #include <stdlib.h>
24 #include <string.h>
25 #include <syslog.h>
26 #include <unistd.h>
27 
28 #include "identd.h"
29 
30 int
31 ipf_natlookup(struct sockaddr_storage *ss, struct sockaddr *nat_addr,
32     int *nat_lport)
33 {
34 	natlookup_t nl;
35 	ipfobj_t obj;
36 	int dev;
37 
38 	(void)memset(&obj, 0, sizeof(obj));
39 	(void)memset(&nl, 0, sizeof(nl));
40 
41         /* Build the ipf object description structure. */
42 	obj.ipfo_rev = IPFILTER_VERSION;
43 	obj.ipfo_size = sizeof(nl);
44 	obj.ipfo_ptr = &nl;
45 	obj.ipfo_type = IPFOBJ_NATLOOKUP;
46 
47 	/* Build the ipf natlook structure. */
48 	switch (ss[0].ss_family) {
49 	case AF_INET:
50 		(void)memcpy(&nl.nl_realip, &satosin(&ss[0])->sin_addr,
51 		    sizeof(struct in_addr));
52 		(void)memcpy(&nl.nl_outip, &satosin(&ss[1])->sin_addr,
53 		    sizeof(struct in_addr));
54 		nl.nl_realport = ntohs(satosin(&ss[0])->sin_port);
55 		nl.nl_outport = ntohs(satosin(&ss[1])->sin_port);
56 		nl.nl_flags = IPN_TCP | IPN_IN;
57 		break;
58 	case AF_INET6:
59 		/* XXX IP Filter doesn't support IPv6 NAT yet. */
60 	default:
61 		maybe_syslog(LOG_ERR, "Unsupported protocol for NAT lookup "
62 		    "(no. %d)", ss[0].ss_family);
63 		return 0;
64 	}
65 
66 	/* Open the NAT device and do the lookup. */
67 	if ((dev = open(IPNAT_NAME, O_RDONLY)) == -1) {
68 		maybe_syslog(LOG_ERR, "Cannot open %s: %m", IPNAT_NAME);
69 		return 0;
70 	}
71 	if (ioctl(dev, SIOCGNATL, &obj) == -1) {
72 		maybe_syslog(LOG_ERR, "NAT lookup failure: %m");
73 		(void)close(dev);
74 		return 0;
75 	}
76 	(void)close(dev);
77 
78 	/*
79 	 * Put the originating address into nat_addr and fill
80 	 * the port with the ident port, 113.
81 	 */
82 	switch (ss[0].ss_family) {
83 	case AF_INET:
84 		(void)memcpy(&satosin(nat_addr)->sin_addr, &nl.nl_inip,
85 		    sizeof(struct in_addr));
86 		satosin(nat_addr)->sin_port = htons(113);
87 		satosin(nat_addr)->sin_len = sizeof(struct sockaddr_in);
88 		satosin(nat_addr)->sin_family = AF_INET;
89 		break;
90 	case AF_INET6:
91 		break;
92 	}
93 	/* Put the originating port into nat_lport. */
94 	*nat_lport = nl.nl_inport;
95 
96 	return 1;
97 }
98