]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - 6/contrib/pf/ftp-proxy/util.c
Clone Kip's Xen on stable/6 tree so that I can work on improving FreeBSD/amd64
[FreeBSD/FreeBSD.git] / 6 / contrib / pf / ftp-proxy / util.c
1 /*      $OpenBSD: util.c,v 1.19 2004/07/06 19:49:11 dhartmei Exp $ */
2
3 /*
4  * Copyright (c) 1996-2001
5  *      Obtuse Systems Corporation.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the Obtuse Systems nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE OBTUSE SYSTEMS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL OBTUSE
23  * SYSTEMS CORPORATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
24  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
28  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
30  * OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/ioctl.h>
37 #include <sys/file.h>
38 #include <netinet/in.h>
39 #include <netinet/in_systm.h>
40 #include <net/if.h>
41 #include <net/pfvar.h>
42
43 #include <arpa/inet.h>
44
45 #include <ctype.h>
46 #include <errno.h>
47 #include <netdb.h>
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <stdarg.h>
53 #include <sysexits.h>
54 #include <syslog.h>
55 #include <unistd.h>
56
57 #include "util.h"
58
59 extern int ReverseMode;
60
61 int Debug_Level;
62 int Use_Rdns;
63 in_addr_t Bind_Addr = INADDR_NONE;
64
65 void            debuglog(int debug_level, const char *fmt, ...);
66
67 void
68 debuglog(int debug_level, const char *fmt, ...)
69 {
70         va_list ap;
71         va_start(ap, fmt);
72
73         if (Debug_Level >= debug_level)
74                 vsyslog(LOG_DEBUG, fmt, ap);
75         va_end(ap);
76 }
77
78 int
79 get_proxy_env(int connected_fd, struct sockaddr_in *real_server_sa_ptr,
80     struct sockaddr_in *client_sa_ptr, struct sockaddr_in *proxy_sa_ptr)
81 {
82         struct pfioc_natlook natlook;
83         socklen_t slen;
84         int fd;
85
86         slen = sizeof(*proxy_sa_ptr);
87         if (getsockname(connected_fd, (struct sockaddr *)proxy_sa_ptr,
88             &slen) != 0) {
89                 syslog(LOG_ERR, "getsockname() failed (%m)");
90                 return(-1);
91         }
92         slen = sizeof(*client_sa_ptr);
93         if (getpeername(connected_fd, (struct sockaddr *)client_sa_ptr,
94             &slen) != 0) {
95                 syslog(LOG_ERR, "getpeername() failed (%m)");
96                 return(-1);
97         }
98
99         if (ReverseMode)
100                 return(0);
101
102         /*
103          * Build up the pf natlook structure.
104          * Just for IPv4 right now
105          */
106         memset((void *)&natlook, 0, sizeof(natlook));
107         natlook.af = AF_INET;
108         natlook.saddr.addr32[0] = client_sa_ptr->sin_addr.s_addr;
109         natlook.daddr.addr32[0] = proxy_sa_ptr->sin_addr.s_addr;
110         natlook.proto = IPPROTO_TCP;
111         natlook.sport = client_sa_ptr->sin_port;
112         natlook.dport = proxy_sa_ptr->sin_port;
113         natlook.direction = PF_OUT;
114
115         /*
116          * Open the pf device and lookup the mapping pair to find
117          * the original address we were supposed to connect to.
118          */
119         fd = open("/dev/pf", O_RDWR);
120         if (fd == -1) {
121                 syslog(LOG_ERR, "cannot open /dev/pf (%m)");
122                 exit(EX_UNAVAILABLE);
123         }
124
125         if (ioctl(fd, DIOCNATLOOK, &natlook) == -1) {
126                 syslog(LOG_INFO,
127                     "pf nat lookup failed %s:%hu (%m)",
128                     inet_ntoa(client_sa_ptr->sin_addr),
129                     ntohs(client_sa_ptr->sin_port));
130                 close(fd);
131                 return(-1);
132         }
133         close(fd);
134
135         /*
136          * Now jam the original address and port back into the into
137          * destination sockaddr_in for the proxy to deal with.
138          */
139         memset((void *)real_server_sa_ptr, 0, sizeof(struct sockaddr_in));
140         real_server_sa_ptr->sin_port = natlook.rdport;
141         real_server_sa_ptr->sin_addr.s_addr = natlook.rdaddr.addr32[0];
142         real_server_sa_ptr->sin_len = sizeof(struct sockaddr_in);
143         real_server_sa_ptr->sin_family = AF_INET;
144         return(0);
145 }
146
147
148 /*
149  * Transfer one unit of data across a pair of sockets
150  *
151  * A unit of data is as much as we get with a single read(2) call.
152  */
153 int
154 xfer_data(const char *what_read,int from_fd, int to_fd, struct in_addr from,
155     struct in_addr to)
156 {
157         int rlen, offset, xerrno, mark, flags = 0;
158         char tbuf[4096];
159
160         /*
161          * Are we at the OOB mark?
162          */
163         if (ioctl(from_fd, SIOCATMARK, &mark) < 0) {
164                 xerrno = errno;
165                 syslog(LOG_ERR, "cannot ioctl(SIOCATMARK) socket from %s (%m)",
166                     what_read);
167                 errno = xerrno;
168                 return(-1);
169         }
170         if (mark)
171                 flags = MSG_OOB;        /* Yes - at the OOB mark */
172
173 snarf:
174         rlen = recv(from_fd, tbuf, sizeof(tbuf), flags);
175         if (rlen == -1 && flags == MSG_OOB && errno == EINVAL) {
176                 /* OOB didn't work */
177                 flags = 0;
178                 rlen = recv(from_fd, tbuf, sizeof(tbuf), flags);
179         }
180         if (rlen == 0) {
181                 debuglog(3, "EOF on read socket");
182                 return(0);
183         } else if (rlen == -1) {
184                 if (errno == EAGAIN || errno == EINTR)
185                         goto snarf;
186                 xerrno = errno;
187                 syslog(LOG_ERR, "xfer_data (%s): failed (%m) with flags 0%o",
188                     what_read, flags);
189                 errno = xerrno;
190                 return(-1);
191         } else {
192                 offset = 0;
193                 debuglog(3, "got %d bytes from socket", rlen);
194
195                 while (offset < rlen) {
196                         int wlen;
197                 fling:
198                         wlen = send(to_fd, &tbuf[offset], rlen - offset,
199                             flags);
200                         if (wlen == 0) {
201                                 debuglog(3, "zero-length write");
202                                 goto fling;
203                         } else if (wlen == -1) {
204                                 if (errno == EAGAIN || errno == EINTR)
205                                         goto fling;
206                                 xerrno = errno;
207                                 syslog(LOG_INFO, "write failed (%m)");
208                                 errno = xerrno;
209                                 return(-1);
210                         } else {
211                                 debuglog(3, "wrote %d bytes to socket",wlen);
212                                 offset += wlen;
213                         }
214                 }
215                 return(offset);
216         }
217 }
218
219 /*
220  * get_backchannel_socket gets us a socket bound somewhere in a
221  * particular range of ports
222  */
223 int
224 get_backchannel_socket(int type, int min_port, int max_port, int start_port,
225     int direction, struct sockaddr_in *sap)
226 {
227         int count;
228
229         /*
230          * Make sure that direction is 'defined' and that min_port is not
231          * greater than max_port.
232          */
233         if (direction != -1)
234                 direction = 1;
235
236         /* by default we go up by one port until we find one */
237         if (min_port > max_port) {
238                 errno = EINVAL;
239                 return(-1);
240         }
241
242         count = 1 + max_port - min_port;
243
244         /*
245          * Pick a port we can bind to from within the range we want.
246          * If the caller specifies -1 as the starting port number then
247          * we pick one somewhere in the range to try.
248          * This is an optimization intended to speedup port selection and
249          * has NOTHING to do with security.
250          */
251         if (start_port == -1)
252                 start_port = (arc4random() % count) + min_port;
253
254         if (start_port < min_port || start_port > max_port) {
255                 errno = EINVAL;
256                 return(-1);
257         }
258
259         while (count-- > 0) {
260                 struct sockaddr_in sa;
261                 int one, fd;
262
263                 fd = socket(AF_INET, type, 0);
264
265                 bzero(&sa, sizeof sa);
266                 sa.sin_family = AF_INET;
267                 if (Bind_Addr == INADDR_NONE)
268                         if (sap == NULL)
269                                 sa.sin_addr.s_addr = INADDR_ANY;
270                         else
271                                 sa.sin_addr.s_addr = sap->sin_addr.s_addr;
272                 else
273                         sa.sin_addr.s_addr = Bind_Addr;
274
275                 /*
276                  * Indicate that we want to reuse a port if it happens that the
277                  * port in question was a listen port recently.
278                  */
279                 one = 1;
280                 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one,
281                     sizeof(one))  == -1)
282                         return(-1);
283
284                 sa.sin_port = htons(start_port);
285
286                 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) == 0) {
287                         if (sap != NULL)
288                                 *sap = sa;
289                         return(fd);
290                 }
291
292                 if (errno != EADDRINUSE)
293                         return(-1);
294
295                 /* if it's in use, try the next port */
296                 close(fd);
297
298                 start_port += direction;
299                 if (start_port < min_port)
300                         start_port = max_port;
301                 else if (start_port > max_port)
302                         start_port = min_port;
303         }
304         errno = EAGAIN;
305         return(-1);
306 }