From 847b25f6aa865967d0b118c0fe1082cd6b47b352 Mon Sep 17 00:00:00 2001 From: "Kyle J. McKay" Date: Tue, 20 Sep 2016 22:25:36 -0700 Subject: [PATCH] chroot: add DragonFly BSD support The support is basically the same as the FreeBSD support except that DragonFly BSD uses devfsctl to modify devfs mounts and there's no system-provided devfs ruleset for chroots so we must provide one. Additionally, DragonFly BSD does not have any netcat port available with support for the -U option. This is a problem even for non-chroot installations of Girocco. Therefore we provide src/dragonfly with a suitable (OpenBSD) version of netcat (nc.openbsd) for DragonFly BSD.o Various comments are added to note the new additions and subtle differences (such as the loopback fs type being null instead of nullfs). Signed-off-by: Kyle J. McKay --- Girocco/Config.pm | 1 + chrootsetup_dragonfly.sh | 122 ++++++ fstab/devfsctl_chroot_ruleset | 27 ++ fstab/fstab.girocco | 7 +- jailsetup.sh | 2 + src/dragonfly/Makefile | 31 ++ src/dragonfly/README | 18 + src/dragonfly/atomicio.c | 64 +++ src/dragonfly/atomicio.h | 33 ++ src/dragonfly/nc.1 | 392 +++++++++++++++++++ src/dragonfly/netcat.c | 891 ++++++++++++++++++++++++++++++++++++++++++ src/dragonfly/socks.c | 270 +++++++++++++ 12 files changed, 1857 insertions(+), 1 deletion(-) create mode 100644 chrootsetup_dragonfly.sh create mode 100644 fstab/devfsctl_chroot_ruleset create mode 100644 src/dragonfly/Makefile create mode 100644 src/dragonfly/README create mode 100644 src/dragonfly/atomicio.c create mode 100644 src/dragonfly/atomicio.h create mode 100644 src/dragonfly/nc.1 create mode 100644 src/dragonfly/netcat.c create mode 100644 src/dragonfly/socks.c diff --git a/Girocco/Config.pm b/Girocco/Config.pm index 469bc3e..46e91dd 100644 --- a/Girocco/Config.pm +++ b/Girocco/Config.pm @@ -38,6 +38,7 @@ our $git_http_backend_bin = undef; # Name (if in $PATH) or full path to netcat executable that accepts a -U option # to connect to a unix socket. This may simply be 'nc' on many systems. +# See the ../src/dragonfly/README file for a DragonFly BSD nc with -U support. our $nc_openbsd_bin = 'nc.openbsd'; # Path to POSIX sh executable to use. Set to undef to use /bin/sh diff --git a/chrootsetup_dragonfly.sh b/chrootsetup_dragonfly.sh new file mode 100644 index 0000000..e9bac5a --- /dev/null +++ b/chrootsetup_dragonfly.sh @@ -0,0 +1,122 @@ +# chrootsetup_dragonfly.sh + +# This file SHOULD NOT be executable! It is sourced by jailsetup.sh and +# SHOULD NOT be executed directly! + +# On entry the current directory will be set to the top of the chroot +# This script must perform platform-specific chroot setup which includes +# creating any dev device entries, setting up proc (if needed), setting +# up lib64 (if needed) as well as installing a basic set of whatever libraries +# are needed for a chroot to function on this platform. + +# This script must also define a pull_in_bin function that may be called to +# install an executable together with any libraries it depends on into the +# chroot. + +# Finally this script must install a suitable nc.openbsd compatible version of +# netcat into the chroot jail that's available as nc.openbsd and which supports +# connects to unix sockets. + +# We are designed to set up the chroot based on binaries from +# x86_64 DragonFly BSD 4.4; some things may need slight modifications if +# being run on a different distribution. + +# We require update_pwd_db to be set to work properly on DragonFly BSD +[ -n "$cfg_update_pwd_db" -a "$cfg_update_pwd_db" != "0" ] || { + echo 'error: Config.pm must set $update_pwd_db to 1 to use a DragonFly BSD jail' >&2 + exit 1 +} + +chroot_dir="`pwd`" + +mkdir -p dev proc +chown 0:0 dev proc + +# Extra directories +mkdir -p libexec var/tmp + +# Install the devfsctl chroot ruleset +rm -f etc/devfs.conf +cat "$curdir/fstab/devfsctl_chroot_ruleset" > etc/devfs.conf +chown 0:0 etc/devfs.conf +chmod 0444 etc/devfs.conf + +cp_p() { + # use cpio to avoid setting flags + # must NOT use passthrough mode as that will set flags on newer systems + (cd "$(dirname "$1")" && echo "$(basename "$1")" | \ + cpio -o -L 2>/dev/null| { cd "$chroot_dir/${2%/*}" && cpio -i -m -u; } 2>/dev/null) + if [ "${2%/*}" != "${2%/}" ]; then + mv -f "$chroot_dir/${2%/*}/$(basename "$1")" \ + "$chroot_dir/${2%/*}/$(basename "$2")" + fi +} + +# Bring in basic libraries: +rm -f lib/* libexec/* +# ld-elf.so.2: +cp_p /libexec/ld-elf.so.2 libexec + +pull_in_lib() { + [ -f "$1" ] || return + dst="${2%/}/$(basename "$1")" + if [ ! -e "$dst" ] || [ "$1" -nt "$dst" ]; then + cp_p "$1" "$dst" + for llib in $(ldd "$1" | grep '=>' | awk '{print $3}'); do + (pull_in_lib "$llib" lib) + done + fi + +} + +# pull_in_bin takes two arguments: +# 1: the full path to a binary to pull in (together with any library dependencies) +# 2: the destination directory relative to the current directory to copy it to which +# MUST already exist with optional alternate name if the name in the chroot should be different +# 3: optional name of binary that if already in $2 and the same as $1 hard link to instead +# for example, "pull_in_bin /bin/sh bin" will install the shell into the chroot bin directory +# for example, "pull_in_bin /bin/bash bin/sh" will install bash as the chroot bin/sh +# IMPORTANT: argument 1 must be a machine binary, NOT a shell script or other interpreted text +# IMPORTANT: text scripts can simply be copied in or installed as they don't have libraries to copy +# NOTE: it's expected that calling this function on a running chroot may cause temporary disruption +# In order to avoid a busy error while replacing binaries we first copy the binary to the +# var/tmp directory and then force move it into place after the libs have been brought in. +pull_in_bin() { + bin="$1"; bdst="$2" + if [ -d "${bdst%/}" ]; then + bnam="$(basename "$bin")" + bdst="${bdst%/}" + else + bnam="$(basename "$bdst")" + bdst="${bdst%/*}" + fi + if [ -n "$3" ] && [ "$3" != "$bnam" ] && \ + [ -r "$bdst/$3" -a -x "$bdst/$3" ] && cmp -s "$bin" "$bdst/$3"; then + ln -f "$bdst/$3" "$bdst/$bnam" + return 0 + fi + cp_p "$bin" var/tmp + # ...and all the dependencies. + for lib in $(ldd "$bin" | grep '=>' | awk '{print $3}'); do + pull_in_lib "$lib" lib + done + mv -f "var/tmp/$(basename "$bin")" "$bdst/$bnam" +} + +# A catch all that needs to be called after everything's been pulled in +chroot_update_permissions() { + # Be paranoid + [ -n "$chroot_dir" -a "$chroot_dir" != "/" ] || { echo bad '$chroot_dir' >&2; exit 2; } + cd "$chroot_dir" || { echo bad '$chroot_dir' >&2; exit 2; } + rm -rf var/tmp + chown -R 0:0 bin lib sbin var libexec + # bootstrap the master.passwd database + rm -f etc/master.passwd etc/pwd.db etc/spwd.db + awk -F ':' '{ print $1 ":" $2 ":" $3 ":" $4 "::0:0:" $5 ":" $6 ":" $7 }' < etc/passwd > etc/master.passwd + PW_SCAN_BIG_IDS=1 pwd_mkdb -d etc etc/master.passwd 2>/dev/null + chown $cfg_mirror_user:$cfg_owning_group etc/master.passwd etc/pwd.db etc/spwd.db + chmod 0664 etc/master.passwd etc/pwd.db etc/spwd.db +} + +# the nc.openbsd compatible utility is available as $Girocco::Config::nc_openbsd_bin +pull_in_bin "$(command -v "$cfg_nc_openbsd_bin")" bin/nc.openbsd diff --git a/fstab/devfsctl_chroot_ruleset b/fstab/devfsctl_chroot_ruleset new file mode 100644 index 0000000..b013571 --- /dev/null +++ b/fstab/devfsctl_chroot_ruleset @@ -0,0 +1,27 @@ +# devfsctl ruleset suitable for chroot devfs mount +# (devfsctl is DragonFly BSD specific) + +# This ruleset can be applied to a /dev mount +# of the devfs filesystem like so: +# +# devfsctl -c -m /dev +# devfsctl -r -m /dev +# devfsctl -a -f -m /dev +# +# Note that this file MUST be owned by root or devfsctl will fail. +# +# For that reason it's most convenient if the chroot creation script +# installs this file to /etc/devfs.conf with chown 0:0 and +# chmod 0444 for easy access when running the devfsctl commands. + +group devs null zero crypto random urandom +group pty1 ptyl* ptym* ptyn* ptyo* ptyL* ptyM* ptyN* ptyO* +group pty2 ptyp* ptyq* ptyr* ptys* ptyP* pytQ* pytR* ptyS* +group tty1 ttyl* ttym* ttyn* ttyo* ttyL* ttyM* ttyN* ttyO* +group tty2 ttyp* ttyq* ttyr* ttys* ttyP* ttyQ* ttyR* ttyS* +group pttys @pty1 @pty2 @tty1 @tty2 ptmx pts pts/* +group fds fd fd/* stdin stdout stderr +group chroot @devs @pttys @fds + +hide * +show @chroot diff --git a/fstab/fstab.girocco b/fstab/fstab.girocco index 91b0f9c..2e4115a 100644 --- a/fstab/fstab.girocco +++ b/fstab/fstab.girocco @@ -16,6 +16,7 @@ # mount the git repositories in the jail # Note that on FreeBSD a "bind" mount is accomplished by setting the type to # nullfs and the options to rw as FreeBSD does not have a mount --bind option +# Note that DragonFly BSD is the same as FreeBSD except the type should be null /srv/git /home/repo/j/srv/git none bind 0 0 # mount the proc filesystem in the jail @@ -32,9 +33,13 @@ proc /home/repo/j/proc proc nodev,noexec,nosuid 0 0 # mount the devfs filesystem in the jail # Note that this is only necessary on systems where mknod does not work -# except on devfs mounts (e.g. FreeBSD) +# except on devfs mounts (e.g. FreeBSD, DragonFly BSD) # Note that on FreeBSD before starting the chroot, the following commands # may be executed to reduce the number of exposed devices: # devfs -m /home/repo/j/dev ruleset 4 # devfs -m /home/repo/j/dev rule applyset +# Note that on DragonFly BSD before starting the chroot, the devsfctl +# commands shown in the devfsctl_chroot_ruleset file (which will be +# automatically installed to $Girocco::Config::chroot/etc/devfs.conf) +# may be executed to reduce the number of devices exposed in the chroot. #devfs /home/repo/j/dev devfs rw,noexec,nosuid 0 0 diff --git a/jailsetup.sh b/jailsetup.sh index 49c8f11..e36c270 100755 --- a/jailsetup.sh +++ b/jailsetup.sh @@ -200,6 +200,8 @@ case "$sysname" in sysname=linux;; *darwin*) sysname=darwin;; + *dragonfly*) + sysname=dragonfly;; *freebsd*) sysname=freebsd;; *linux*) diff --git a/src/dragonfly/Makefile b/src/dragonfly/Makefile new file mode 100644 index 0000000..ed1998b --- /dev/null +++ b/src/dragonfly/Makefile @@ -0,0 +1,31 @@ +.PHONY : all clean install + +CC ?= cc +CFLAGS ?= -g -O + +all : nc.openbsd nc.openbsd.1.gz + +clean : + rm -f atomicio.o* socks.o* nc.o* nc.openbsd nc.openbsd.1.gz + rm -rf atomicio.d* socks.d* nc.d* + +atomicio.o : atomicio.c atomicio.h + $(CC) $(CFLAGS) -c -o $@ $*.c + +socks.o : socks.c atomicio.h + $(CC) $(CFLAGS) -c -o $@ $*.c + +nc.o : netcat.c atomicio.h + $(CC) $(CFLAGS) -c -o $@ netcat.c + +nc.openbsd : nc.o socks.o atomicio.o + $(CC) $(CFLAGS) -o $@ nc.o socks.o atomicio.o + +nc.openbsd.1.gz : nc.1 + gzip -n -9 < nc.1 > nc.openbsd.1.gz + +install : all + install -d /usr/local/bin + install -m 555 -s nc.openbsd /usr/local/bin/nc.openbsd + install -d /usr/local/man/man1 + install -m 444 nc.openbsd.1.gz /usr/local/man/man1/nc.openbsd.1.gz diff --git a/src/dragonfly/README b/src/dragonfly/README new file mode 100644 index 0000000..17e7712 --- /dev/null +++ b/src/dragonfly/README @@ -0,0 +1,18 @@ +This directory contains a 3-clause BSD licensed version of +the OpenBSD netcat utility that supports the -U (unix socket) +option. See the netcat.c source file for the license text. + +Running "make" and then "sudo make install" will install the +/usr/local/bin/nc.openbsd and /usr/local/man/man1/nc.openbsd.1.gz +files at which point nc.openbsd can be used immediately afterwards. + +Web Site: + +CVS: + cvs -d :ext:anoncvs@anoncvs1.usa.openbsd.org:/cvs co src/usr.bin/nc + +Sources fetched 2005-10-07. + +Modifications: + The -S and -j options are disabled for __DragonFly__ because they are + not supported on DragonFly BSD. diff --git a/src/dragonfly/atomicio.c b/src/dragonfly/atomicio.c new file mode 100644 index 0000000..dfd6632 --- /dev/null +++ b/src/dragonfly/atomicio.c @@ -0,0 +1,64 @@ +/* $OpenBSD: atomicio.c,v 1.7 2005/05/26 01:01:08 avsm Exp $ */ + +/* + * Copyright (c) 2005 Anil Madhavapeddy. All rights served. + * Copyright (c) 1995,1999 Theo de Raadt. All rights reserved. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "atomicio.h" + +/* + * ensure all of data on socket comes through. f==read || f==vwrite + */ +size_t +atomicio(f, fd, _s, n) + ssize_t (*f) (int, void *, size_t); + int fd; + void *_s; + size_t n; +{ + char *s = _s; + size_t pos = 0; + ssize_t res; + + while (n > pos) { + res = (f) (fd, s + pos, n - pos); + switch (res) { + case -1: + if (errno == EINTR || errno == EAGAIN) + continue; + return 0; + case 0: + errno = EPIPE; + return pos; + default: + pos += (u_int)res; + } + } + return pos; +} diff --git a/src/dragonfly/atomicio.h b/src/dragonfly/atomicio.h new file mode 100644 index 0000000..551a056 --- /dev/null +++ b/src/dragonfly/atomicio.h @@ -0,0 +1,33 @@ +/* $OpenBSD: atomicio.h,v 1.1 2005/05/24 20:13:28 avsm Exp $ */ + +/* + * Copyright (c) 1995,1999 Theo de Raadt. All rights reserved. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Ensure all of data on socket comes through. f==read || f==vwrite + */ +size_t atomicio(ssize_t (*)(int, void *, size_t), int, void *, size_t); + +#define vwrite (ssize_t (*)(int, void *, size_t))write diff --git a/src/dragonfly/nc.1 b/src/dragonfly/nc.1 new file mode 100644 index 0000000..1d2fed6 --- /dev/null +++ b/src/dragonfly/nc.1 @@ -0,0 +1,392 @@ +.\" $OpenBSD: nc.1,v 1.40 2005/07/17 19:18:47 jmc Exp $ +.\" +.\" Copyright (c) 1996 David Sacerdote +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" 3. The name of the author may not be used to endorse or promote products +.\" derived from this software without specific prior written permission +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +.\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +.\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +.\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +.\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +.\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +.\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +.\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +.\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +.\" +.Dd June 25, 2001 +.Dt NC 1 +.Os +.Sh NAME +.Nm nc +.Nd arbitrary TCP and UDP connections and listens +.Sh SYNOPSIS +.Nm nc +.Bk -words +.Op Fl 46DdhklnrtUuvz +.Op Fl i Ar interval +.Op Fl p Ar source_port +.Op Fl s Ar source_ip_address +.Op Fl w Ar timeout +.Op Fl X Ar proxy_protocol +.Oo Xo +.Fl x Ar proxy_address Ns Oo : Ns +.Ar port Oc Oc +.Xc +.Op Ar hostname +.Op Ar port Ns Bq Ar s +.Ek +.Sh DESCRIPTION +The +.Nm +(or +.Nm netcat ) +utility is used for just about anything under the sun involving TCP +or UDP. +It can open TCP connections, send UDP packets, listen on arbitrary +TCP and UDP ports, do port scanning, and deal with both IPv4 and +IPv6. +Unlike +.Xr telnet 1 , +.Nm +scripts nicely, and separates error messages onto standard error instead +of sending them to standard output, as +.Xr telnet 1 +does with some. +.Pp +Common uses include: +.Pp +.Bl -bullet -offset indent -compact +.It +simple TCP proxies +.It +shell-script based HTTP clients and servers +.It +network daemon testing +.It +a SOCKS or HTTP ProxyCommand for +.Xr ssh 1 +.It +and much, much more +.El +.Pp +The options are as follows: +.Bl -tag -width Ds +.It Fl 4 +Forces +.Nm +to use IPv4 addresses only. +.It Fl 6 +Forces +.Nm +to use IPv6 addresses only. +.It Fl D +Enable debugging on the socket. +.It Fl d +Do not attempt to read from stdin. +.It Fl h +Prints out +.Nm +help. +.It Fl i Ar interval +Specifies a delay time interval between lines of text sent and received. +Also causes a delay time between connections to multiple ports. +.It Fl k +Forces +.Nm +to stay listening for another connection after its current connection +is completed. +It is an error to use this option without the +.Fl l +option. +.It Fl l +Used to specify that +.Nm +should listen for an incoming connection rather than initiate a +connection to a remote host. +It is an error to use this option in conjunction with the +.Fl p , +.Fl s , +or +.Fl z +options. +Additionally, any timeouts specified with the +.Fl w +option are ignored. +.It Fl n +Do not do any DNS or service lookups on any specified addresses, +hostnames or ports. +.It Fl p Ar source_port +Specifies the source port +.Nm +should use, subject to privilege restrictions and availability. +It is an error to use this option in conjunction with the +.Fl l +option. +.It Fl r +Specifies that source and/or destination ports should be chosen randomly +instead of sequentially within a range or in the order that the system +assigns them. +.It Fl s Ar source_ip_address +Specifies the IP of the interface which is used to send the packets. +It is an error to use this option in conjunction with the +.Fl l +option. +.It Fl t +Causes +.Nm +to send RFC 854 DON'T and WON'T responses to RFC 854 DO and WILL requests. +This makes it possible to use +.Nm +to script telnet sessions. +.It Fl U +Specifies to use Unix Domain Sockets. +.It Fl u +Use UDP instead of the default option of TCP. +.It Fl v +Have +.Nm +give more verbose output. +.It Fl w Ar timeout +If a connection and stdin are idle for more than +.Ar timeout +seconds, then the connection is silently closed. +The +.Fl w +flag has no effect on the +.Fl l +option, i.e.\& +.Nm +will listen forever for a connection, with or without the +.Fl w +flag. +The default is no timeout. +.It Fl X Ar proxy_version +Requests that +.Nm +should use the specified protocol when talking to the proxy server. +Supported protocols are +.Dq 4 +(SOCKS v.4), +.Dq 5 +(SOCKS v.5) +and +.Dq connect +(HTTPS proxy). +If the protocol is not specified, SOCKS version 5 is used. +.It Xo +.Fl x Ar proxy_address Ns Oo : Ns +.Ar port Oc +.Xc +Requests that +.Nm +should connect to +.Ar hostname +using a proxy at +.Ar proxy_address +and +.Ar port . +If +.Ar port +is not specified, the well-known port for the proxy protocol is used (1080 +for SOCKS, 3128 for HTTPS). +.It Fl z +Specifies that +.Nm +should just scan for listening daemons, without sending any data to them. +It is an error to use this option in conjunction with the +.Fl l +option. +.El +.Pp +.Ar hostname +can be a numerical IP address or a symbolic hostname +(unless the +.Fl n +option is given). +In general, a hostname must be specified, +unless the +.Fl l +option is given +(in which case the local host is used). +.Pp +.Ar port Ns Op Ar s +can be single integers or ranges. +Ranges are in the form nn-mm. +In general, +a destination port must be specified, +unless the +.Fl U +option is given +(in which case a socket must be specified). +.Sh CLIENT/SERVER MODEL +It is quite simple to build a very basic client/server model using +.Nm . +On one console, start +.Nm +listening on a specific port for a connection. +For example: +.Pp +.Dl $ nc -l 1234 +.Pp +.Nm +is now listening on port 1234 for a connection. +On a second console +.Pq or a second machine , +connect to the machine and port being listened on: +.Pp +.Dl $ nc 127.0.0.1 1234 +.Pp +There should now be a connection between the ports. +Anything typed at the second console will be concatenated to the first, +and vice-versa. +After the connection has been set up, +.Nm +does not really care which side is being used as a +.Sq server +and which side is being used as a +.Sq client . +The connection may be terminated using an +.Dv EOF +.Pq Sq ^D . +.Sh DATA TRANSFER +The example in the previous section can be expanded to build a +basic data transfer model. +Any information input into one end of the connection will be output +to the other end, and input and output can be easily captured in order to +emulate file transfer. +.Pp +Start by using +.Nm +to listen on a specific port, with output captured into a file: +.Pp +.Dl $ nc -l 1234 \*(Gt filename.out +.Pp +Using a second machine, connect to the listening +.Nm +process, feeding it the file which is to be transferred: +.Pp +.Dl $ nc host.example.com 1234 \*(Lt filename.in +.Pp +After the file has been transferred, the connection will close automatically. +.Sh TALKING TO SERVERS +It is sometimes useful to talk to servers +.Dq by hand +rather than through a user interface. +It can aid in troubleshooting, +when it might be necessary to verify what data a server is sending +in response to commands issued by the client. +For example, to retrieve the home page of a web site: +.Bd -literal -offset indent +$ echo -n "GET / HTTP/1.0\er\en\er\en" | nc host.example.com 80 +.Ed +.Pp +Note that this also displays the headers sent by the web server. +They can be filtered, using a tool such as +.Xr sed 1 , +if necessary. +.Pp +More complicated examples can be built up when the user knows the format +of requests required by the server. +As another example, an email may be submitted to an SMTP server using: +.Bd -literal -offset indent +$ nc localhost 25 \*(Lt\*(Lt EOF +HELO host.example.com +MAIL FROM: \*(Ltuser@host.example.com\*(Gt +RCPT TO: \*(Ltuser2@host.example.com\*(Gt +DATA +Body of email. +\&. +QUIT +EOF +.Ed +.Sh PORT SCANNING +It may be useful to know which ports are open and running services on +a target machine. +The +.Fl z +flag can be used to tell +.Nm +to report open ports, +rather than initiate a connection. +For example: +.Bd -literal -offset indent +$ nc -z host.example.com 20-30 +Connection to host.example.com 22 port [tcp/ssh] succeeded! +Connection to host.example.com 25 port [tcp/smtp] succeeded! +.Ed +.Pp +The port range was specified to limit the search to ports 20 \- 30. +.Pp +Alternatively, it might be useful to know which server software +is running, and which versions. +This information is often contained within the greeting banners. +In order to retrieve these, it is necessary to first make a connection, +and then break the connection when the banner has been retrieved. +This can be accomplished by specifying a small timeout with the +.Fl w +flag, or perhaps by issuing a +.Qq Dv QUIT +command to the server: +.Bd -literal -offset indent +$ echo "QUIT" | nc host.example.com 20-30 +SSH-1.99-OpenSSH_3.6.1p2 +Protocol mismatch. +220 host.example.com IMS SMTP Receiver Version 0.84 Ready +.Ed +.Sh EXAMPLES +Open a TCP connection to port 42 of host.example.com, using port 31337 as +the source port, with a timeout of 5 seconds: +.Pp +.Dl $ nc -p 31337 -w 5 host.example.com 42 +.Pp +Open a UDP connection to port 53 of host.example.com: +.Pp +.Dl $ nc -u host.example.com 53 +.Pp +Open a TCP connection to port 42 of host.example.com using 10.1.2.3 as the +IP for the local end of the connection: +.Pp +.Dl $ nc -s 10.1.2.3 host.example.com 42 +.Pp +Create and listen on a Unix Domain Socket: +.Pp +.Dl $ nc -lU /var/tmp/dsocket +.Pp +Connect to port 42 of host.example.com via an HTTP proxy at 10.2.3.4, +port 8080. +This example could also be used by +.Xr ssh 1 ; +see the +.Cm ProxyCommand +directive in +.Xr ssh_config 5 +for more information. +.Pp +.Dl $ nc -x10.2.3.4:8080 -Xconnect host.example.com 42 +.Sh SEE ALSO +.Xr cat 1 , +.Xr ssh 1 +.Sh AUTHORS +Original implementation by *Hobbit* +.Aq hobbit@avian.org . +.br +Rewritten with IPv6 support by +.An Eric Jackson Aq ericj@monkey.org . +.Sh CAVEATS +UDP port scans will always succeed +(i.e. report the port as open), +rendering the +.Fl uz +combination of flags relatively useless. diff --git a/src/dragonfly/netcat.c b/src/dragonfly/netcat.c new file mode 100644 index 0000000..3d5cf0a --- /dev/null +++ b/src/dragonfly/netcat.c @@ -0,0 +1,891 @@ +/* $OpenBSD: netcat.c,v 1.82 2005/07/24 09:33:56 marius Exp $ */ +/* + * Copyright (c) 2001 Eric Jackson + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Re-written nc(1) for OpenBSD. Original implementation by + * *Hobbit* . + */ + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#ifdef __DragonFly__ +#include +#endif /* __DragonFly__ */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "atomicio.h" + +#ifndef SUN_LEN +#define SUN_LEN(su) \ + (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path)) +#endif + +#define PORT_MAX 65535 +#define PORT_MAX_LEN 6 + +/* Command Line Options */ +int dflag; /* detached, no stdin */ +int iflag; /* Interval Flag */ +#ifndef __DragonFly__ +int jflag; /* use jumbo frames if we can */ +#endif /* !__DragonFly__ */ +int kflag; /* More than one connect */ +int lflag; /* Bind to local port */ +int nflag; /* Don't do name look up */ +char *pflag; /* Localport flag */ +int rflag; /* Random ports flag */ +char *sflag; /* Source Address */ +int tflag; /* Telnet Emulation */ +int uflag; /* UDP - Default to TCP */ +int vflag; /* Verbosity */ +int xflag; /* Socks proxy */ +int zflag; /* Port Scan Flag */ +int Dflag; /* sodebug */ +#ifndef __DragonFly__ +int Sflag; /* TCP MD5 signature option */ +#endif /* !__DragonFly__ */ + +int timeout = -1; +int family = AF_UNSPEC; +char *portlist[PORT_MAX+1]; + +void atelnet(int, unsigned char *, unsigned int); +void build_ports(char *); +void help(void); +int local_listen(char *, char *, struct addrinfo); +void readwrite(int); +int remote_connect(const char *, const char *, struct addrinfo); +int socks_connect(const char *, const char *, struct addrinfo, const char *, const char *, + struct addrinfo, int); +int udptest(int); +int unix_connect(char *); +int unix_listen(char *); +int set_common_sockopts(int); +void usage(int); + +int +main(int argc, char *argv[]) +{ + int ch, s, ret, socksv; + char *host, *uport, *endp; + struct addrinfo hints; + struct servent *sv; + socklen_t len; + struct sockaddr_storage cliaddr; + char *proxy; + const char *proxyhost = "", *proxyport = NULL; + struct addrinfo proxyhints; + + ret = 1; + s = 0; + socksv = 5; + host = NULL; + uport = NULL; + endp = NULL; + sv = NULL; + + while ((ch = getopt(argc, argv, + "46Ddhi:jklnp:rSs:tUuvw:X:x:z")) != -1) { + switch (ch) { + case '4': + family = AF_INET; + break; + case '6': + family = AF_INET6; + break; + case 'U': + family = AF_UNIX; + break; + case 'X': + if (strcasecmp(optarg, "connect") == 0) + socksv = -1; /* HTTP proxy CONNECT */ + else if (strcmp(optarg, "4") == 0) + socksv = 4; /* SOCKS v.4 */ + else if (strcmp(optarg, "5") == 0) + socksv = 5; /* SOCKS v.5 */ + else + errx(1, "unsupported proxy protocol"); + break; + case 'd': + dflag = 1; + break; + case 'h': + help(); + break; + case 'i': + iflag = (int)strtoul(optarg, &endp, 10); + if (iflag < 0 || *endp != '\0') + errx(1, "interval cannot be negative"); + break; +#ifndef __DragonFly__ + case 'j': + jflag = 1; + break; +#endif /* !__DragonFly__ */ + case 'k': + kflag = 1; + break; + case 'l': + lflag = 1; + break; + case 'n': + nflag = 1; + break; + case 'p': + pflag = optarg; + break; + case 'r': + rflag = 1; + break; + case 's': + sflag = optarg; + break; + case 't': + tflag = 1; + break; + case 'u': + uflag = 1; + break; + case 'v': + vflag = 1; + break; + case 'w': + timeout = (int)strtoul(optarg, &endp, 10); + if (timeout < 0 || *endp != '\0') + errx(1, "timeout cannot be negative"); + if (timeout >= (INT_MAX / 1000)) + errx(1, "timeout too large"); +#ifndef USE_SELECT + timeout *= 1000; +#endif + break; + case 'x': + xflag = 1; + if ((proxy = strdup(optarg)) == NULL) + err(1, NULL); + break; + case 'z': + zflag = 1; + break; + case 'D': + Dflag = 1; + break; +#ifndef __DragonFly__ + case 'S': + Sflag = 1; + break; +#endif /* !__DragonFly__ */ + default: + usage(1); + } + } + argc -= optind; + argv += optind; + + /* Cruft to make sure options are clean, and used properly. */ + if (argv[0] && !argv[1] && family == AF_UNIX) { + if (uflag) + errx(1, "cannot use -u and -U"); + host = argv[0]; + uport = NULL; + } else if (argv[0] && !argv[1]) { + if (!lflag) + usage(1); + uport = argv[0]; + host = NULL; + } else if (argv[0] && argv[1]) { + host = argv[0]; + uport = argv[1]; + } else + usage(1); + + if (lflag && sflag) + errx(1, "cannot use -s and -l"); + if (lflag && pflag) + errx(1, "cannot use -p and -l"); + if (lflag && zflag) + errx(1, "cannot use -z and -l"); + if (!lflag && kflag) + errx(1, "must use -l with -k"); + + /* Initialize addrinfo structure. */ + if (family != AF_UNIX) { + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = family; + hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM; + hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP; + if (nflag) + hints.ai_flags |= AI_NUMERICHOST; + } + + if (xflag) { + if (uflag) + errx(1, "no proxy support for UDP mode"); + + if (lflag) + errx(1, "no proxy support for listen"); + + if (family == AF_UNIX) + errx(1, "no proxy support for unix sockets"); + + /* XXX IPv6 transport to proxy would probably work */ + if (family == AF_INET6) + errx(1, "no proxy support for IPv6"); + + if (sflag) + errx(1, "no proxy support for local source address"); + + proxyhost = strsep(&proxy, ":"); + proxyport = proxy; + + memset(&proxyhints, 0, sizeof(struct addrinfo)); + proxyhints.ai_family = family; + proxyhints.ai_socktype = SOCK_STREAM; + proxyhints.ai_protocol = IPPROTO_TCP; + if (nflag) + proxyhints.ai_flags |= AI_NUMERICHOST; + } + + if (lflag) { + int connfd; + ret = 0; + + if (family == AF_UNIX) + s = unix_listen(host); + + /* Allow only one connection at a time, but stay alive. */ + for (;;) { + if (family != AF_UNIX) + s = local_listen(host, uport, hints); + if (s < 0) + err(1, NULL); + /* + * For UDP, we will use recvfrom() initially + * to wait for a caller, then use the regular + * functions to talk to the caller. + */ + if (uflag) { + int rv, plen; + char buf[8192]; + struct sockaddr_storage z; + + len = sizeof(z); +#ifndef __DragonFly__ + plen = jflag ? 8192 : 1024; +#else /* __DragonFly__ */ + plen = 1024; +#endif /* !__DragonFly__ */ + rv = recvfrom(s, buf, plen, MSG_PEEK, + (struct sockaddr *)&z, &len); + if (rv < 0) + err(1, "recvfrom"); + + rv = connect(s, (struct sockaddr *)&z, len); + if (rv < 0) + err(1, "connect"); + + connfd = s; + } else { + len = sizeof(cliaddr); + connfd = accept(s, (struct sockaddr *)&cliaddr, + &len); + } + + readwrite(connfd); + close(connfd); + if (family != AF_UNIX) + close(s); + + if (!kflag) + break; + } + } else if (family == AF_UNIX) { + ret = 0; + + if ((s = unix_connect(host)) > 0 && !zflag) { + readwrite(s); + close(s); + } else + ret = 1; + + exit(ret); + + } else { + int i = 0; + + /* Construct the portlist[] array. */ + build_ports(uport); + + /* Cycle through portlist, connecting to each port. */ + for (i = 0; portlist[i] != NULL; i++) { + if (s) + close(s); + + if (xflag) + s = socks_connect(host, portlist[i], hints, + proxyhost, proxyport, proxyhints, socksv); + else + s = remote_connect(host, portlist[i], hints); + + if (s < 0) + continue; + + ret = 0; + if (vflag || zflag) { + /* For UDP, make sure we are connected. */ + if (uflag) { + if (udptest(s) == -1) { + ret = 1; + continue; + } + } + + /* Don't look up port if -n. */ + if (nflag) + sv = NULL; + else { + sv = getservbyport( + ntohs(atoi(portlist[i])), + uflag ? "udp" : "tcp"); + } + + printf("Connection to %s %s port [%s/%s] succeeded!\n", + host, portlist[i], uflag ? "udp" : "tcp", + sv ? sv->s_name : "*"); + } + if (!zflag) + readwrite(s); + } + } + + if (s) + close(s); + + exit(ret); +} + +/* + * unix_connect() + * Returns a socket connected to a local unix socket. Returns -1 on failure. + */ +int +unix_connect(char *path) +{ + struct sockaddr_un sun; + int s; + + if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) + return (-1); + (void)fcntl(s, F_SETFD, 1); + + memset(&sun, 0, sizeof(struct sockaddr_un)); + sun.sun_family = AF_UNIX; + + if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >= + sizeof(sun.sun_path)) { + close(s); + errno = ENAMETOOLONG; + return (-1); + } + if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) { + close(s); + return (-1); + } + return (s); + +} + +/* + * unix_listen() + * Create a unix domain socket, and listen on it. + */ +int +unix_listen(char *path) +{ + struct sockaddr_un sun; + int s; + + /* Create unix domain socket. */ + if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) + return (-1); + + memset(&sun, 0, sizeof(struct sockaddr_un)); + sun.sun_family = AF_UNIX; + + if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >= + sizeof(sun.sun_path)) { + close(s); + errno = ENAMETOOLONG; + return (-1); + } + + if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) { + close(s); + return (-1); + } + + if (listen(s, 5) < 0) { + close(s); + return (-1); + } + return (s); +} + +/* + * remote_connect() + * Returns a socket connected to a remote host. Properly binds to a local + * port or source address if needed. Returns -1 on failure. + */ +int +remote_connect(const char *host, const char *port, struct addrinfo hints) +{ + struct addrinfo *res, *res0; + int s, error; + + if ((error = getaddrinfo(host, port, &hints, &res))) + errx(1, "getaddrinfo: %s", gai_strerror(error)); + + res0 = res; + do { + if ((s = socket(res0->ai_family, res0->ai_socktype, + res0->ai_protocol)) < 0) + continue; + + /* Bind to a local port or source address if specified. */ + if (sflag || pflag) { + struct addrinfo ahints, *ares; + + if (!(sflag && pflag)) { + if (!sflag) + sflag = NULL; + else + pflag = NULL; + } + + memset(&ahints, 0, sizeof(struct addrinfo)); + ahints.ai_family = res0->ai_family; + ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM; + ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP; + ahints.ai_flags = AI_PASSIVE; + if ((error = getaddrinfo(sflag, pflag, &ahints, &ares))) + errx(1, "getaddrinfo: %s", gai_strerror(error)); + + if (bind(s, (struct sockaddr *)ares->ai_addr, + ares->ai_addrlen) < 0) + errx(1, "bind failed: %s", strerror(errno)); + freeaddrinfo(ares); + } + + set_common_sockopts(s); + + if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0) + break; + else if (vflag) + warn("connect to %s port %s (%s) failed", host, port, + uflag ? "udp" : "tcp"); + + close(s); + s = -1; + } while ((res0 = res0->ai_next) != NULL); + + freeaddrinfo(res); + + return (s); +} + +/* + * local_listen() + * Returns a socket listening on a local port, binds to specified source + * address. Returns -1 on failure. + */ +int +local_listen(char *host, char *port, struct addrinfo hints) +{ + struct addrinfo *res, *res0; + int s, ret, x = 1; + int error; + + /* Allow nodename to be null. */ + hints.ai_flags |= AI_PASSIVE; + + /* + * In the case of binding to a wildcard address + * default to binding to an ipv4 address. + */ + if (host == NULL && hints.ai_family == AF_UNSPEC) + hints.ai_family = AF_INET; + + if ((error = getaddrinfo(host, port, &hints, &res))) + errx(1, "getaddrinfo: %s", gai_strerror(error)); + + res0 = res; + do { + if ((s = socket(res0->ai_family, res0->ai_socktype, + res0->ai_protocol)) < 0) + continue; + + ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x)); + if (ret == -1) + err(1, NULL); + + set_common_sockopts(s); + + if (bind(s, (struct sockaddr *)res0->ai_addr, + res0->ai_addrlen) == 0) + break; + + close(s); + s = -1; + } while ((res0 = res0->ai_next) != NULL); + + if (!uflag && s != -1) { + if (listen(s, 1) < 0) + err(1, "listen"); + } + + freeaddrinfo(res); + + return (s); +} + +/* + * readwrite() + * Loop that polls on the network file descriptor and stdin. + */ +void +readwrite(int nfd) +{ +#ifdef USE_SELECT + fd_set readfds; + struct timeval tv; + int nfd_open = 1, wfd_open = 1; +#else + struct pollfd pfd[2]; +#endif + unsigned char buf[8192]; + int n, wfd = fileno(stdin); + int lfd = fileno(stdout); + int plen; + +#ifndef __DragonFly__ + plen = jflag ? 8192 : 1024; +#else /* __DragonFly__ */ + plen = 1024; +#endif /* !__DragonFly__ */ + +#ifndef USE_SELECT + /* Setup Network FD */ + pfd[0].fd = nfd; + pfd[0].events = POLLIN; + + /* Set up STDIN FD. */ + pfd[1].fd = wfd; + pfd[1].events = POLLIN; +#endif + +#ifdef USE_SELECT + while (nfd_open) { +#else + while (pfd[0].fd != -1) { +#endif + if (iflag) + sleep(iflag); + +#ifdef USE_SELECT + FD_ZERO(&readfds); + if (nfd_open) + FD_SET(nfd, &readfds); + if (wfd_open) + FD_SET(wfd, &readfds); + + tv.tv_sec = timeout; + tv.tv_usec = 0; + + if ((n = select(nfd + 1, &readfds, NULL, NULL, (timeout == -1) ? NULL : &tv)) < 0) { +#else + if ((n = poll(pfd, 2 - dflag, timeout)) < 0) { +#endif + close(nfd); + err(1, "Polling Error"); + } + + if (n == 0) + return; + +#ifdef USE_SELECT + if (FD_ISSET(nfd, &readfds)) { +#else + if (pfd[0].revents & POLLIN) { +#endif + if ((n = read(nfd, buf, plen)) < 0) + return; + else if (n == 0) { + shutdown(nfd, SHUT_RD); +#ifdef USE_SELECT + nfd_open = 0; +#else + pfd[0].fd = -1; + pfd[0].events = 0; +#endif + } else { + if (tflag) + atelnet(nfd, buf, n); + if (atomicio(vwrite, lfd, buf, n) != n) + return; + } + } + +#ifdef USE_SELECT + if (!dflag && FD_ISSET(wfd, &readfds)) { +#else + if (!dflag && pfd[1].revents & POLLIN) { +#endif + if ((n = read(wfd, buf, plen)) < 0) + return; + else if (n == 0) { + shutdown(nfd, SHUT_WR); +#ifdef USE_SELECT + wfd_open = 0; +#else + pfd[1].fd = -1; + pfd[1].events = 0; +#endif + } else { + if (atomicio(vwrite, nfd, buf, n) != n) + return; + } + } + } +} + +/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */ +void +atelnet(int nfd, unsigned char *buf, unsigned int size) +{ + unsigned char *p, *end; + unsigned char obuf[4]; + + end = buf + size; + obuf[0] = '\0'; + + for (p = buf; p < end; p++) { + if (*p != IAC) + break; + + obuf[0] = IAC; + p++; + if ((*p == WILL) || (*p == WONT)) + obuf[1] = DONT; + if ((*p == DO) || (*p == DONT)) + obuf[1] = WONT; + if (obuf) { + p++; + obuf[2] = *p; + obuf[3] = '\0'; + if (atomicio(vwrite, nfd, obuf, 3) != 3) + warn("Write Error!"); + obuf[0] = '\0'; + } + } +} + +/* + * build_ports() + * Build an array or ports in portlist[], listing each port + * that we should try to connect to. + */ +void +build_ports(char *p) +{ + char *n, *endp; + int hi, lo, cp; + int x = 0; + + if ((n = strchr(p, '-')) != NULL) { + if (lflag) + errx(1, "Cannot use -l with multiple ports!"); + + *n = '\0'; + n++; + + /* Make sure the ports are in order: lowest->highest. */ + hi = (int)strtoul(n, &endp, 10); + if (hi <= 0 || hi > PORT_MAX || *endp != '\0') + errx(1, "port range not valid"); + lo = (int)strtoul(p, &endp, 10); + if (lo <= 0 || lo > PORT_MAX || *endp != '\0') + errx(1, "port range not valid"); + + if (lo > hi) { + cp = hi; + hi = lo; + lo = cp; + } + + /* Load ports sequentially. */ + for (cp = lo; cp <= hi; cp++) { + portlist[x] = calloc(1, PORT_MAX_LEN); + if (portlist[x] == NULL) + err(1, NULL); + snprintf(portlist[x], PORT_MAX_LEN, "%d", cp); + x++; + } + + /* Randomly swap ports. */ + if (rflag) { + int y; + char *c; + + for (x = 0; x <= (hi - lo); x++) { + y = (arc4random() & 0xFFFF) % (hi - lo); + c = portlist[x]; + portlist[x] = portlist[y]; + portlist[y] = c; + } + } + } else { + hi = (int)strtoul(p, &endp, 10); + if (hi <= 0 || hi > PORT_MAX || *endp != '\0') + errx(1, "port range not valid"); + portlist[0] = calloc(1, PORT_MAX_LEN); + if (portlist[0] == NULL) + err(1, NULL); + portlist[0] = p; + } +} + +/* + * udptest() + * Do a few writes to see if the UDP port is there. + * XXX - Better way of doing this? Doesn't work for IPv6. + * Also fails after around 100 ports checked. + */ +int +udptest(int s) +{ + int i, ret; + + for (i = 0; i <= 3; i++) { + if (write(s, "X", 1) == 1) + ret = 1; + else + ret = -1; + } + return (ret); +} + +int +set_common_sockopts(int s) +{ + int x = 1; + +#ifndef __DragonFly__ + if (Sflag) { + if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG, + &x, sizeof(x)) == -1) + err(1, NULL); + } +#endif /* !__DragonFly__ */ + if (Dflag) { + if (setsockopt(s, SOL_SOCKET, SO_DEBUG, + &x, sizeof(x)) == -1) + err(1, NULL); + } +#ifndef __DragonFly__ + if (jflag) { + if (setsockopt(s, SOL_SOCKET, SO_JUMBO, + &x, sizeof(x)) == -1) + err(1, NULL); + } +#endif /* !__DragonFly__ */ +} + +void +help(void) +{ + usage(0); + fprintf(stderr, "\tCommand Summary:\n\ + \t-4 Use IPv4\n\ + \t-6 Use IPv6\n\ + \t-D Enable the debug socket option\n\ + \t-d Detach from stdin\n\ + \t-h This help text\n\ + \t-i secs\t Delay interval for lines sent, ports scanned\n\ + \t-k Keep inbound sockets open for multiple connects\n\ + \t-l Listen mode, for inbound connects\n\ + \t-n Suppress name/port resolutions\n\ + \t-p port\t Specify local port for remote connects\n\ + \t-r Randomize remote ports\n\ +%s\ + \t-s addr\t Local source address\n\ + \t-t Answer TELNET negotiation\n\ + \t-U Use UNIX domain socket\n\ + \t-u UDP mode\n\ + \t-v Verbose\n\ + \t-w secs\t Timeout for connects and final net reads\n\ + \t-X proto Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\ + \t-x addr[:port]\tSpecify proxy address and port\n\ + \t-z Zero-I/O mode [used for scanning]\n\ + Port numbers can be individual or ranges: lo-hi [inclusive]\n", +#ifndef __DragonFly__ + " \t-S Enable the TCP MD5 signature option\n" +#else /* __DragonFly__ */ + "" +#endif /* !__DragonFly__ */ + ); + exit(1); +} + +void +usage(int ret) +{ +#ifndef __DragonFly__ + fprintf(stderr, "usage: nc [-46DdhklnrStUuvz] [-i interval] [-p source_port]\n"); +#else /* __DragonFly__ */ + fprintf(stderr, "usage: nc [-46DdhklnrtUuvz] [-i interval] [-p source_port]\n"); +#endif /* !__DragonFly__ */ + fprintf(stderr, "\t [-s source_ip_address] [-w timeout] [-X proxy_version]\n"); + fprintf(stderr, "\t [-x proxy_address[:port]] [hostname] [port[s]]\n"); + if (ret) + exit(1); +} diff --git a/src/dragonfly/socks.c b/src/dragonfly/socks.c new file mode 100644 index 0000000..de61439 --- /dev/null +++ b/src/dragonfly/socks.c @@ -0,0 +1,270 @@ +/* $OpenBSD: socks.c,v 1.15 2005/05/24 20:13:28 avsm Exp $ */ + +/* + * Copyright (c) 1999 Niklas Hallqvist. All rights reserved. + * Copyright (c) 2004, 2005 Damien Miller. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "atomicio.h" + +#define SOCKS_PORT "1080" +#define HTTP_PROXY_PORT "3128" +#define HTTP_MAXHDRS 64 +#define SOCKS_V5 5 +#define SOCKS_V4 4 +#define SOCKS_NOAUTH 0 +#define SOCKS_NOMETHOD 0xff +#define SOCKS_CONNECT 1 +#define SOCKS_IPV4 1 +#define SOCKS_DOMAIN 3 +#define SOCKS_IPV6 4 + +int remote_connect(const char *, const char *, struct addrinfo); +int socks_connect(const char *host, const char *port, struct addrinfo hints, + const char *proxyhost, const char *proxyport, struct addrinfo proxyhints, + int socksv); + +static int +decode_addrport(const char *h, const char *p, struct sockaddr *addr, + socklen_t addrlen, int v4only, int numeric) +{ + int r; + struct addrinfo hints, *res; + + bzero(&hints, sizeof(hints)); + hints.ai_family = v4only ? PF_INET : PF_UNSPEC; + hints.ai_flags = numeric ? AI_NUMERICHOST : 0; + hints.ai_socktype = SOCK_STREAM; + r = getaddrinfo(h, p, &hints, &res); + /* Don't fatal when attempting to convert a numeric address */ + if (r != 0) { + if (!numeric) { + errx(1, "getaddrinfo(\"%.64s\", \"%.64s\"): %s", h, p, + gai_strerror(r)); + } + return (-1); + } + if (addrlen < res->ai_addrlen) { + freeaddrinfo(res); + errx(1, "internal error: addrlen < res->ai_addrlen"); + } + memcpy(addr, res->ai_addr, res->ai_addrlen); + freeaddrinfo(res); + return (0); +} + +static int +proxy_read_line(int fd, char *buf, size_t bufsz) +{ + size_t off; + + for(off = 0;;) { + if (off >= bufsz) + errx(1, "proxy read too long"); + if (atomicio(read, fd, buf + off, 1) != 1) + err(1, "proxy read"); + /* Skip CR */ + if (buf[off] == '\r') + continue; + if (buf[off] == '\n') { + buf[off] = '\0'; + break; + } + off++; + } + return (off); +} + +int +socks_connect(const char *host, const char *port, + struct addrinfo hints __attribute__ ((__unused__)), + const char *proxyhost, const char *proxyport, struct addrinfo proxyhints, + int socksv) +{ + int proxyfd, r; + size_t hlen, wlen; + unsigned char buf[1024]; + size_t cnt; + struct sockaddr_storage addr; + struct sockaddr_in *in4 = (struct sockaddr_in *)&addr; + struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr; + in_port_t serverport; + + if (proxyport == NULL) + proxyport = (socksv == -1) ? HTTP_PROXY_PORT : SOCKS_PORT; + + proxyfd = remote_connect(proxyhost, proxyport, proxyhints); + + if (proxyfd < 0) + return (-1); + + /* Abuse API to lookup port */ + if (decode_addrport("0.0.0.0", port, (struct sockaddr *)&addr, + sizeof(addr), 1, 1) == -1) + errx(1, "unknown port \"%.64s\"", port); + serverport = in4->sin_port; + + if (socksv == 5) { + if (decode_addrport(host, port, (struct sockaddr *)&addr, + sizeof(addr), 0, 1) == -1) + addr.ss_family = 0; /* used in switch below */ + + /* Version 5, one method: no authentication */ + buf[0] = SOCKS_V5; + buf[1] = 1; + buf[2] = SOCKS_NOAUTH; + cnt = atomicio(vwrite, proxyfd, buf, 3); + if (cnt != 3) + err(1, "write failed (%d/3)", cnt); + + cnt = atomicio(read, proxyfd, buf, 2); + if (cnt != 2) + err(1, "read failed (%d/3)", cnt); + + if (buf[1] == SOCKS_NOMETHOD) + errx(1, "authentication method negotiation failed"); + + switch (addr.ss_family) { + case 0: + /* Version 5, connect: domain name */ + + /* Max domain name length is 255 bytes */ + hlen = strlen(host); + if (hlen > 255) + errx(1, "host name too long for SOCKS5"); + buf[0] = SOCKS_V5; + buf[1] = SOCKS_CONNECT; + buf[2] = 0; + buf[3] = SOCKS_DOMAIN; + buf[4] = hlen; + memcpy(buf + 5, host, hlen); + memcpy(buf + 5 + hlen, &serverport, sizeof serverport); + wlen = 7 + hlen; + break; + case AF_INET: + /* Version 5, connect: IPv4 address */ + buf[0] = SOCKS_V5; + buf[1] = SOCKS_CONNECT; + buf[2] = 0; + buf[3] = SOCKS_IPV4; + memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr); + memcpy(buf + 8, &in4->sin_port, sizeof in4->sin_port); + wlen = 10; + break; + case AF_INET6: + /* Version 5, connect: IPv6 address */ + buf[0] = SOCKS_V5; + buf[1] = SOCKS_CONNECT; + buf[2] = 0; + buf[3] = SOCKS_IPV6; + memcpy(buf + 4, &in6->sin6_addr, sizeof in6->sin6_addr); + memcpy(buf + 20, &in6->sin6_port, + sizeof in6->sin6_port); + wlen = 22; + break; + default: + errx(1, "internal error: silly AF"); + } + + cnt = atomicio(vwrite, proxyfd, buf, wlen); + if (cnt != wlen) + err(1, "write failed (%d/%d)", cnt, wlen); + + cnt = atomicio(read, proxyfd, buf, 10); + if (cnt != 10) + err(1, "read failed (%d/10)", cnt); + if (buf[1] != 0) + errx(1, "connection failed, SOCKS error %d", buf[1]); + } else if (socksv == 4) { + /* This will exit on lookup failure */ + decode_addrport(host, port, (struct sockaddr *)&addr, + sizeof(addr), 1, 0); + + /* Version 4 */ + buf[0] = SOCKS_V4; + buf[1] = SOCKS_CONNECT; /* connect */ + memcpy(buf + 2, &in4->sin_port, sizeof in4->sin_port); + memcpy(buf + 4, &in4->sin_addr, sizeof in4->sin_addr); + buf[8] = 0; /* empty username */ + wlen = 9; + + cnt = atomicio(vwrite, proxyfd, buf, wlen); + if (cnt != wlen) + err(1, "write failed (%d/%d)", cnt, wlen); + + cnt = atomicio(read, proxyfd, buf, 8); + if (cnt != 8) + err(1, "read failed (%d/8)", cnt); + if (buf[1] != 90) + errx(1, "connection failed, SOCKS error %d", buf[1]); + } else if (socksv == -1) { + /* HTTP proxy CONNECT */ + + /* Disallow bad chars in hostname */ + if (strcspn(host, "\r\n\t []:") != strlen(host)) + errx(1, "Invalid hostname"); + + /* Try to be sane about numeric IPv6 addresses */ + if (strchr(host, ':') != NULL) { + r = snprintf(buf, sizeof(buf), + "CONNECT [%s]:%d HTTP/1.0\r\n\r\n", + host, ntohs(serverport)); + } else { + r = snprintf(buf, sizeof(buf), + "CONNECT %s:%d HTTP/1.0\r\n\r\n", + host, ntohs(serverport)); + } + if (r == -1 || (size_t)r >= sizeof(buf)) + errx(1, "hostname too long"); + r = strlen(buf); + + cnt = atomicio(vwrite, proxyfd, buf, r); + if (cnt != r) + err(1, "write failed (%d/%d)", cnt, r); + + /* Read reply */ + for (r = 0; r < HTTP_MAXHDRS; r++) { + proxy_read_line(proxyfd, buf, sizeof(buf)); + if (r == 0 && strncmp(buf, "HTTP/1.0 200 ", 12) != 0) + errx(1, "Proxy error: \"%s\"", buf); + /* Discard headers until we hit an empty line */ + if (*buf == '\0') + break; + } + } else + errx(1, "Unknown proxy protocol %d", socksv); + + return (proxyfd); +} -- 2.11.4.GIT