Compare commits

...

235 Commits
v4.3 ... master

Author SHA1 Message Date
rofl0r fffd2532ad fix wrong prototype of freeaddrinfo_t
closes #557
2024-03-14 20:11:58 +00:00
rofl0r 282ac7dd02 release 4.17 2024-01-21 17:28:35 +00:00
rofl0r 1d0bc349eb fix potential double-close of file descriptors
in case of an error condition, both start_chain() and chain_step()
were closing the fd to be acted upon, without setting it to -1,
and the function calling them would close them again.

this could affect multi-threaded applications that opened new fds
between the first and the second close, invalidating those fds
in the targeted app.

patch loosely based on report and PR by @jhfrontz.

closes #542
2024-01-02 14:45:25 +00:00
Guilherme Janczak 0279dda939
OpenBSD: use ':' as LD_PRELOAD separator (#538)
LD_PRELOAD documentation added in 1998 talks about colon as
separator, and apparently space no longer works.
2023-12-09 12:59:53 +00:00
wzy d5cc80ae16
Fix zsh install location (#532)
Reported: https://github.com/NixOS/nixpkgs/pull/222667#issuecomment-1713238866
2023-12-02 21:28:35 +00:00
rofl0r 0c795085fa move initialization of quiet variable to do_init
fixes #511 - DLL init line is always printed even with -q.
regression from recent changes to init code.
2023-05-20 15:27:22 +00:00
Wu Zhenyu 42d2d95160 Remove unused code in zsh completion
Move completions/_proxychains4 to completions/zsh/_proxychains4 to avoid confusion
2023-04-26 21:11:29 +01:00
rofl0r 133e06b3f0 fix resolving of proxy names with proxy_dns_daemon
closes #497

in order to make this work, also the change in 2d265582a2
was required; otherwise the sendto() call from rdns lookup would
cause the init code to be called from within the init code and
ultimately hanging on pthread_once().
2023-03-20 20:29:25 +00:00
rofl0r 2d265582a2 disable lazy init if compiler supports GCC constructor attribute
before we started to use the gcc constructor attribute to load our
initialization code, each function hook used to check whether the
initialization was already done, and if not, do it at that point.

this workaround is quite ugly, and creates a circular reference
if the startup code calls any of the hooked functions.

now we only do the lazy init if the compiler used is not GCC
compatible.
2023-03-20 20:15:00 +00:00
rofl0r 66f99b19dd improve DNS failure handling with old proxyresolv method
should fix #493
2023-03-08 15:05:06 +00:00
rofl0r 199d03d8b4 configure: add a check for whether libc headers are usable
closes #486
2022-12-10 19:19:53 +00:00
rofl0r 060801d8c8 fat-binary-m1: use arm64e for dylib, but not for executable
according to research done by @malash, the proxychains4 binary
itself isn't allowed to use system-internal arm64e mode; but
it's possible to add it as a 3rd architecture to the shared
library (.dylib), and then even inject it into system binaries
like /usr/bin/curl, which didn't work since the introduction
of SIP.

therefore, we now create the dylib with all 3 archs, but the
launcher only with arm64 and x86_64.

closes #453
2022-07-21 23:04:03 +00:00
rofl0r 09142579c5 use -Wno-unknown-pragmas if available
this heavily reduces compiler warning spam in build logs.
2022-06-11 11:00:34 +00:00
rofl0r 916d2d7da1 fix --fat-binary-m1 option
even though the preload library was built correctly, the LDFLAGS set
weren't passed to the main proxychains4 binary, resulting in link
errors against the fat object files.

closes #452
2022-05-31 23:53:23 +00:00
rofl0r 4b531806b2 configure: add --fat-binary-m1 for arm64e/x86_64 (M1) fat binary
addresses #451
closes #383
2022-05-19 09:12:10 +00:00
Zenithal 9b42da71f4 Fix zsh completion file to proxychains4 2022-05-15 09:36:35 +01:00
Freed-Wu 04023d3811 Add zsh completion file 2022-04-13 00:55:19 +01:00
rofl0r 0a4daa62d6 using qsort for 4 ints is overkill
replace it with custom mini sort routine.
2022-04-12 23:51:17 +00:00
Recolic Keghart 0000000062 Add hook to close_range function, solves #439. |0! 2022-04-12 20:37:05 +08:00
rofl0r 07c15a02f6 add configure check for non-POSIX compliant getnameinfo signature
- glibc < 2.14 uses "unsigned" instead of "int" for flags
- openbsd and freebsd use "size_t" instead of socklen_t for servlen
  and nodelen, while still using socklen_t for salen.

closes #430
2022-01-25 15:42:55 +00:00
rofl0r 2cc014995e release 4.16 2022-01-23 14:16:56 +00:00
Vladimir Panteleev 6abeb53e69 proxy_getaddrinfo(): Fill in ai_socktype if requested
If the application specifies a protocol but not a socket type,
normally getaddrinfo will select a corresponding protocol.

Mimic this behavior in our implementation of the function as well.
We only care about the case we're actually able to proxify
(SOCK_STREAM / IPPROTO_TCP).

Fixes proxifying pssh.
2022-01-22 20:05:47 +00:00
Vladimir Panteleev 70629aaf25 src/proxychains.conf: Fix typos 2022-01-22 20:05:47 +00:00
rofl0r a12cf0a516 main: add more luser-friendly error message when execvp fails
closes #423
closes #412
2022-01-10 11:44:26 +00:00
Eero Häkkinen 2739fb5416 support IPv6 localnets
closes #218
2022-01-03 14:52:06 +00:00
rofl0r 4a963b2feb only use -ldl if available (netbsd compilation fix)
fixes #416
2021-12-17 13:37:58 +00:00
rofl0r e20c08fe47 configure: detect OSX >= 12 and use new dyld hooking method
closes #409
2021-12-14 14:38:55 +00:00
rofl0r 4a013fe6a5 preliminary support for new DYLD hooking method for OSX Monterey
there's currently no build system support yet. after ./configure
was executed, add -DMONTEREY_HOOKING to CFLAGS/CPPFLAGS in config.mak
to activate this.

addressing #409

special thanks go to @yicong2007 and @YangshengLu for helping to
figure out this new technique.
2021-12-14 12:49:27 +00:00
rofl0r d415d8a5ed introduce HOOKFUNC macro to mark all libc hook functions
this is currently a NO-OP, but it's already useful in that it
clearly marks our hook functions that override libc.
this in preparation of adding support for MacOS 12.0.1 "Monterey",
which apparently requires a new dynlinker hooking method.
2021-12-12 17:59:17 +00:00
rofl0r 063ac681da remove 10 year old workaround for wrong glibc getnameinfo signature
in ce655fdac8 the getnameinfo function
was factored into a separate TU to prevent its POSIX signature from
colliding with GLIBC's wrong prototype. since this has been fixed
in GLIBC 10 years ago, it should be safe by now.
undoing the workaround has the advantage that all hooked functions
are now available in the same place, which is a prerequisite for
a change i'm about to commit.

if it turns out there's still systems in use that use the old GLIBC
version with the wrong prototype, we can add a configure check
dealing with it.
2021-12-12 17:51:25 +00:00
rofl0r b83e90dcaf update some testcases 2021-12-12 15:59:34 +00:00
rofl0r 7de7dd0de1 configure: fix regression in detecting linker options
introduced in 83bfa0b61d, the check_link_silent
option always returned the result from the rm -f command rather than
the result from the compiler.

fixes #400
2021-10-01 08:58:19 +00:00
rofl0r 1015efaf16 release 4.15 2021-07-24 06:23:03 +01:00
Fabrice Fontaine 83bfa0b61d configure: fix check_link_silent and check_compile
Replace -o /dev/null by -o "$tmpc".out in check_link_silent and
check_compile otherwise test will fail with some bugged binutils
(https://sourceware.org/bugzilla/show_bug.cgi?id=19526) since version
4.13 and
35a674bdbc:

checking what's the option to use in linker to set library name ...
cannot find an option to set library name
package/pkg-generic.mk:249: recipe for target '/home/buildroot/autobuild/instance-2/output-1/build/proxychains-ng-4.14/.stamp_configured' failed

Fixes:
 - http://autobuild.buildroot.org/results/9320d9b2c69882e23bbe7b30057eb8bee0c9d2e5

Signed-off-by: Fabrice Fontaine <fontaine.fabrice@gmail.com>
2021-07-23 20:18:34 +01:00
rofl0r 931e0df9f8 README: freenode -> libera 2021-05-19 14:18:27 +01:00
rofl0r 092d7042e0 initialize rand seed with nano-second granularity
in scenarios where one is to spin up several processes with the same
proxy list in random mode, all processes started in the same second
would pick the same proxy due to using the same srand() seed.

closes #380
2021-05-14 14:10:14 +00:00
rofl0r 6af2686a52 configure: check for -pthread vs -lpthread (#379) 2021-04-30 16:15:30 +01:00
rofl0r 918855deed proxy_getaddrinfo(): debug: print hints->ai_flags 2021-02-05 01:50:39 +00:00
rofl0r 181cc0f414 debug.h: print pid in all debug output 2021-02-05 01:45:19 +00:00
rofl0r 3721f7e144 test_getaddrinfo: also print port information 2021-02-05 01:38:17 +00:00
rofl0r 6c029fdf47 fix compiler parentheses warning in dnat code 2021-01-08 17:45:35 +00:00
rofl0r 596f0028cb proxychains.conf: fix localnet documentation
localnet with hostnames/DNS is not compatible with remote dns - if remote dns
is activated we get an ip from the remote dns resolver in the connect() call,
so we don't know whether the destination would match any localnet - except
from the ANY localnet 0.0.0.0 - in which case we would need to do a real DNS
lookup with the remote DNS ip involving both the rdns resolver to get the
original hostname back and then call the native DNS resolver function - for
which there is only getaddrinfo() when we don't want to support the 5
different gethostbyname_r() variants in existence, or using getaddrinfo(),
which in turn requires memory allocation/free() - in other words a huge mess.
we also can't easily check in the resolver whether an ANY-destination localnet
is enabled and the port matches, because the resolver might only resolve the
hostname at this stage, but not the destination port.

addressing #358
2021-01-08 17:36:05 +00:00
rofl0r fa9644dc27 configure: check first whether C compiler works
closes #353
2020-12-18 12:33:49 +00:00
Alexandre Viau 159ab94635
support 'raw' proxy type (#348) 2020-12-12 08:25:36 +00:00
rofl0r 583343a2ef configure: fix typo in fail() 2020-10-29 12:06:00 +00:00
rofl0r 0069fcd53e configure: add missing function fail() 2020-10-29 11:58:22 +00:00
rofl0r 13680e775d proxy_gethostbyname_old(): fix omission of namebuffer population 2020-10-28 11:12:36 +00:00
rofl0r 55dce2c040 proxy_gethostbyname_old(): fix returned address type 2020-10-28 11:12:36 +00:00
rofl0r 82c766461c proxy_gethostbyname_old(): likewise. 2020-10-28 11:12:36 +00:00
rofl0r 59e8d1710a proxy_gethostbyname(): fix failure to omit DNS lookup for ipv4 addrs
gethostbyname() is specified to transform simple numeric ipv4 addresses
into their binary form. since proxy_gethostbyname() was used as a
backend for all resolver functions, somehow we assumed the check for
an ipv4 was done from another site, however this didn't hold true when
the caller used gethostbyname() directly.

fixes #347
2020-10-28 11:12:17 +00:00
rofl0r 452830283c move isnumericipv4() to common.c 2020-10-28 10:39:27 +00:00
rofl0r 486f8200ad tunnel_to: shrink huge buffer size
the buffer buff was only used for the initial handshake packets,
which in all supported protocols are usual less than a 100 bytes,
with user/pass and dns name at maximum we'd require 768 bytes,
which still leaves us a formidable 256 bytes for the rest of
the packet.
this fixes a segfault with microsocks which on musl uses tiny
thread stack sizes of 8KB.
2020-10-26 03:03:08 +00:00
rofl0r c99d97983e shrink huge gethostbyname buffer
careful analysis has shown that the buffer is only ever used for
at most a single hostname, so 256 bytes are sufficient.
the huge 8KB buffer caused stack overflow when used with microsocks,
which defaults to tiny thread stacks of 8KB with musl libc.
2020-10-26 02:53:29 +00:00
rofl0r 7fe8139496 experimental new feature: proxy_dns_daemon
since many users complain about issues with modern, ultracomplex
clusterfuck software such as chromium, nodejs, etc, i've reconsidered
one of my original ideas how to implement remote dns lookup support.
instead of having a background thread serving requests via a pipe,
the user manually starts a background daemon process before running
proxychains, and the two processes then communicate via UDP.
this requires much less hacks (like hooking of close() to prevent
pipes from getting closed) and doesn't need to call any async-signal
unsafe code like malloc(). this means it should be much more compatible
than the previous method, however it's not as practical and slightly
slower.

it's recommended that the proxychains4-daemon runs on localhost, and
if you use proxychains-ng a lot you might want to set ip up as a service
that starts on boot. a single proxychains4-daemon should theoretically
be able to serve many parallel proxychains4 instances, but this has not
yet been tested so far. it's also possible to run the daemon on other
computers, even over internet, but currently there is no error-checking/
timeout code at all; that means the UDP connection needs to be very
stable.

the library code used for the daemon sources are from my projects
libulz[0] and htab[1], and the server code is loosely based on
microsocks[2]. their licenses are all compatible with the GPL.
if not otherwise mentioned, they're released for this purpose under
the standard proxychains-ng license (see COPYING).

[0]: https://github.com/rofl0r/libulz
[1]: https://github.com/rofl0r/htab
[2]: https://github.com/rofl0r/microsocks
2020-09-23 22:14:39 +01:00
rofl0r 1e00b9ac1e get rid of ip_type.c 2020-09-23 17:00:16 +01:00
rofl0r 1221c5e93a get_chain_data: fix strstr() config parsing
using strstr() is a very error-prone way for config parsing.

for example if "proxy_dns" is being tested for the line "proxy_dns_old",
it would return true.

we fix this by removing leading and trailing whitespace from the line
to parse and use strcmp/strncmp() instead.

the if(1) has been inserted so we can keep the same indentation level
and not spam the commit with whitespace changes.
2020-09-21 11:31:52 +01:00
rofl0r e6c4764660 proxy_dns_old: use pipe2 if available, else O_CLOEXEC
make the old code a little less lame
2020-09-21 10:46:38 +01:00
rofl0r 2ab631918d add support for "proxy_dns_old" to use old 3.1 DNS lookup method
some lamer on IRC by the name of annoner/R3M0RS3/penis was complaining
that 3.1 is a lot better than proxychains-ng, because it happens to
work with the browser he's interested in.
since this wasn't the first time this is requested, let's give this
those lamers what they want: lame code!
2020-09-20 22:11:17 +01:00
rofl0r 3e791fd797 make sure allocator thread is only used if proxy_dns is requested 2020-09-20 18:21:40 +01:00
rofl0r 3a5050bec2 initialize allocator thread from get_chain_data if needed
since we caved in to demands that it should be possible to allow
hostnames in the proxy list section, we now got to deal with the
fallout. the code was calling at_get... assuming that the allocator
thread is always used.
2020-09-20 18:18:31 +01:00
rofl0r 3dfda493d8 only start allocator thread if proxy_dns is requested
this should fix problems with programs that do whacky
non-async-signal-safe stuff.
2020-09-20 18:17:51 +01:00
rofl0r ed8f8444ab allocator_thread: rework message sending structures
simplify code by adding a new at_msg struct that contains both
the message header and the message body.
this allow e.g. atomic writes of the whole message instead of doing
it in 2 steps. unfortunately reads still have to be done in at least
2 steps, since there are no atomicity guarantees[0].
additionally the message header shrunk from 8 to 4 bytes.

[0]: https://stackoverflow.com/questions/14661708/under-what-conditions-are-pipe-reads-atomic
2020-09-20 18:17:51 +01:00
rofl0r 12e5da1b90 get_chain_data: print debug info 2020-09-20 17:02:21 +01:00
rofl0r 121c582d9c debug: fix DUMP_PROXY_CHAIN() hack 2020-09-20 17:00:10 +01:00
rofl0r acf2f4725d fix build on FreeBSD due to usage of Dl_info 2020-09-05 14:36:05 +01:00
Ethan F 0ee5db605b
Add Haiku support (#340) 2020-08-17 09:31:04 +01:00
tom gilon bf2ef2ce38 dnat: add rule precedence logic 2020-07-08 19:35:18 +03:00
tom gilon de31961349 Add option to change tcp destination port and ip before sending to proxy server 2020-05-06 01:07:57 +03:00
Solar Flare b8fa2a7405 get own_dir by using dladdr() instead of argv[0] 2019-11-27 00:32:08 +08:00
Solar Flare 0a8663c845 fix a buffer overflow bug 2019-11-12 10:40:33 +08:00
rofl0r 86408cd806 add libc gethostbyname test 2019-09-07 15:23:02 +01:00
rofl0r ea187938e1 test_gethostent: improve compileability 2019-09-07 15:22:41 +01:00
rofl0r 962373e5c6 getaddrinfo: fix behaviour when node is null and !passive
according to the spec, if these 2 conditions hold, the name shall
resolve to localhost.

closes #292
2019-07-21 14:27:55 +01:00
rofl0r de4460fbd1 proxy_getaddrinfo: don't use sizeof(struct sockaddr_storage) for addr_len
this should fix an issue which seems to be mac's bind() only accepting
sizeof(struct sockaddr_in) for AF_INET.

ref: https://github.com/rofl0r/microsocks/issues/19
2019-05-25 02:23:38 +01:00
rofl0r 5ad7c2a183 proxy_getaddrinfo: implement support for numeric ipv6
closes #282
2019-04-25 14:36:08 +01:00
rofl0r 067885694d proxy url parser: look for @ from the right side
fixes usernames with @ in them.
this is only relevant for support of new url-style proxy addresses.
2019-04-21 01:48:38 +01:00
rofl0r e895fb713a release 4.14 2019-03-16 23:04:10 +00:00
rofl0r b8cdfe842c allow non-numeric proxy ips under certain circumstances
conditions that need to be met are:
1) chaintype strict
2) proxy_dns on
3) not the first proxy in the list

if these conditions are met, the dns name can be passed to be
receiving proxy and be resolved there.

addressing https://github.com/rofl0r/proxychains-ng/issues/246#issuecomment-468222637
2019-02-28 14:07:08 +00:00
rofl0r 9f17774b99 allocator_thread.c: whitespace cleanup 2019-02-28 13:32:57 +00:00
rofl0r dbec605e2c get_chain_data(): no need for inline 2019-02-28 13:28:10 +00:00
rofl0r 5c8f9a2922 shrink huge log buffer 2019-02-28 13:22:13 +00:00
rofl0r 50c079d4b4 don't try to connect to null-routed ips 2019-02-28 13:08:02 +00:00
Tom Li 11988579f5 allocator_thread.c: set O_CLOEXEC/FD_CLOEXEC for pipes, fix #273.
In proxychains, we create pipes and use them internally.
If exec() is called by the program we run, the pipes opened
previously are never closed, causing a file descriptor leak
may eventually crash the program.

This commit calls fcntl() to set FD_CLOEXEC flags on pipes.
AFAIK there's no race condition on pipe creation, but we still
prefer to call the newer pipe2() with O_CLOEXEC if it's supported
by the system, due to its advantage of atomic operation, which
prevents potential race conditions in the future.

Signed-off-by: Tom Li <tomli@tomli.me>
2018-12-25 18:03:39 +00:00
Tom Li db5cd6b699 configure: define HAVE_PIPE2 if we have pipe2() and O_CLOEXEC.
This commit adds a new run for pipe2() and O_CLOEXEC. If a program
can be executed, define HAVE_PIPE2.

Signed-off-by: Tom Li <tomli@tomli.me>
2018-12-25 18:03:39 +00:00
rofl0r a6959ee715 configure: force check_compile() to link an executable
by using -c (which just creates an object file), we don't catch implicit
function declarations as an error (see discussion of #274).
2018-12-25 18:01:26 +00:00
rofl0r 49bf4ba772 replace getservbyname_r ifdef hacks with configure check
this should make it work automatically on any new platform without
having to add yet another ifdef hack.
should fix issues with android (#265).
additionally the code for the systems lacking GNU-compatible getservbyname_r()
is now guarded with a mutex, which prevents possible races, therefore
resolving the ancient "TODO" item.
2018-12-02 13:48:43 +00:00
rofl0r 2213afb6f0 debug mode: display whether proxy_dns is on or off 2018-12-02 13:46:55 +00:00
rofl0r bd7e8a1da1 test_getaddrinfo.c: add check for service argument 2018-12-02 13:45:35 +00:00
rofl0r 416d481ac9 test_getaddrinfo.c: whitespace cleanup 2018-12-02 13:27:22 +00:00
amyangfei eb36238c8a remove unused variable 2018-08-26 06:18:20 +01:00
amyangfei 275e64499e Fix select_proxy dead loop in round_roubin_chain
Fix issue #147.
If all proxies are in DOWN_STATE or BUSY_STATE state, select_proxy will run
forever in an infinite loop. When all proxies are not available, we wait some
intervals and retry. The wait time starts with 10 milliseconds and is
increased by 10 milliiseconds in each loop. 14 loops sums up with 1.05 second.
2018-08-23 12:40:27 +01:00
rofl0r 1c8f8e4e7e alternatively allow specifying proxy addresses via URL-style strings
e.g. socks5://user:pass@ip:port

code taken from my library "rocksock"[0].

[0]: https://github.com/rofl0r/rocksock
2018-07-26 23:13:15 +01:00
rofl0r d21af711d8 release 4.13 2018-06-25 00:26:05 +01:00
rofl0r 49d8ac9338 accept proper RFC1929 auth subnegotiation version field
this was wrongly fixed in 06c20ed394

instead of reverting we now accept the correct version
(version field containing 1) plus the incorrect version (5) given by some
proxyservers in the wild. curl accepts both forms too.

closing #224
addressing #221
2018-05-29 18:59:30 +01:00
rofl0r bb30d867fe configure: prevent bug overwriting config.mak on OpenBSD
the command writing the openbsd line was using >> before the call
which was meant to initialize config.mak using >.

closes #228
2018-04-12 07:13:26 +01:00
rofl0r 06c20ed394 fix socks5 username/password auth
the version field in the auth check needs to be 5, not 1.

closes #221
2018-02-11 14:59:27 +00:00
rofl0r 831df039bd print usage info on --help too 2018-02-11 14:58:26 +00:00
rofl0r 1a62ec60af support solaris X/Open connect call too
solaris curiously defines connect to point to __xnet_connect when
_XOPEN_SOURCE is defined 600.
that means some programs use the real connect symbol, while others
use __xnet_connect.

thanks to @Low-power for testing.

https://github.com/nxmirrors/onnv/blob/master/usr/src/lib/libsocket/socket/socket.c
https://github.com/nxmirrors/onnv/blob/master/usr/src/uts/common/sys/socket.h#L486
2018-01-10 17:36:39 +00:00
WHR 35a674bdbc configure: Solaris detection, ld 'soname' option auto detection; other Solaris related fixes 2018-01-11 00:45:40 +08:00
papadave a1f7007a46 main.c: fix build error with solaris
sys/feature_tests.h:362:2: error: #error
"Compiler or options invalid for pre-UNIX 03 X/Open applications and pre-2001 POSIX applications"
2018-01-10 16:14:21 +00:00
rofl0r 3366dc3131 allocator_thread.c: fix build on FreeBSD due to MAP_ANON
thx to @Low-power for testing
2018-01-10 16:09:09 +00:00
rofl0r b299193d13 configure: remove bogus uname platform checks
calling uname in a configure script is entirely bogus, as it will return
wrong results in crosscompilation scenarios. the only sensible way to
detect the target platform's peculiarities is to test the preprocessor
for macros defining the target.
2018-01-09 13:50:11 +00:00
rofl0r 2f3d33dd47 remove usage of s6_addr16 and s6_addr32
it turns out that those macros are not portable at all. rather than
adding workarounds to make it work for every single platform, just
use plain s6_addr instead.
2018-01-09 13:30:02 +00:00
rofl0r d28f4df8e2 allocator_thread.c: define _DARWIN_C_SOURCE so we get MAP_ANON
https://github.com/nneonneo/osx-10.9-opensource/blob/master/xnu-2422.1.72/bsd/sys/mman.h#L142
https://opensource.apple.com/source/xnu/xnu-344/bsd/sys/mman.h
2017-12-21 16:30:17 +00:00
rofl0r 03880ce695 allocator_thread: add assertion that we get the right response
in order to prevent future bugs like the one fixed in cc7bc891ff
we need to assure that the response is of the same type as the request -
if not, some unexpected race condition happened.
2017-12-19 00:35:01 +00:00
rofl0r cc7bc891ff allocator_thread: fix segfault with weechat 2.0
it was reported that weechat 2.0 on ubuntu 16.04 LTS x86_64 segfaulted like this:

4 0x00007f6bf0e7e0c0 in __stack_chk_fail () at stack_chk_fail.c:28
5 0x00007f6bf2536bce in at_get_ip_for_host (host=0x339c4d0 "abcdefghijklmnop.onion", len=22) at src/allocator_thread.c:290
 readbuf = {octet = "irc.", as_int = 778269289} msg = {msgtype = ATM_GETNAME, datalen = 13}

what happened was that weechat forked, thus got its own private copy of the VM
and thus a private copy of the mutex which should prevent parallel use of
at_get_ip_for_host() & friends. therefore the following race was possible:
- process A writes a message of type ATM_GETIP into the server pipe
- process B writes a message of type ATM_GETNAME into the server pipe
- process A write transaction is finished, and goes into receive mode
- server thread reads process B's message and responds with a ATM_GETNAME msg
- process A reads the response which was intended for process B into the 4 byte
  ip address buffer, but ATM_GETNAME are much larger than ATM_GETIP responses,
  resulting in stack corruption.

to prevent this issue, the storage of the mutex must reside in shared memory,
which we achieve via mmap. alternatively, shm_open() or sysvipc shm stuff could
be used. the former requires the mmap call to happen before the fork, the latter
not, however the shm would require a named object in /dev/shm (which requires
generating a unique name per proxychains instance, and subsequent cleanup).
so in the end, the mmap is easier to deal with, and we can be reasonably
certain that our constructor is being run before the hooked application forks.
2017-12-19 00:29:23 +00:00
rofl0r 3b5f41028b allocator_thread: use bigger stacksize for Mac OS X 2017-12-15 13:15:13 +00:00
Antonio Quartulli 46647bee44 fix memory leak
don't leak variable 'space' when the host is numeric

Signed-off-by: Antonio Quartulli <a@unstable.cc>
2017-08-28 15:19:43 +01:00
rofl0r bb3df1e440 allocator_thread.c: handle EINTR case when reading/writing pipe data
addressing #163
2017-02-23 01:08:24 +00:00
rofl0r 7a233fb1f0 release 4.12
the xmas release.
2016-12-24 13:14:08 +00:00
rofl0r cd4ced1d52 Revert "Makefile: suppress pedantic warnings in user CFLAGS"
This reverts commit 6ae959e051.

It appears as if -pedantic is special in that there is no option
to disable it.
2016-12-24 12:49:14 +00:00
rofl0r cb70ab5f8f configure: use quotes for echo calls 2016-12-24 12:48:41 +00:00
Jatin Rungta c91e6a09ef Fix configure so the right CC gets picked up
unlike one would expect, setting `CC?=gcc -m32` in config.mak did not actually
lead to `gcc -m32` being used as compiler when running make, even though CC
was not declared anywhere else.
it appears as if the CC variable is implicitly defined by GNU make, so using
the ?= assignment (meaning "assign only if not already assigned") did not have
an effect.
when this configure script and Makefile here were written, they were modeled
after the interface provided by GNU autoconf (so there are no surprises for the
user). the assumption was that environment variables passed during configure
are usually stored and used for the compile, but can be overridden when running
make by exporting the variables again.
in reality though they can not be overridden by environment when running make,
as tests showed.
because of that, the other user-supplied variables will now be hard-assigned as
well.

closes #152

commit message by @rofl0r.
2016-12-24 12:36:42 +00:00
rofl0r bf6eeff75a check snprintf return value for error 2016-12-20 22:18:21 +00:00
rofl0r 6ae959e051 Makefile: suppress pedantic warnings in user CFLAGS 2016-12-13 20:42:50 +00:00
Carlos Maddela 5ed5089733 Avoid using %n$ operand number formats to compile cleanly with ISO C. 2016-12-13 20:27:56 +00:00
Carlos Maddela 8ddc8a6da3 Prevent empty translation units to satisfy ISO C compilers. 2016-12-13 20:27:15 +00:00
Carlos Maddela 167780ce36 Fix format ‘%p’ expects argument of type ‘void *’ warning. 2016-12-13 20:12:15 +00:00
Carlos Maddela 4b413c902f Fix format specifier for unsigned int. 2016-12-13 20:11:37 +00:00
Carlos Maddela 6dcaf533d1 Fix grammar in usage message to keep Lintian happy. 2016-12-05 18:37:11 +11:00
Carlos Maddela 0bd2130352 Fix spelling in log message: doesnt -> doesn't 2016-12-05 14:10:09 +11:00
forkbomber cf9a16de06 core.c: add HOST header to each CONNECT request
fixes #92
closes #93
2016-10-16 19:43:00 +00:00
rofl0r c883cd4940 configure: make buildsystem-set CPPFLAGS non-overridable
we temporarily store all buildsystem-set conditionals into
OUR_CPPFLAGS and write it into config.mak as an addition to eventually
user-supplied CPPFLAGS. this should prevent crucial things we set from
being overwritten by a user that has CPPFLAGS exported.

fixes #142
2016-10-16 11:28:05 +00:00
Jay Taylor 0f6b226b15 Fix random_chain on Mac OS X
On Mac OS X, random chain was broken and returned always the last proxy from the
config file.  Use fix as suggested by @ravomavain.

Closes #75.
2016-10-14 21:49:01 +00:00
rofl0r 260578d00e configure: do not use mktemp
apparently mktemp on OSX 10.9.5 requires a parameter.
instead of playing whack-a-mole with apple we now use the portable
code from musl's configure script which should work everywhere.

adresses #142
2016-10-08 21:02:13 +01:00
rofl0r e527b9ee64 print error message instead of segfaulting for invalid chain_len
closes #126
2016-06-23 09:27:15 +01:00
Carlos Maddela 635ded3393 Fix build failure with -pie in user LDFLAGS
When hardening flags are set by Debian's auto build system,
the project fails to build due to usage of -pie, which tells the linker
to build a PIE binary, and since the user LDFLAGS are deliberately put
later in the command line to override things, this overrides -shared.
work around by putting it directly in the last position of the linker
command line.

closes #124
Commit message authored by commiter.
2016-06-09 21:07:33 +01:00
Carlos Maddela 993dfc059d Fix trivial compilation warning
Fix "missing braces around initializer" warning.
2016-06-09 12:09:51 +01:00
rofl0r f1e5f2ba01 don't call dlsym() from close() hook
it turned out that calling dlsym() may call malloc() in turn,
so we end up with the same deadlock described in the latest commit.

we thus now put all the fds passed to close pre-init into a list
and close them at init time.

this may finally fix #119.
2016-05-26 19:11:18 +01:00
rofl0r 8870140ff0 don't call INIT() from close hook
it was observed that it is a bad idea to initialize the entire
infrastructure used by proxychains from the close hook,
because the following scenario will lead to a deadlock:

- it is possible that the dynlinker executes the initializer code of
  other shared libs first
- if that code directly or indirectly calls malloc()
- which calls close() if it decided to use an mmap based allocation
- will now call our close(), which does
- call pthread_once which requires a lock
- creates a thread which calls malloc()
- which in turn calls our close() another time
- and our close is still in locked state.

so it seems the only save thing to do is to just get the address
of the original close function, and call that when we're in a
pre-init state.
this may hold for other functions that do lazy initialization as well,
however for those just calling the original function is probably
undesired since that could result in unproxified connections.
it will be needed to analyze on a per-function basis what the best
thing to do is, and finally rely only on the execution of the init
function from the gcc initializer.

should fix #119
2016-05-26 10:48:32 +01:00
rofl0r aea9172653 release 4.11 2016-02-09 20:12:51 +00:00
rofl0r afdbfcf40c README: add 'Known Problems' section 2016-02-09 20:11:40 +00:00
rofl0r 058adbcac2 configure: whitespace cleanup in help text 2016-02-04 12:56:00 +00:00
rofl0r b64c89e0e4 add check for broken OpenBSD fclose()
http://marc.info/?l=openbsd-bugs&m=145280872431093&w=2

closes #95
2016-02-04 12:49:49 +00:00
rofl0r a1c31e73b6 improve hostsreader test code 2016-02-04 09:38:16 +00:00
Alexander Batischev f85cecdabe Fix bug in hostsreader
hostsreader_get() used to assign the IP address to both `name` and `ip`
fields in `struct hostsreader`, which led to proxychains effectively
ignoring the contents of /etc/hosts.
2016-02-04 09:37:06 +00:00
rofl0r 672bf7661d getnameinfo: support ipv6 as well 2015-12-06 13:01:56 +00:00
rofl0r 4c3be5e1e3 test_getnameinfo: improve, check ipv6 2015-12-06 13:01:07 +00:00
rofl0r 0e0e35927c mute warning in debug mode 2015-12-06 12:57:45 +00:00
rofl0r 205004fa2a factor out setup_hooks() 2015-12-02 12:14:58 +00:00
rofl0r 50c84176da debug.c: fix for ipv6 changes
closes #94
2015-12-01 20:37:27 +00:00
rofl0r 1294d0a004 configure: check for availability of s6_addr16
this should fix the build of the recently added ipv6 code on MacOS X,
OpenBSD and eventually FreeBSD.

closes #83
closes #85

thanks to @cam13 and @vonnyfly for reporting/testing.
2015-10-01 14:14:23 +01:00
rofl0r e9bf9623ba README: fix omission and whitespace 2015-09-19 11:09:41 +01:00
rofl0r 8a7081409e remove obsolete config.mak example
config.mak is autogenerated by the configure script since a long time.
there's no need to supply the example anymore, and it appears a lot
of people are looking into the directory expecting to find a binary
distribution.
2015-09-15 22:00:43 +01:00
rofl0r 32df7ff152 connect(): handle ipv4-mapped ipv6 addresses
if an ipv4-mapped ipv6 address is detected, the ip is converted
into v4 format because it may actually be one of our remote dns ips.
it was reported that a program called "maven", when getting handed our
fake ips in the remote dns subnet, converts the ip to v6 prior to calling
connect():
[proxychains] Strict chain ... 127.0.0.1:1080 ... ::ffff:224.0.0.1:443
<--socket error or timeout!

fixes #77
2015-09-15 21:19:51 +01:00
rofl0r 097c7f9125 add testcase for ipv4-mapped ipv6 address 2015-09-15 21:14:58 +01:00
rofl0r 2237749567 preliminary ipv6 support
only basic testing was done (with 2 socks5 proxies listening on ::1)
but seems to work as intended.

ipv6 support for the hostsreader (/etc/hosts) is not implemented so far.
2015-08-10 17:00:26 +01:00
rofl0r 9969dd3a22 fix socks5 bug: always requested user auth cap
since "user" always points to a statically allocated string buffer,
the test for if(user)... was bogus.
use ulen instead.

this bug should only be visible on socks servers that require auth
if username was not passed, so it was probably not really an issue.
2015-06-14 12:10:32 +01:00
rofl0r d900b090fe put INIT() call consistently at beginning of hooked funcs 2015-06-14 11:16:59 +01:00
rofl0r afe6171cad clean up some debug ifdefs 2015-06-14 10:53:33 +01:00
rofl0r 51b2eb91ce remove commented-out code [2] 2015-06-14 10:27:41 +01:00
rofl0r ae16ae9fc9 remove commented-out code 2015-06-14 09:57:05 +01:00
rofl0r 338b9ce4e3 whitespace fixes for proxytype switch block 2015-06-13 20:32:15 +01:00
rofl0r c6553c2cc5 replace string manip. in HTTP setup code with single snprintf 2015-06-13 20:21:59 +01:00
rofl0r 49adb6ce29 simplify socks5 buffer setup code 2015-06-13 19:02:11 +01:00
rofl0r c7fa7bf86a simplify start_chain struct setup 2015-06-13 18:37:57 +01:00
rofl0r 29df9abec3 release 4.10 2015-06-09 08:23:28 +02:00
rofl0r 2182eff358 fix segfault in DNS mapping lookup code
the allocatorthread got pointers to RAM which were reallocated
behind the back, and if realloc() couldn't grow in-place, lead
to segfaults in applications that do a lot of DNS-lookups such
as webbrowsers.

closes #66
closes #31

thanks to @ravomavain for tracking down the issue.
2015-06-06 11:43:53 +01:00
rofl0r 53c6c2ca9b configure: respect user LDFLAGS without breaking link order 2015-06-04 21:11:08 +01:00
rofl0r c9c51d6705 Revert "Fix LDFLAGS"
This reverts commit e79e05a228.

This commit broke link order for a number of people.
2015-06-04 21:04:30 +01:00
rofl0r fda4ba37ec Revert "fix makefile link order"
This reverts commit 377b474b40.

There still are problems with the link order.
Revert to the known-good version.
2015-06-04 21:03:25 +01:00
rofl0r f35f14c1ed release 4.9 2015-05-28 08:35:57 +02:00
rofl0r 68e42d59f7 fixup for 9ab7dbe 2015-05-21 14:04:10 +01:00
rofl0r 9ab7dbeb3b fix for CVE-2015-3887
closes #60
2015-05-21 13:46:22 +01:00
rofl0r ba61b48fd7 fix compilation with openbsd
closes #52
2015-04-08 11:09:48 +01:00
jackyzy823 377b474b40 fix makefile link order 2015-04-03 22:37:26 +08:00
rofl0r d461f397b2 Merge pull request #51 from tyll/ldflags
Fix LDFLAGS
2015-03-22 19:34:09 +01:00
rofl0r 30495fde39 Merge pull request #44 from sarum9in/master
add sendto hook to handle MSG_FASTOPEN flag
2015-03-22 19:32:17 +01:00
Till Maas e79e05a228 Fix LDFLAGS
- Use user-supplied LDFLAGS
- Use LDFLAGS for linking proxychains4
2015-03-15 11:46:31 +01:00
Aleksey Filippov 4e986caa2a support MSG_FASTOPEN on old kernels 2015-02-17 15:30:43 +01:00
Aleksey Filippov 8dd08e2cd2 add sendto hook to handle MSG_FASTOPEN flag 2015-01-23 17:14:37 +01:00
rofl0r ea51cdac29 README: fix typo 2014-11-15 17:54:15 +01:00
rofl0r 25ee4c318d hostsreader: use temporary vars for string manipulation
working directly with the passed variables could lead to bugs when
some lines in the hosts file aren't well-formed and the loop is taken
several times while the buf vars are already modified.
2014-11-14 13:19:06 +01:00
rofl0r 4fb7eb0532 replace problematic hostentdb with hostsreader
the hostentdb introduced between 4.2 and 4.3
(via af5c6f0c6a )
had several issues:
- it caused breakage on FreeBSD and was commented out there
- prevented usage of the hostdb when proxy_dns was turned off
  (issue #42)
- required dynamic memory allocation which was accessed from several
  threads
- wouldnt reflect changes to the hosts file made during program run

the only sensible solution is to remove the hostentdb and replace it
with a home-grown hosts parser (we can't use gethostent() since
that would mess up the gethostent()-state from different threads).

the new parser used here is deliberately held simple and only meant
to provide the user with means to reference hardcoded ipv4 addresses
via his hosts file.

fixes #42
2014-11-14 12:33:58 +01:00
rofl0r 567935b1ab fix FSF address in COPYING to mute opensuse build service complaints 2014-09-13 23:33:26 +02:00
rofl0r 631a8059d9 release 4.8.1 2014-07-22 17:22:34 +02:00
rofl0r d8a08707e7 fix regression in install-config Makefile target
closes #34
2014-07-22 17:21:14 +02:00
rofl0r a30f514309 release 4.8 2014-07-22 15:33:53 +02:00
rofl0r 840b361897 configure: hint that gmake should be used on BSD 2014-07-22 14:56:49 +02:00
rofl0r 9f8db927d9 update .gitignore 2014-07-22 14:34:13 +02:00
rofl0r 6143266edd use musl's install.sh rather than doing workarounds for BSD install 2014-07-22 14:32:27 +02:00
rofl0r cd4aee1997 print proxychains version on DLL init
framework to print version stolen from musl
2014-07-22 14:10:11 +02:00
rofl0r 7852269282 libproxychains.c: whitespace cleanup 2014-07-21 13:18:20 +02:00
rofl0r d3586380bd get_chain_data: reject invalid entries in proxylist section 2014-07-21 13:17:24 +02:00
rofl0r 5168bc4eed bail out when no proxy was configured 2014-07-21 12:37:01 +02:00
rofl0r 82d0b13b8f main.c: remove trailing whitespace noise 2014-07-09 19:16:33 +02:00
rofl0r ed7c89072a main.c: append previously existing LD_PRELOAD contents rather than overwriting
some broken programs like pulseaudio rely on LD_PRELOAD hacks to function,
if we just override the environment variable, those will stop working.

simplified version of patch suggested by @hexchain

closes #35
2014-07-09 19:12:30 +02:00
rofl0r 84d9a97a08 main.c: remove code duplication around LD_PRELOAD 2014-07-09 18:07:24 +02:00
rofl0r f669139c9e common.c: fix trailing whitespace 2014-07-02 10:10:53 +02:00
rofl0r 69abe128ca Makefile: respect CPPFLAGS 2014-02-02 09:49:21 +01:00
rofl0r 3dd2fa7782 Makefile: add proper dependency info for install targets 2014-02-02 09:46:57 +01:00
rofl0r e34d417b55 README: fix typo in contributor name 2014-01-22 22:33:09 +01:00
rofl0r 8519518b92 update AUTHORS 2014-01-22 22:33:09 +01:00
rofl0r 530fee89ce proxy_getaddrinfo: don't use strncpy
the strncpy function is both dangerous and slow.
dangerous because it doesn't do what the naive programmer expects
(bounded strcpy), and slow because it pads the entire bufsize
with zeroes.
2014-01-22 22:22:24 +01:00
rofl0r ca14801d52 update README 2014-01-22 16:15:49 +01:00
rofl0r b76aa653c9 proxy_getaddrinfo: fix case when func was used in lieu of inet_aton 2014-01-22 16:13:20 +01:00
rofl0r 63ad1b4d70 remove obsolete ChangeLog 2014-01-08 15:33:44 +01:00
rofl0r ad3c0aa58b start 4.8 release cycle. 2014-01-08 15:18:32 +01:00
rofl0r 5847da1d1c README: update release notes for 4.7 2014-01-08 15:05:33 +01:00
rofl0r f868928c4b fix incorrect poll.h inclusion
sys/poll.h is a glibc legacy alias for poll.h.
the latter is specified by POSIX, the former not.
on glibc one of them just includes the other so it doesnt hurt.
2014-01-08 14:57:13 +01:00
rofl0r 582b3ced26 Merge pull request #28 from pocographdotcom/master
Chromium tried to close our pipes and falls into infinity loop.
2014-01-08 05:38:52 -08:00
David ecbd735508 Chromium tried to close our pipes and falls into infinity loop.
If return value of close() is -1, chromium will fall into infinity loop.
2014-01-08 13:38:59 +08:00
Nikki McCavee e2af2f2bd7 Add option to build for i386 architecture on x64 Intel Macs
closes #26
closes #27
2014-01-02 14:25:38 +01:00
rofl0r 44150485cb update README 2013-09-22 05:45:47 +02:00
rofl0r fa0f355ce8 add missing INIT() to close hook
this caused a crash when the gcc initializer was not called first.
2013-08-30 23:44:27 +02:00
rofl0r 8a84f980bb fix indentation of debug.c 2013-06-26 12:22:12 +02:00
crass 354a4ce4e2 Add round_robin to example config. 2013-06-26 12:22:12 +02:00
crass f603e50cb3 Add support for round robin mode. 2013-06-26 12:22:11 +02:00
crass 5c4c166802 Add DUMP_PROXY_CHAIN for debug builds and debug.c. 2013-06-25 12:56:41 +02:00
rofl0r b9ca1cdefd proxychains.conf: add hint that proxy must be in ipv4 notation 2013-05-02 13:44:49 +02:00
rofl0r 64a7cd26dc fix case where proxy was using a DNS name or non-dotted ipv4
it is generally invalid to use a DNS name since DNS subsystem
is only available once connected to the proxy; because
DNS is done server-side.

closes #19
2013-05-02 13:44:49 +02:00
rofl0r 9f6ed6ed90 Merge pull request #18 from mancha1/master
Fix NULL pointer deref (issue #17)
2013-04-30 05:41:45 -07:00
mancha 2aba83087e libproxychains.c: fix NULL pointer dereference after fopen().
if a configuration file can be accessed by proxychains but there is a
mandatory access control (or other) block on the target appication's
ability to read that file, fopen() creates a NULL pointer that will
cause a segfault in fgets().

closes #17

Signed-off-by: mancha <mancha1@hush.com>
2013-04-30 04:06:36 -04:00
rofl0r 8a93f45007 README: add hint about IRC channel 2013-03-05 13:48:06 +01:00
rofl0r 73ff65ed76 Makefile: prevent from using 2 slashes (cosmetic change) 2013-02-10 12:38:05 +01:00
rofl0r aa1b9df2cb overhaul README
especially mentioning that proxychains is a HACK so it may not work.
it is a hack because it modifies existing programs in a way not
originally intended by its authors.
additionally it relies on a very complicated and fragile dynamic
linker infrastructure which can easily break, as is the case with
glibc-linked programs that use dlopen() (see issue #10).
2013-02-10 09:54:03 +01:00
rofl0r f3af1239a9 better regex for obsolete proxyresolv script (thx yhzarcali)
closes #11
2013-01-29 18:43:21 +01:00
rofl0r 1da09e49e5 hook close() to prevent rude programs like ssh to close our pipes
those pipes are needed to talk with the dns-name allocator thread.

closes #9
2013-01-21 01:54:45 +01:00
rofl0r a8e8cced6d README: add disclaimer. 2013-01-06 21:42:02 +01:00
rofl0r 2efe207dde README: add bold warnings about risks 2013-01-06 21:23:44 +01:00
rofl0r 5d7715551d Makefile: add install-data to .PHONY 2013-01-06 19:33:34 +01:00
rofl0r 5d9148a900 README: mention install-config 2013-01-06 19:32:55 +01:00
rofl0r 4f7363efbc Makefile: put include config later so the program name can be overridden 2013-01-06 19:26:01 +01:00
rofl0r 173b90368e update proxyresolv 2013-01-06 19:20:44 +01:00
rofl0r 5f433adfed fine-tune configure for BSD 2013-01-06 19:18:04 +01:00
rofl0r 52cbc8f87d post-release update of README 2013-01-06 19:14:43 +01:00
rofl0r c8bfdc15e6 remove old proxychains launcher script 2013-01-06 19:12:15 +01:00
rofl0r 5526afb56d FreeBSD support 2012-12-25 19:08:05 +01:00
rofl0r be4efc0fd5 fix no-newline warnings on old compilers 2012-12-25 18:01:11 +01:00
rofl0r ab4fb353b6 fix for mac build error
closes #6
2012-12-18 09:42:17 +01:00
rofl0r 5ecd5ac51d fix compilation on musl libc 2012-12-18 09:38:32 +01:00
rofl0r d888e4ebf4 add test for getnameinfo 2012-12-17 23:22:25 +01:00
rofl0r 1c265b9628 getnameinfo: check size and family of salen 2012-12-17 23:21:58 +01:00
rofl0r 346474a43b getnameinfo: return error if buffers are too small 2012-12-17 22:41:51 +01:00
rofl0r ce655fdac8 fix the never-ending issues with the wrong glibc prototype of getnameinfo
this bug was fixed shortly before 2.14 release, so we checked for that.
however some distros decided to backport this fix to earlier versions,
breaking our compiletime check.

http://sourceware.org/git/?p=glibc.git;a=commitdiff;h=e4ecafe004b3d4270b3a9dace8f970047400ed38

the portable solution is to stick the function into a separate comilation
unit that does not see the glibc prototype.

closes #7
2012-12-17 22:17:04 +01:00
53 changed files with 3507 additions and 919 deletions

5
.gitignore vendored
View File

@ -1,3 +1,7 @@
proxychains4
proxychains4-daemon
*.bz2
*.xz
*.o
*.so
*.la
@ -8,6 +12,7 @@
*.out
*~
*.patch
version.h
# Autoconf stuff
libtool

View File

@ -6,13 +6,17 @@ netcreature@users.sourceforge.net
main.c, remote-dns, thread safety, bugfixes, build system,
cleanups, mac support
rofl0r.
https://github.com/rofl0r/proxychains
https://github.com/rofl0r/proxychains-ng
localnet, bugfixes
jianing yang.
https://github.com/jianingy/proxychains
https://sourceforge.net/projects/proxychains/forums/forum/644747/topic/3498696
round-robin
crass.
https://github.com/crass/proxychains-ng
poll_retry (fixes for signal handling)
colin cross.
https://sourceforge.net/projects/proxychains/forums/forum/644747/topic/2367923

View File

@ -1,8 +1,8 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, USA
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

View File

@ -1,65 +0,0 @@
ProxyChains version history (public releases)
====================
ver 3.1
changed:
* dns resolver script fix
* prototypes in core.h
-------------------------------------------------------------------------
ver 3.0
added:
* new feature - DNS from behind proxy
* proxyresolv - stand alone command
* proxychains.conf - new option to enable/disable DNS support
changed:
* bugfixes in core lib
* fixed strict chain
* fixed random chain
* output text
* autotools fix
-------------------------------------------------------------------------
ver 2.1
* bugfuxes
-------------------------------------------------------------------------
ver 2.0
* major core rewrite
* new config options
-------------------------------------------------------------------------
ver 1.8.2
* minor bugfixes
* improved compilation on FreeBSD & OpenBSD sysems.
* improved compilation on Sun Solaris systems .
* cross platform (UNIX) issues
-------------------------------------------------------------------------
ver 1.8.0
added:
* Socks5 protocol
* Socks4 protocol
* HTTP proxy auth basic
* Socks4 user auth
* Socks5 user/pass auth
* more chain options (random, strict, dynamic )
* configurable timeout for TCP connect.
* configurable timeout for TCP read.
* INSTALL file (explains how to install properly)
changed:
* configuration file entries (proxychains.conf)
* configuration file lookup
-------------------------------------------------------------------------
ver 0.0.1
* TCP calls interception
* HTTP CONNECT proxy protocol.

View File

@ -11,34 +11,47 @@ bindir = $(exec_prefix)/bin
prefix = /usr/local/
includedir = $(prefix)/include
libdir = $(prefix)/lib
sysconfdir=$(prefix)/etc
sysconfdir = $(prefix)/etc
zshcompletiondir = $(prefix)/share/zsh/site-functions
SRCS = $(sort $(wildcard src/*.c))
OBJS = $(SRCS:.c=.o)
LOBJS = src/core.o src/common.o src/libproxychains.o src/shm.o \
src/allocator_thread.o src/ip_type.o src/stringdump.o \
src/hostentdb.o src/hash.o
OBJS = src/common.o src/main.o
DOBJS = src/daemon/hsearch.o \
src/daemon/sblist.o src/daemon/sblist_delete.o \
src/daemon/daemon.o src/daemon/udpserver.o
LOBJS = src/version.o \
src/core.o src/common.o src/libproxychains.o \
src/allocator_thread.o src/rdns.o \
src/hostsreader.o src/hash.o src/debug.o
GENH = src/version.h
CFLAGS += -Wall -O0 -g -std=c99 -D_GNU_SOURCE -pipe
LDFLAGS = -shared -fPIC -Wl,--no-as-needed -ldl -lpthread
NO_AS_NEEDED = -Wl,--no-as-needed
LDFLAGS = -fPIC $(NO_AS_NEEDED) $(LIBDL) $(PTHREAD)
INC =
PIC = -fPIC
AR = $(CROSS_COMPILE)ar
RANLIB = $(CROSS_COMPILE)ranlib
SOCKET_LIBS =
LDSO_SUFFIX = so
LD_SET_SONAME = -Wl,-soname=
INSTALL_FLAGS = -D -m
-include config.mak
INSTALL = ./tools/install.sh
LDSO_PATHNAME = libproxychains4.$(LDSO_SUFFIX)
SHARED_LIBS = $(LDSO_PATHNAME)
ALL_LIBS = $(SHARED_LIBS)
PXCHAINS = proxychains4
ALL_TOOLS = $(PXCHAINS)
PXCHAINS_D = proxychains4-daemon
ALL_TOOLS = $(PXCHAINS) $(PXCHAINS_D)
ALL_CONFIGS = src/proxychains.conf
ZSH_COMPLETION = completions/zsh/_proxychains4
-include config.mak
CFLAGS+=$(USER_CFLAGS) $(MAC_CFLAGS)
CFLAGS_MAIN=-DLIB_DIR=\"$(libdir)\" -DSYSCONFDIR=\"$(sysconfdir)\" -DDLL_NAME=\"$(LDSO_PATHNAME)\"
@ -46,28 +59,48 @@ CFLAGS_MAIN=-DLIB_DIR=\"$(libdir)\" -DSYSCONFDIR=\"$(sysconfdir)\" -DDLL_NAME=\"
all: $(ALL_LIBS) $(ALL_TOOLS)
install-config:
install -d $(DESTDIR)/$(sysconfdir)
install $(INSTALL_FLAGS) 644 src/proxychains.conf $(DESTDIR)/$(sysconfdir)/
install: install-libs install-tools
install:
install -d $(DESTDIR)/$(bindir)/ $(DESTDIR)/$(libdir)/
install $(INSTALL_FLAGS) 755 $(ALL_TOOLS) $(DESTDIR)/$(bindir)/
install $(INSTALL_FLAGS) 644 $(ALL_LIBS) $(DESTDIR)/$(libdir)/
$(DESTDIR)$(bindir)/%: %
$(INSTALL) -D -m 755 $< $@
$(DESTDIR)$(libdir)/%: %
$(INSTALL) -D -m 644 $< $@
$(DESTDIR)$(sysconfdir)/%: src/%
$(INSTALL) -D -m 644 $< $@
$(DESTDIR)$(zshcompletiondir)/%: completions/zsh/%
$(INSTALL) -D -m 644 $< $@
install-libs: $(ALL_LIBS:%=$(DESTDIR)$(libdir)/%)
install-tools: $(ALL_TOOLS:%=$(DESTDIR)$(bindir)/%)
install-config: $(ALL_CONFIGS:src/%=$(DESTDIR)$(sysconfdir)/%)
install-zsh-completion: $(ZSH_COMPLETION:completions/zsh/%=$(DESTDIR)$(zshcompletiondir)/%)
clean:
rm -f $(ALL_LIBS)
rm -f $(ALL_TOOLS)
rm -f $(OBJS)
rm -f $(OBJS) $(LOBJS) $(DOBJS)
rm -f $(GENH)
src/version.h: $(wildcard VERSION .git)
printf '#define VERSION "%s"\n' "$$(sh tools/version.sh)" > $@
src/version.o: src/version.h
%.o: %.c
$(CC) $(CFLAGS) $(CFLAGS_MAIN) $(INC) $(PIC) -c -o $@ $<
$(CC) $(CPPFLAGS) $(CFLAGS) $(CFLAGS_MAIN) $(INC) $(PIC) -c -o $@ $<
$(LDSO_PATHNAME): $(LOBJS)
$(CC) $(LDFLAGS) $(LD_SET_SONAME)$(LDSO_PATHNAME) -o $@ $(LOBJS)
$(CC) $(LDFLAGS) $(FAT_LDFLAGS) $(LD_SET_SONAME)$(LDSO_PATHNAME) \
$(USER_LDFLAGS) -shared -o $@ $^ $(SOCKET_LIBS)
$(ALL_TOOLS): $(OBJS)
$(CC) src/main.o src/common.o -o $(PXCHAINS)
$(PXCHAINS): $(OBJS)
$(CC) $^ $(FAT_BIN_LDFLAGS) $(USER_LDFLAGS) $(LIBDL) -o $@
$(PXCHAINS_D): $(DOBJS)
$(CC) $^ $(FAT_BIN_LDFLAGS) $(USER_LDFLAGS) -o $@
.PHONY: all clean install
.PHONY: all clean install install-config install-libs install-tools install-zsh-completion

204
README
View File

@ -1,33 +1,155 @@
ProxyChains ver 4.3 README
==========================
ProxyChains-NG ver 4.17 README
=============================
ProxyChains is a UNIX program, that hooks network-related libc functions
in dynamically linked programs via a preloaded DLL and redirects the
connections through SOCKS4a/5 or HTTP proxies.
in DYNAMICALLY LINKED programs via a preloaded DLL (dlsym(), LD_PRELOAD)
and redirects the connections through SOCKS4a/5 or HTTP proxies.
It supports TCP only (no UDP/ICMP etc).
The way it works is basically a HACK; so it is possible that it doesn't
work with your program, especially when it's a script, or starts
numerous processes like background daemons or uses dlopen() to load
"modules" (bug in glibc dynlinker).
It should work with simple compiled (C/C++) dynamically linked programs
though.
If your program doesn't work with proxychains, consider using an
iptables based solution instead; this is much more robust.
Supported Platforms: Linux, BSD, Mac, Haiku.
*********** ATTENTION ***********
this program works only on dynamically linked programs.
also both proxychains and the program to call must use
the same dynamic linker (i.e. same libc).
why ? because in order to hook to libc functions like
connect(), dynamic loader facilities are used, namely
dl_sym() and LD_PRELOAD.
this program can be used to circumvent censorship.
doing so can be VERY DANGEROUS in certain countries.
*********************************
ALWAYS MAKE SURE THAT PROXYCHAINS WORKS AS EXPECTED
BEFORE USING IT FOR ANYTHING SERIOUS.
this involves both the program and the proxy that you're going to
use.
for example, you can connect to some "what is my ip" service
like ifconfig.me to make sure that it's not using your real ip.
ONLY USE PROXYCHAINS IF YOU KNOW WHAT YOU'RE DOING.
THE AUTHORS AND MAINTAINERS OF PROXYCHAINS DO NOT TAKE ANY
RESPONSIBILITY FOR ANY ABUSE OR MISUSE OF THIS SOFTWARE AND
THE RESULTING CONSEQUENCES.
*** Installation ***
# needs a working C compiler, preferably gcc
./configure
./configure --prefix=/usr --sysconfdir=/etc
make
[optional] sudo make install
[optional] sudo make install-config (installs proxychains.conf)
if you dont install, you can use proxychains from the build directory
like this: ./proxychains4 -f src/proxychains.conf telnet google.com 80
Changelog:
----------
Version 4.17
- add hook for close_range function, fixing newer versions of openssh
- fat-binary-m1 option for mac
- fix DNS error handling in proxy_dns_old
- simplify init code
- fix openbsd preloading
- fix double-close in multithreaded apps
- various improvements to configure script
Version 4.16
- fix regression in configure script linker flag detection
- remove 10 year old workaround for wrong glibc getnameinfo signature
- support for new DYLD hooking method for OSX Monterey
- netbsd compilation fix
- support IPv6 localnets
- more user-friendly error message when execvp fails
- proxy_getaddrinfo(): fill in ai_socktype if requested
Version 4.15
- fix configure script for buggy binutils version
- initialize rand_seed with nano-second granularity
- add support for numeric ipv6 in getaddrinfo
- fix bug in getaddrinfo when node is null and !passive
- add dnat feature
- add raw proxy type
- add haiku support
- add proxy_dns_old to emulate proxychains 3.1 behaviour
- add new proxy_dns_daemon feature (experimental)
- various other fixes
Version 4.14
- allow alternative proto://user:pass@ip:port syntax for proxylist
- fix endless loop in round robin mode when all proxies are down (#147)
- fix compilation on android (#265)
- fix fd leak in forked processes (#273)
- skip connection attempt to nullrouted ips
- allow hostnames for proxylist under specific circumstances
Version 4.13
- fix robustness of DNS lookup thread and a segfault
- fix socks5 user/pass auth on non-conforming servers
- fix memory leak
- add support for Solaris
Version 4.12
- fix several build issues
- for MAC
- with -pie
- with custom CC
- compatibility fix for some GUI apps (8870140)
- compatibility fix for some HTTP proxies (cf9a16d)
- fix several warnings for cleaner build on debian
- fix random_chain on OSX (0f6b226)
Version 4.11
- preliminary IPv6 support
- fixed bug in hostsreader
- preliminary support for usage on OpenBSD (caveat emptor)
Version 4.10
- fix regression in linking order with custom LDFLAGS
- fix segfault in DNS mapping code in programs with > ~400 different lookups
Version 4.9
- fix a security issue CVE-2015-3887
- add sendto hook to handle MSG_FASTOPEN flag
- replace problematic hostentdb with hostsreader
- fix compilation on OpenBSD (although doesn't work there)
Version 4.8.1:
- fix regression in 4.8 install-config Makefile target
Version 4.8:
- fix for odd cornercase where getaddrinfo was used with AI_NUMERICHOST
to test for a numeric ip instead of resolving it (fixes nmap).
- allow usage with programs that rely on LD_PRELOAD themselves
- reject wrong entries in config file
- print version number on startup
Version 4.7:
- new round_robin chaintype by crass.
- fix bug with lazy allocation when GCC constructor was not used.
- new configure flag --fat-binary to create a "fat" binary/library on OS X
- return EBADF rather than EINTR in close hook.
it's legal for a program to retry close() calls when they receive
EINTR, which could cause an infinite loop, as seen in chromium.
Version 4.6:
- some cosmetic fixes to Makefile, fix a bug when non-numeric ip was
used as proxy server address.
Version 4.5:
- hook close() to prevent OpenSSH from messing with internal infrastructure.
this caused ssh client to segfault when proxified.
Version 4.4:
- FreeBSD port
- fixes some installation issues on Debian and Mac.
Version 4.3:
- fixes programs that do dns-lookups in child processes (fork()ed),
@ -40,13 +162,13 @@ Version 4.2:
- fixes compilation issues with ubuntu 12.04 toolchain
- fixes segfault in rare codepath
Version 4.1
Version 4.1
- support for mac os x (all archs)
- all internal functions are threadsafe when compiled with -DTHREAD_SAFE
- all internal functions are threadsafe when compiled with -DTHREAD_SAFE
(default).
Version 4.0
- replaced dnsresolver script (which required a dynamically linked "dig"
- replaced dnsresolver script (which required a dynamically linked "dig"
binary to be present) with remote DNS lookup.
this speeds up any operation involving DNS, as the old script had to use TCP.
additionally it allows to use .onion urls when used with TOR.
@ -56,7 +178,7 @@ Version 4.0
environment variables.
Version 3.0
- support for DNS resolving through proxy
- support for DNS resolving through proxy
supports SOCKS4, SOCKS5 and HTTP CONNECT proxy servers.
Auth-types: socks - "user/pass" , http - "basic".
@ -78,10 +200,9 @@ Some cool features:
random order from the list ( user defined length of chain ).
exact order (as they appear in the list )
dynamic order (smart exclude dead proxies from chain)
* You can use it with any TCP client application, even network scanners
yes, yes - you can make portscan via proxy (or chained proxies)
for example with Nmap scanner by fyodor (www.insecire.org/nmap).
proxychains nmap -sT -PO -p 80 -iR (find some webservers through proxy)
* You can use it with most TCP client applications, possibly even network
scanners, as long as they use standard libc functionality.
pcap based scanning does not work.
* You can use it with servers, like squid, sendmail, or whatever.
* DNS resolving through proxy.
@ -90,13 +211,13 @@ Configuration:
--------------
proxychains looks for config file in following order:
1) file listed in environment variable ${PROXYCHAINS_CONF_FILE} or
1) file listed in environment variable PROXYCHAINS_CONF_FILE or
provided as a -f argument to proxychains script or binary.
2) ./proxychains.conf
3) $(HOME)/.proxychains/proxychains.conf
4) /etc/proxychains.conf **
4) $(sysconfdir)/proxychains.conf **
**see more in /etc/proxychains.conf
** usually /etc/proxychains.conf
Usage Example:
@ -107,9 +228,9 @@ specified by proxychains.conf
Usage Example:
$ proxychains -f /etc/proxychains-other.conf targethost2.com
$ proxychains -f /etc/proxychains-other.conf telnet targethost2.com
in this example it will use different configuration file then proxychains.conf
in this example it will use different configuration file then proxychains.conf
to connect to targethost2.com host.
Usage Example:
@ -119,3 +240,36 @@ Usage Example:
in this example it will resolve targethost.com through proxy(or chained proxies)
specified by proxychains.conf
Known Problems:
---------------
- newer versions of nmap try to determine the network interface to use
even if it's not needed (like when doing simple syn scans which use the
standard POSIX socket API. this results in errors when proxychains hands
out an ip address to a reserved address space.
possible workarounds: disable proxy_dns, use a numeric ip, or use nmap's
native support for SOCKS proxies.
- Mac OS X 10.11 (El Capitan) ships with a new security feature called SIP
that prevents hooking of system apps.
workarounds are to partially disable SIP by issuing
csrutil enable --without debug in recovery mode,
or to copy the system binary into the home directory and run it from there.
see github issue #78 for details.
- the glibc dynlinker has a bug or security feature that inhibits dlopen()ed
modules from being subject to the same dlsym hooks as installed for the main
program. this mainly affects scripting languages such as perl or python
that heavily rely on dlopen() for modules written in C to work.
there are unconfirmed reports that it works as root though.
musl libc is unaffected from the bug.
Community:
----------
#proxychains on irc.libera.chat
Donations:
----------
bitcoins donations are welcome - please send to this address:
1C9LBpuy56veBqw5N33sZMoZW8mwCw3tPh

1
VERSION Normal file
View File

@ -0,0 +1 @@
4.17

View File

@ -0,0 +1,8 @@
#compdef proxychains4
_arguments \
'(- : *)--help[More help in README file]' \
'-q[makes proxychains quiet - this overrides the config setting]' \
'-f[allows one to manually specify a configfile to use]: :_files' \
'(-)1: :{_command_names -e}' \
'*:: :_normal'

250
configure vendored
View File

@ -1,15 +1,94 @@
#!/bin/sh
prefix=/usr/local
OUR_CPPFLAGS=
# Get a temporary filename
fail() { printf "%s\n" "$1" >&2 ; exit 1 ; }
i=0
set -C
while : ; do i=$(($i+1))
tmpc="./conf$$-$PPID-$i.c"
2>|/dev/null > "$tmpc" && break
test "$i" -gt 50 && fail "$0: cannot create temporary file $tmpc"
done
set +C
trap 'rm "$tmpc"' EXIT INT QUIT TERM HUP
check_compile() {
printf "checking %s ... " "$1"
printf "$3" > "$tmpc"
local res=0
$CC $OUR_CPPFLAGS $CPPFLAGS $2 $CFLAGS "$tmpc" -o "$tmpc".out >/dev/null 2>&1 \
|| res=1
test x$res = x0 && \
{ printf "yes\n" ; test x"$2" = x || OUR_CPPFLAGS="$OUR_CPPFLAGS $2" ; } \
|| printf "no\n"
rm -f "$tmpc".out
return $res
}
get_define() {
$CC $OUR_CPPFLAGS $CPPFLAGS $CFLAGS -dM -E - </dev/null | grep "$1"
}
get_define_stripped() {
local output=$(get_define "$1")
test "$?" = 0 || return 1
printf "%s\n" "$output" | sed 's/^.* .* //'
}
check_define() {
printf "checking whether \$CC defines %s ... " "$1"
local res=1
get_define "$1" >/dev/null && res=0
test x$res = x0 && printf "yes\n" || printf "no\n"
return $res
}
check_compile_run() {
printf "checking %s ... " "$1"
printf "$2" > "$tmpc"
local res=0
$CC $OUR_CPPFLAGS $CPPFLAGS $CFLAGS "$tmpc" -o "$tmpc".out >/dev/null 2>&1 \
|| res=1
test x$res = x0 && { "$tmpc".out || res=1 ; }
rm -f "$tmpc".out
test x$res = x0 && printf "yes\n" || printf "no\n"
return $res
}
check_link_silent() {
printf "$2" > "$tmpc"
local res=0
$CC $OUR_CPPFLAGS $CPPFLAGS $1 $CFLAGS "$tmpc" -o "$tmpc".out >/dev/null 2>&1 || res=1
rm -f "$tmpc".out
return $res
}
check_link() {
printf "checking %s ... " "$1"
local res=0
check_link_silent "$2" "$3" || res=1
test x$res = x0 && printf "yes\n" || printf "no\n"
return $res
}
usage() {
echo "supported arguments"
echo "--prefix=/path default: $prefix"
echo "--exec_prefix=/path default: $prefix/bin"
echo "--bindir=/path default: $prefix/bin"
echo "--libdir=/path default: $prefix/lib"
echo "--includedir=/path default: $prefix/include"
echo "--sysconfdir=/path default: $prefix/etc"
echo "--prefix=/path default: $prefix"
echo "--exec_prefix=/path default: $prefix/bin"
echo "--bindir=/path default: $prefix/bin"
echo "--libdir=/path default: $prefix/lib"
echo "--includedir=/path default: $prefix/include"
echo "--sysconfdir=/path default: $prefix/etc"
echo "--ignore-cve default: no"
echo " if set to yes ignores CVE-2015-3887 and makes it possible"
echo " to preload from current dir (possibly insecure, but handy)"
echo "--fat-binary : build for both i386 and x86_64 architectures on 64-bit Macs"
echo "--fat-binary-m1 : build for both arm64e and x86_64 architectures on M1 Macs"
echo "--hookmethod=dlsym|dyld hook method for osx. default: auto"
echo " if OSX >= 12 is detected, dyld method will be used if auto."
echo "--help : show this text"
exit 1
}
@ -21,6 +100,11 @@ spliteq() {
# or echo "$arg" | sed 's/[^=]*=//'
}
fat_binary=
fat_binary_m1=
ignore_cve=no
hookmethod=auto
parsearg() {
case "$1" in
--prefix=*) prefix=`spliteq $1`;;
@ -29,14 +113,15 @@ parsearg() {
--libdir=*) libdir=`spliteq $1`;;
--includedir=*) includedir=`spliteq $1`;;
--sysconfdir=*) sysconfdir=`spliteq $1`;;
--ignore-cve) ignore_cve=1;;
--ignore-cve=*) ignore_cve=`spliteq $1`;;
--hookmethod=*) hookmethod=`spliteq $1`;;
--fat-binary) fat_binary=1;;
--fat-binary-m1) fat_binary_m1=1;;
--help) usage;;
esac
}
ismac() {
uname -s | grep Darwin
}
while true ; do
case $1 in
-*) parsearg "$1"; shift;;
@ -68,21 +153,152 @@ if [ -z "$CC" ] ; then
CC=cc
fi
echo CC?=$CC>config.mak
[ -z "$CPPFLAGS" ] || echo CPPFLAGS?=$CPPFLAGS>>config.mak
[ -z "$CFLAGS" ] || echo USER_CFLAGS?=$CFLAGS>>config.mak
echo > config.mak
bsd_detected=false
isbsd() {
$bsd_detected
}
mac_detected=false
ismac() {
$mac_detected
}
mac_64=false
ismac64() {
$mac_64
}
solaris_detected=false
issolaris() {
$solaris_detected
}
haiku_detected=false
ishaiku() {
$haiku_detected
}
check_compile 'whether C compiler works' '' 'int main() {return 0;}' || fail 'error: install a C compiler and library'
check_compile 'whether libc headers are complete' '' '#include <netdb.h>\nint main() {return 0;}' || fail 'error: necessary libc headers are not installed'
check_compile 'whether C compiler understands -Wno-unknown-pragmas' '-Wno-unknown-pragmas' 'int main() {return 0;}'
if ! check_compile 'whether getnameinfo() servlen argument is POSIX compliant (socklen_t)' "-DGN_NODELEN_T=socklen_t -DGN_SERVLEN_T=socklen_t -DGN_FLAGS_T=int" \
'#define _GNU_SOURCE\n#include <netdb.h>\nint getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *, socklen_t, int);int main() {\nreturn 0;}' ; then
# GLIBC < 2.14
if ! check_compile 'whether getnameinfo() flags argument is unsigned' "-DGN_NODELEN_T=socklen_t -DGN_SERVLEN_T=socklen_t -DGN_FLAGS_T=unsigned" \
'#define _GNU_SOURCE\n#include <netdb.h>\nint getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *, socklen_t, unsigned);int main() {\nreturn 0;}' ; then
if ! check_compile 'whether getnameinfo() servlen argument is size_t' "-DGN_NODELEN_T=socklen_t -DGN_SERVLEN_T=size_t -DGN_FLAGS_T=int" \
'#define _GNU_SOURCE\n#include <netdb.h>\nint getnameinfo(const struct sockaddr *, socklen_t, char *, socklen_t, char *, size_t, int);int main() {\nreturn 0;}' ; then
# OpenBSD & FreeBSD
if ! check_compile 'whether getnameinfo() servlen and nodelen argument is size_t' "-DGN_NODELEN_T=size_t -DGN_SERVLEN_T=size_t -DGN_FLAGS_T=int" \
'#define _GNU_SOURCE\n#include <netdb.h>\nint getnameinfo(const struct sockaddr *, socklen_t, char *, size_t, char *, size_t, int);int main() {\nreturn 0;}' ; then
fail "failed to detect getnameinfo signature"
fi
fi
fi
fi
check_compile 'whether we have GNU-style getservbyname_r()' "-DHAVE_GNU_GETSERVBYNAME_R" \
'#define _GNU_SOURCE\n#include <netdb.h>\nint main() {\nstruct servent *se = 0;struct servent se_buf;char buf[1024];\ngetservbyname_r("foo", (void*) 0, &se_buf, buf, sizeof(buf), &se);\nreturn 0;}'
check_compile 'whether we have pipe2() and O_CLOEXEC' "-DHAVE_PIPE2" \
'#define _GNU_SOURCE\n#include <fcntl.h>\n#include <unistd.h>\nint main() {\nint pipefd[2];\npipe2(pipefd, O_CLOEXEC);\nreturn 0;}'
check_compile 'whether we have SOCK_CLOEXEC' "-DHAVE_SOCK_CLOEXEC" \
'#define _GNU_SOURCE\n#include <sys/socket.h>\nint main() {\nreturn socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);}'
check_compile 'whether we have clock_gettime' "-DHAVE_CLOCK_GETTIME" \
'#define _GNU_SOURCE\n#include <time.h>\nint main() {\nstruct timespec now;clock_gettime(CLOCK_REALTIME, &now);\nreturn now.tv_sec ^ now.tv_nsec;}'
check_define __APPLE__ && {
mac_detected=true
check_define __x86_64__ && mac_64=true
if test "$hookmethod" = auto ; then
osver=$(get_define_stripped __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 2>/dev/null)
test "$osver" -gt $((120000 - 1)) && hookmethod=dyld
fi
}
check_define __FreeBSD__ && bsd_detected=true
check_define __OpenBSD__ && {
bsd_detected=true
echo "CFLAGS+=-DIS_OPENBSD">>config.mak
check_compile_run 'whether OpenBSDs fclose() (illegally) calls close()' \
'#include <stdio.h>\n#include<stdlib.h>\nint close(int x){exit(0);}int main(){fclose(stdin);return 1;}' && \
OUR_CPPFLAGS="$OUR_CPPFLAGS -DBROKEN_FCLOSE"
}
check_define __sun && check_define __SVR4 && solaris_detected=true
check_define __HAIKU__ && haiku_detected=true
echo "CC=$CC">>config.mak
[ -z "$CPPFLAGS" ] || echo "CPPFLAGS=$CPPFLAGS">>config.mak
[ -z "$CFLAGS" ] || echo "USER_CFLAGS=$CFLAGS">>config.mak
[ -z "$LDFLAGS" ] || echo "USER_LDFLAGS=$LDFLAGS">>config.mak
echo prefix=$prefix>>config.mak
echo exec_prefix=$exec_prefix>>config.mak
echo bindir=$bindir>>config.mak
echo libdir=$libdir>>config.mak
echo includedir=$includedir>>config.mak
echo sysconfdir=$sysconfdir>>config.mak
[ "$ignore_cve" = "no" ] && echo "CPPFLAGS+= -DSUPER_SECURE">>config.mak
[ -z "$OUR_CPPFLAGS" ] || echo "CPPFLAGS+= $OUR_CPPFLAGS" >>config.mak
check_link "whether we can use -Wl,--no-as-needed" "-Wl,--no-as-needed" \
"int main() { return 0; }" || echo NO_AS_NEEDED= >> config.mak
LD_SONAME_FLAG=
printf "checking what's the option to use in linker to set library name ... "
for o in --soname -h -soname -install_name; do
check_link_silent "-shared -Wl,$o,libconftest.so" "void test_func(int a) {}" && LD_SONAME_FLAG=$o && break
done
if [ -z "$LD_SONAME_FLAG" ]; then
printf '\ncannot find an option to set library name\n'
exit 1
fi
echo "$LD_SONAME_FLAG"
echo "LD_SET_SONAME = -Wl,$LD_SONAME_FLAG," >> config.mak
if check_link "checking whether we can use -ldl" "-ldl" \
"int main(){return 0;}" ; then
echo "LIBDL = -ldl" >> config.mak
fi
if check_link "checking whether we can use -lpthread" "-lpthread" \
"int main(){return 0;}" ; then
echo "PTHREAD = -lpthread" >> config.mak
else
check_link "checking whether we can use -pthread" "-pthread" \
"int main(){return 0;}" || fail "no pthread support detected"
echo "PTHREAD = -pthread" >> config.mak
fi
make_cmd=make
if ismac ; then
echo LDSO_SUFFIX=dylib>>config.mak
echo MAC_CFLAGS+=-DIS_MAC=1>>config.mak
echo LD_SET_SONAME=-Wl,-install_name,>>config.mak
echo INSTALL_FLAGS=-m>>config.mak
if test "$hookmethod" = dyld ; then
echo "using Monterey style DYLD hooking"
echo "CFLAGS+=-DMONTEREY_HOOKING">>config.mak
fi
if ismac64 && [ "$fat_binary" = 1 ] ; then
echo "Configuring a fat binary for i386 and x86_64"
echo "MAC_CFLAGS+=-arch i386 -arch x86_64">>config.mak
echo "FAT_LDFLAGS=-arch i386 -arch x86_64">>config.mak
echo "FAT_BIN_LDFLAGS=-arch i386 -arch x86_64">>config.mak
fi
if [ "$fat_binary_m1" = 1 ] ; then
echo "Configuring a fat binary for arm64[e] and x86_64"
echo "MAC_CFLAGS+=-arch arm64 -arch arm64e -arch x86_64">>config.mak
echo "FAT_LDFLAGS=-arch arm64 -arch arm64e -arch x86_64">>config.mak
echo "FAT_BIN_LDFLAGS=-arch arm64 -arch x86_64">>config.mak
fi
elif isbsd ; then
echo LIBDL=>>config.mak
echo "CFLAGS+=-DIS_BSD">>config.mak
make_cmd=gmake
elif issolaris; then
echo "CFLAGS+=-DIS_SOLARIS -D__EXTENSIONS__" >> config.mak
echo "SOCKET_LIBS=-lsocket -lnsl" >> config.mak
elif ishaiku ; then
echo LIBDL=>>config.mak
echo "CFLAGS+=-DIS_HAIKU" >> config.mak
fi
echo done, now run make \&\& make install
echo "Done, now run $make_cmd && $make_cmd install"

11
dist/config.mak vendored
View File

@ -1,11 +0,0 @@
### config.mak template for proxychains
#######################################
# just copy into proxychains root dir and adapt to your needs.
prefix = /usr/local/
libdir = $(prefix)/lib
exec_prefix = /usr/local
bindir = $(exec_prefix)/bin

View File

@ -1,3 +1,8 @@
#undef _GNU_SOURCE
#define _GNU_SOURCE
#undef _POSIX_C_SOURCE
#define _DARWIN_C_SOURCE
#include <limits.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
@ -8,13 +13,14 @@
#include <string.h>
#include <stdint.h>
#include <stddef.h>
#include <errno.h>
#include <sys/mman.h>
#include "allocator_thread.h"
#include "shm.h"
#include "debug.h"
#include "ip_type.h"
#include "mutex.h"
#include "hash.h"
#include "stringdump.h"
#include "remotedns.h"
/* stuff for our internal translation table */
@ -29,20 +35,25 @@ typedef struct {
string_hash_tuple** list;
} internal_ip_lookup_table;
pthread_mutex_t internal_ips_lock;
internal_ip_lookup_table *internal_ips = NULL;
internal_ip_lookup_table internal_ips_buf;
static void *dumpstring(char* s, size_t len) {
char* p = malloc(len);
if(p) memcpy(p, s, len);
return p;
}
uint32_t index_from_internal_ip(ip_type internalip) {
static pthread_mutex_t *internal_ips_lock;
static internal_ip_lookup_table *internal_ips;
uint32_t index_from_internal_ip(ip_type4 internalip) {
PFUNC();
ip_type tmp = internalip;
ip_type4 tmp = internalip;
uint32_t ret;
ret = tmp.octet[3] + (tmp.octet[2] << 8) + (tmp.octet[1] << 16);
ret -= 1;
return ret;
}
char *string_from_internal_ip(ip_type internalip) {
char *string_from_internal_ip(ip_type4 internalip) {
PFUNC();
char *res = NULL;
uint32_t index = index_from_internal_ip(internalip);
@ -52,11 +63,11 @@ char *string_from_internal_ip(ip_type internalip) {
}
extern unsigned int remote_dns_subnet;
ip_type make_internal_ip(uint32_t index) {
ip_type ret;
ip_type4 make_internal_ip(uint32_t index) {
ip_type4 ret;
index++; // so we can start at .0.0.1
if(index > 0xFFFFFF)
return ip_type_invalid;
return IPT4_INVALID;
ret.octet[0] = remote_dns_subnet & 0xFF;
ret.octet[1] = (index & 0xFF0000) >> 16;
ret.octet[2] = (index & 0xFF00) >> 8;
@ -64,10 +75,10 @@ ip_type make_internal_ip(uint32_t index) {
return ret;
}
static ip_type ip_from_internal_list(char* name, size_t len) {
static ip_type4 ip_from_internal_list(char* name, size_t len) {
uint32_t hash = dalias_hash((char *) name);
size_t i;
ip_type res;
ip_type4 res;
void* new_mem;
// see if we already have this dns entry saved.
if(internal_ips->counter) {
@ -94,7 +105,7 @@ static ip_type ip_from_internal_list(char* name, size_t len) {
}
res = make_internal_ip(internal_ips->counter);
if(res.as_int == ip_type_invalid.as_int)
if(res.as_int == IPT4_INVALID.as_int)
goto err_plus_unlock;
string_hash_tuple tmp = { 0 };
@ -106,9 +117,9 @@ static ip_type ip_from_internal_list(char* name, size_t len) {
internal_ips->list[internal_ips->counter] = new_mem;
internal_ips->list[internal_ips->counter]->hash = hash;
new_mem = dumpstring((char*) name, len + 1);
new_mem = dumpstring((char*) name, len);
if(!new_mem) {
internal_ips->list[internal_ips->counter] = 0;
goto oom;
@ -121,34 +132,22 @@ static ip_type ip_from_internal_list(char* name, size_t len) {
return res;
err_plus_unlock:
PDEBUG("return err\n");
return ip_type_invalid;
return IPT4_INVALID;
}
/* stuff for communication with the allocator thread */
enum at_msgtype {
ATM_GETIP,
ATM_GETNAME,
ATM_EXIT,
};
enum at_direction {
ATD_SERVER = 0,
ATD_CLIENT,
ATD_MAX,
};
struct at_msghdr {
enum at_msgtype msgtype;
size_t datalen;
};
static pthread_t allocator_thread;
static pthread_attr_t allocator_thread_attr;
static int req_pipefd[2];
static int resp_pipefd[2];
int req_pipefd[2];
int resp_pipefd[2];
static int wait_data(int readfd) {
PFUNC();
@ -158,32 +157,75 @@ static int wait_data(int readfd) {
int ret;
while((ret = select(readfd+1, &fds, NULL, NULL, NULL)) <= 0) {
if(ret < 0) {
perror("select2");
int e = errno;
if(e == EINTR) continue;
#ifdef __GLIBC__
char emsg[1024];
char* x = strerror_r(errno, emsg, sizeof emsg);
dprintf(2, "select2: %s\n", x);
#endif
return 0;
}
}
return 1;
}
static int sendmessage(enum at_direction dir, struct at_msghdr *hdr, void* data) {
static int* destfd[ATD_MAX] = { [ATD_SERVER] = &req_pipefd[1], [ATD_CLIENT] = &resp_pipefd[1] };
int ret = write(*destfd[dir], hdr, sizeof *hdr) == sizeof *hdr;
if(ret && hdr->datalen) {
assert(hdr->datalen <= MSG_LEN_MAX);
ret = write(*destfd[dir], data, hdr->datalen) == hdr->datalen;
static int trywrite(int fd, void* buf, size_t bytes) {
ssize_t ret;
unsigned char *out = buf;
again:
ret = write(fd, out, bytes);
switch(ret) {
case -1:
if(errno == EINTR) goto again;
case 0:
return 0;
default:
if(ret == bytes || !bytes) return 1;
out += ret;
bytes -= ret;
goto again;
}
}
static int sendmessage(enum at_direction dir, struct at_msg *msg) {
static int* destfd[ATD_MAX] = { [ATD_SERVER] = &req_pipefd[1], [ATD_CLIENT] = &resp_pipefd[1] };
assert(msg->h.datalen <= MSG_LEN_MAX);
int ret = trywrite(*destfd[dir], msg, sizeof (msg->h)+msg->h.datalen);
assert(msg->h.datalen <= MSG_LEN_MAX);
return ret;
}
static int getmessage(enum at_direction dir, struct at_msghdr *hdr, void* data) {
static int tryread(int fd, void* buf, size_t bytes) {
ssize_t ret;
unsigned char *out = buf;
again:
ret = read(fd, out, bytes);
switch(ret) {
case -1:
if(errno == EINTR) goto again;
case 0:
return 0;
default:
if(ret == bytes || !bytes) return 1;
out += ret;
bytes -= ret;
goto again;
}
}
static int readmsg(int fd, struct at_msg *msg) {
int ret = tryread(fd, msg, sizeof(msg->h));
if(ret != 1) return ret;
return tryread(fd, &msg->m, msg->h.datalen);
}
static int getmessage(enum at_direction dir, struct at_msg *msg) {
static int* readfd[ATD_MAX] = { [ATD_SERVER] = &req_pipefd[0], [ATD_CLIENT] = &resp_pipefd[0] };
int ret;
ssize_t ret;
if((ret = wait_data(*readfd[dir]))) {
ret = read(*readfd[dir], hdr, sizeof *hdr) == sizeof(*hdr);
assert(hdr->datalen <= MSG_LEN_MAX);
if(ret && hdr->datalen) {
ret = read(*readfd[dir], data, hdr->datalen) == hdr->datalen;
}
if(!readmsg(*readfd[dir], msg))
return 0;
assert(msg->h.datalen <= MSG_LEN_MAX);
}
return ret;
}
@ -191,26 +233,24 @@ static int getmessage(enum at_direction dir, struct at_msghdr *hdr, void* data)
static void* threadfunc(void* x) {
(void) x;
int ret;
struct at_msghdr msg;
union {
char host[MSG_LEN_MAX];
ip_type ip;
} readbuf;
while((ret = getmessage(ATD_SERVER, &msg, &readbuf))) {
switch(msg.msgtype) {
struct at_msg msg;
while((ret = getmessage(ATD_SERVER, &msg))) {
switch(msg.h.msgtype) {
case ATM_GETIP:
/* client wants an ip for a DNS name. iterate our list and check if we have an existing entry.
* if not, create a new one. */
readbuf.ip = ip_from_internal_list(readbuf.host, msg.datalen - 1);
msg.datalen = sizeof(ip_type);
msg.m.ip = ip_from_internal_list(msg.m.host, msg.h.datalen);
msg.h.datalen = sizeof(ip_type4);
break;
case ATM_GETNAME: {
char *host = string_from_internal_ip(readbuf.ip);
char *host = string_from_internal_ip(msg.m.ip);
if(host) {
size_t l = strlen(host);
assert(l < MSG_LEN_MAX);
memcpy(readbuf.host, host, l + 1);
msg.datalen = l + 1;
assert(l+1 < MSG_LEN_MAX);
memcpy(msg.m.host, host, l + 1);
msg.h.datalen = l + 1;
} else {
msg.h.datalen = 0;
}
break;
}
@ -219,60 +259,92 @@ static void* threadfunc(void* x) {
default:
abort();
}
ret = sendmessage(ATD_CLIENT, &msg, &readbuf);
ret = sendmessage(ATD_CLIENT, &msg);
}
return 0;
}
/* API to access the internal ip mapping */
ip_type at_get_ip_for_host(char* host, size_t len) {
ip_type readbuf;
MUTEX_LOCK(&internal_ips_lock);
ip_type4 at_get_ip_for_host(char* host, size_t len) {
ip_type4 readbuf;
MUTEX_LOCK(internal_ips_lock);
if(len > MSG_LEN_MAX) goto inv;
struct at_msghdr msg = {.msgtype = ATM_GETIP, .datalen = len + 1 };
if(sendmessage(ATD_SERVER, &msg, host) &&
getmessage(ATD_CLIENT, &msg, &readbuf));
struct at_msg msg = {.h.msgtype = ATM_GETIP, .h.datalen = len + 1 };
memcpy(msg.m.host, host, len+1);
if(sendmessage(ATD_SERVER, &msg) &&
getmessage(ATD_CLIENT, &msg)) readbuf = msg.m.ip;
else {
inv:
readbuf = ip_type_invalid;
readbuf = IPT4_INVALID;
}
MUTEX_UNLOCK(&internal_ips_lock);
assert(msg.h.msgtype == ATM_GETIP);
MUTEX_UNLOCK(internal_ips_lock);
return readbuf;
}
size_t at_get_host_for_ip(ip_type ip, char* readbuf) {
struct at_msghdr msg = {.msgtype = ATM_GETNAME, .datalen = sizeof(ip_type) };
size_t at_get_host_for_ip(ip_type4 ip, char* readbuf) {
struct at_msg msg = {.h.msgtype = ATM_GETNAME, .h.datalen = sizeof(ip_type4), .m.ip = ip };
size_t res = 0;
MUTEX_LOCK(&internal_ips_lock);
if(sendmessage(ATD_SERVER, &msg, &ip) && getmessage(ATD_CLIENT, &msg, readbuf)) {
if((ptrdiff_t) msg.datalen <= 0) res = 0;
else res = msg.datalen - 1;
MUTEX_LOCK(internal_ips_lock);
if(sendmessage(ATD_SERVER, &msg) && getmessage(ATD_CLIENT, &msg)) {
if((int16_t) msg.h.datalen <= 0) res = 0;
else {
memcpy(readbuf, msg.m.host, msg.h.datalen);
res = msg.h.datalen - 1;
}
}
MUTEX_UNLOCK(&internal_ips_lock);
assert(msg.h.msgtype == ATM_GETNAME);
MUTEX_UNLOCK(internal_ips_lock);
return res;
}
static void initpipe(int* fds) {
if(pipe(fds) == -1) {
int retval;
#ifdef HAVE_PIPE2
retval = pipe2(fds, O_CLOEXEC);
#else
retval = pipe(fds);
if(retval == 0) {
fcntl(fds[0], F_SETFD, FD_CLOEXEC);
fcntl(fds[1], F_SETFD, FD_CLOEXEC);
}
#endif
if(retval == -1) {
perror("pipe");
exit(1);
}
}
#ifndef MAX
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#endif
#if !defined(PTHREAD_STACK_MIN) || defined(__APPLE__)
/* MAC says its min is 8KB, but then crashes in our face. thx hunkOLard */
#define PTHREAD_STACK_MIN 64*1024
#endif
/* initialize with pointers to shared memory. these will
* be used to place responses and arguments */
void at_init(void) {
PFUNC();
MUTEX_INIT(&internal_ips_lock);
internal_ips = &internal_ips_buf;
void *shm = mmap(0, 4096, PROT_WRITE|PROT_READ, MAP_ANON|MAP_SHARED, -1, 0);
assert(shm);
internal_ips_lock = shm;
internal_ips = (void*)((char*)shm + 2048);
MUTEX_INIT(internal_ips_lock);
memset(internal_ips, 0, sizeof *internal_ips);
initpipe(req_pipefd);
initpipe(resp_pipefd);
pthread_attr_t allocator_thread_attr;
pthread_attr_init(&allocator_thread_attr);
pthread_attr_setstacksize(&allocator_thread_attr, 16 * 1024);
pthread_attr_setstacksize(&allocator_thread_attr, MAX(16 * 1024, PTHREAD_STACK_MIN));
pthread_create(&allocator_thread, &allocator_thread_attr, threadfunc, 0);
pthread_attr_destroy(&allocator_thread_attr);
}
void at_close(void) {
@ -284,6 +356,5 @@ void at_close(void) {
close(req_pipefd[1]);
close(resp_pipefd[0]);
close(resp_pipefd[1]);
pthread_attr_destroy(&allocator_thread_attr);
MUTEX_DESTROY(&internal_ips_lock);
MUTEX_DESTROY(internal_ips_lock);
}

View File

@ -4,12 +4,14 @@
#include <unistd.h>
#include "ip_type.h"
#define MSG_LEN_MAX 256
extern int req_pipefd[2];
extern int resp_pipefd[2];
void at_init(void);
void at_close(void);
size_t at_get_host_for_ip(ip_type ip, char* readbuf);
ip_type at_get_ip_for_host(char* host, size_t len);
size_t at_get_host_for_ip(ip_type4 ip, char* readbuf);
ip_type4 at_get_ip_for_host(char* host, size_t len);
//RcB: DEP "allocator_thread.c"
#endif
#endif

View File

@ -3,6 +3,53 @@
#include <unistd.h>
#include <stdio.h>
const char *proxy_type_strmap[] = {
"http",
"socks4",
"socks5",
};
const char *chain_type_strmap[] = {
"dynamic_chain",
"strict_chain",
"random_chain",
"round_robin_chain",
};
const char *proxy_state_strmap[] = {
"play",
"down",
"blocked",
"busy",
};
/* isnumericipv4() taken from libulz */
int pc_isnumericipv4(const char* ipstring) {
size_t x = 0, n = 0, d = 0;
int wasdot = 0;
while(1) {
switch(ipstring[x]) {
case 0: goto done;
case '.':
if(!n || wasdot) return 0;
d++;
wasdot = 1;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
n++;
wasdot = 0;
break;
default:
return 0;
}
x++;
}
done:
if(d == 3 && n >= 4 && n <= 12) return 1;
return 0;
}
// stolen from libulz (C) rofl0r
void pc_stringfromipv4(unsigned char *ip_buf_4_bytes, char *outbuf_16_bytes) {
unsigned char *p;
@ -39,7 +86,7 @@ char *get_config_path(char* default_path, char* pbuf, size_t bufsize) {
char *path = default_path;
if(check_path(path))
goto have;
// priority 1: env var PROXYCHAINS_CONF_FILE
path = getenv(PROXYCHAINS_CONF_FILE_ENV_VAR);
if(check_path(path))
@ -58,6 +105,13 @@ char *get_config_path(char* default_path, char* pbuf, size_t bufsize) {
path = pbuf;
if(check_path(path))
goto have;
// priority 3b: ~/config/settings/proxychains.conf (for haiku)
path = getenv("HOME");
snprintf(pbuf, bufsize, "%s/config/settings/%s", path, PROXYCHAINS_CONF_FILE);
path = pbuf;
if(check_path(path))
goto have;
// priority 4: $SYSCONFDIR/proxychains.conf
path = SYSCONFDIR "/" PROXYCHAINS_CONF_FILE;
@ -68,10 +122,10 @@ char *get_config_path(char* default_path, char* pbuf, size_t bufsize) {
path = "/etc/" PROXYCHAINS_CONF_FILE;
if(check_path(path))
goto have;
perror("couldnt find configuration file");
exit(1);
return NULL;
have:
return path;

View File

@ -11,8 +11,13 @@
#include <stddef.h>
extern const char *proxy_type_strmap[];
extern const char *chain_type_strmap[];
extern const char *proxy_state_strmap[];
char *get_config_path(char* default_path, char* pbuf, size_t bufsize);
void pc_stringfromipv4(unsigned char *ip_buf_4_bytes, char *outbuf_16_bytes);
int pc_isnumericipv4(const char* ipstring);
//RcB: DEP "common.c"
#endif

View File

@ -27,7 +27,7 @@
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <poll.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <time.h>
@ -37,12 +37,13 @@
#include "core.h"
#include "common.h"
#include "shm.h"
#include "allocator_thread.h"
#include "rdns.h"
#include "mutex.h"
extern int tcp_read_time_out;
extern int tcp_connect_time_out;
extern int proxychains_quiet_mode;
extern unsigned int proxychains_proxy_offset;
extern unsigned int remote_dns_subnet;
static int poll_retry(struct pollfd *fds, nfds_t nfsd, int timeout) {
@ -106,7 +107,7 @@ static void encode_base_64(char *src, char *dest, int max_len) {
}
void proxychains_write_log(char *str, ...) {
char buff[1024*20];
char buff[1024*4];
va_list arglist;
if(!proxychains_quiet_mode) {
va_start(arglist, str);
@ -187,6 +188,7 @@ static int timed_connect(int sock, const struct sockaddr *addr, socklen_t len) {
#define INVALID_INDEX 0xFFFFFFFFU
#define BUFF_SIZE 1024 // used to read responses from proxies.
static int tunnel_to(int sock, ip_type ip, unsigned short port, proxy_type pt, char *user, char *pass) {
char *dns_name = NULL;
char hostnamebuf[MSG_LEN_MAX];
@ -198,8 +200,8 @@ static int tunnel_to(int sock, ip_type ip, unsigned short port, proxy_type pt, c
// the range 224-255.* is reserved, and it won't go outside (unless the app does some other stuff with
// the results returned from gethostbyname et al.)
// the hardcoded number 224 can now be changed using the config option remote_dns_subnet to i.e. 127
if(ip.octet[0] == remote_dns_subnet) {
dns_len = at_get_host_for_ip(ip, hostnamebuf);
if(!ip.is_v6 && proxychains_resolver >= DNSLF_RDNS_START && ip.addr.v4.octet[0] == remote_dns_subnet) {
dns_len = rdns_get_host_for_ip(ip.addr.v4, hostnamebuf);
if(!dns_len) goto err;
else dns_name = hostnamebuf;
}
@ -216,207 +218,205 @@ static int tunnel_to(int sock, ip_type ip, unsigned short port, proxy_type pt, c
int len;
unsigned char buff[BUFF_SIZE];
char ip_buf[16];
char ip_buf[INET6_ADDRSTRLEN];
int v6 = ip.is_v6;
//memset (buff, 0, sizeof(buff));
switch (pt) {
case RAW_TYPE: {
return SUCCESS;
}
break;
case HTTP_TYPE:{
if(!dns_len) {
pc_stringfromipv4(&ip.octet[0], ip_buf);
dns_name = ip_buf;
}
snprintf((char *) buff, sizeof(buff), "CONNECT %s:%d HTTP/1.0\r\n", dns_name,
ntohs(port));
if(user[0]) {
#define HTTP_AUTH_MAX ((0xFF * 2) + 1 + 1)
// 2 * 0xff: username and pass, plus 1 for ':' and 1 for zero terminator.
char src[HTTP_AUTH_MAX];
char dst[(4 * HTTP_AUTH_MAX)];
memcpy(src, user, ulen);
memcpy(src + ulen, ":", 1);
memcpy(src + ulen + 1, pass, passlen);
src[ulen + 1 + passlen] = 0;
encode_base_64(src, dst, sizeof(dst));
strcat((char *) buff, "Proxy-Authorization: Basic ");
strcat((char *) buff, dst);
strcat((char *) buff, "\r\n\r\n");
} else
strcat((char *) buff, "\r\n");
len = strlen((char *) buff);
if(len != send(sock, buff, len, 0))
if(!dns_len) {
if(!inet_ntop(v6?AF_INET6:AF_INET,ip.addr.v6,ip_buf,sizeof ip_buf)) {
proxychains_write_log(LOG_PREFIX "error: ip address conversion failed\n");
goto err;
len = 0;
// read header byte by byte.
while(len < BUFF_SIZE) {
if(1 == read_n_bytes(sock, (char *) (buff + len), 1))
len++;
else
goto err;
if(len > 4 &&
buff[len - 1] == '\n' &&
buff[len - 2] == '\r' && buff[len - 3] == '\n' && buff[len - 4] == '\r')
break;
}
// if not ok (200) or response greather than BUFF_SIZE return BLOCKED;
if(len == BUFF_SIZE || !(buff[9] == '2' && buff[10] == '0' && buff[11] == '0'))
return BLOCKED;
return SUCCESS;
dns_name = ip_buf;
}
break;
#define HTTP_AUTH_MAX ((0xFF * 2) + 1 + 1) /* 2 * 0xff: username and pass, plus 1 for ':' and 1 for zero terminator. */
char src[HTTP_AUTH_MAX];
char dst[(4 * HTTP_AUTH_MAX)];
if(ulen) {
snprintf(src, sizeof(src), "%s:%s", user, pass);
encode_base_64(src, dst, sizeof(dst));
} else dst[0] = 0;
uint16_t hs_port = ntohs(port);
len = snprintf((char *) buff, sizeof(buff),
"CONNECT %s:%d HTTP/1.0\r\nHost: %s:%d\r\n%s%s%s\r\n",
dns_name, hs_port,
dns_name, hs_port,
ulen ? "Proxy-Authorization: Basic " : dst,
dst, ulen ? "\r\n" : dst);
if(len < 0 || len != send(sock, buff, len, 0))
goto err;
len = 0;
// read header byte by byte.
while(len < BUFF_SIZE) {
if(1 == read_n_bytes(sock, (char *) (buff + len), 1))
len++;
else
goto err;
if(len > 4 &&
buff[len - 1] == '\n' &&
buff[len - 2] == '\r' && buff[len - 3] == '\n' && buff[len - 4] == '\r')
break;
}
// if not ok (200) or response greather than BUFF_SIZE return BLOCKED;
if(len == BUFF_SIZE || !(buff[9] == '2' && buff[10] == '0' && buff[11] == '0')) {
PDEBUG("HTTP proxy blocked: buff=\"%s\"\n", buff);
return BLOCKED;
}
return SUCCESS;
}
break;
case SOCKS4_TYPE:{
buff[0] = 4; // socks version
buff[1] = 1; // connect command
memcpy(&buff[2], &port, 2); // dest port
if(dns_len) {
ip.octet[0] = 0;
ip.octet[1] = 0;
ip.octet[2] = 0;
ip.octet[3] = 1;
}
memcpy(&buff[4], &ip, 4); // dest host
len = ulen + 1; // username
if(len > 1)
memcpy(&buff[8], user, len);
else {
buff[8] = 0;
}
// do socksv4a dns resolution on the server
if(dns_len) {
memcpy(&buff[8 + len], dns_name, dns_len + 1);
len += dns_len + 1;
}
if((len + 8) != write_n_bytes(sock, (char *) buff, (8 + len)))
goto err;
if(8 != read_n_bytes(sock, (char *) buff, 8))
goto err;
if(buff[0] != 0 || buff[1] != 90)
return BLOCKED;
return SUCCESS;
if(v6) {
proxychains_write_log(LOG_PREFIX "error: SOCKS4 doesn't support ipv6 addresses\n");
goto err;
}
break;
buff[0] = 4; // socks version
buff[1] = 1; // connect command
memcpy(&buff[2], &port, 2); // dest port
if(dns_len) {
ip.addr.v4.octet[0] = 0;
ip.addr.v4.octet[1] = 0;
ip.addr.v4.octet[2] = 0;
ip.addr.v4.octet[3] = 1;
}
memcpy(&buff[4], &ip.addr.v4, 4); // dest host
len = ulen + 1; // username
if(len > 1)
memcpy(&buff[8], user, len);
else {
buff[8] = 0;
}
// do socksv4a dns resolution on the server
if(dns_len) {
memcpy(&buff[8 + len], dns_name, dns_len + 1);
len += dns_len + 1;
}
if((len + 8) != write_n_bytes(sock, (char *) buff, (8 + len)))
goto err;
if(8 != read_n_bytes(sock, (char *) buff, 8))
goto err;
if(buff[0] != 0 || buff[1] != 90)
return BLOCKED;
return SUCCESS;
}
break;
case SOCKS5_TYPE:{
if(user) {
buff[0] = 5; //version
buff[1] = 2; //nomber of methods
buff[2] = 0; // no auth method
buff[3] = 2; /// auth method -> username / password
if(4 != write_n_bytes(sock, (char *) buff, 4))
goto err;
} else {
buff[0] = 5; //version
buff[1] = 1; //nomber of methods
buff[2] = 0; // no auth method
if(3 != write_n_bytes(sock, (char *) buff, 3))
goto err;
}
int n_methods = ulen ? 2 : 1;
buff[0] = 5; // version
buff[1] = n_methods ; // number of methods
buff[2] = 0; // no auth method
if(ulen) buff[3] = 2; /// auth method -> username / password
if(2+n_methods != write_n_bytes(sock, (char *) buff, 2+n_methods))
goto err;
if(2 != read_n_bytes(sock, (char *) buff, 2))
if(2 != read_n_bytes(sock, (char *) buff, 2))
goto err;
if(buff[0] != 5 || (buff[1] != 0 && buff[1] != 2)) {
if(buff[0] == 5 && buff[1] == 0xFF)
return BLOCKED;
else
goto err;
if(buff[0] != 5 || (buff[1] != 0 && buff[1] != 2)) {
if(buff[0] == 5 && buff[1] == 0xFF)
return BLOCKED;
else
goto err;
}
if(buff[1] == 2) {
// authentication
char in[2];
char out[515];
char *cur = out;
size_t c;
*cur++ = 1; // version
c = ulen & 0xFF;
*cur++ = c;
memcpy(cur, user, c);
cur += c;
c = passlen & 0xFF;
*cur++ = c;
memcpy(cur, pass, c);
cur += c;
if((cur - out) != write_n_bytes(sock, out, cur - out))
goto err;
if(2 != read_n_bytes(sock, in, 2))
goto err;
if(in[0] != 1 || in[1] != 0) {
if(in[0] != 1)
goto err;
else
return BLOCKED;
}
}
int buff_iter = 0;
buff[buff_iter++] = 5; // version
buff[buff_iter++] = 1; // connect
buff[buff_iter++] = 0; // reserved
if(!dns_len) {
buff[buff_iter++] = 1; // ip v4
memcpy(buff + buff_iter, &ip, 4); // dest host
buff_iter += 4;
} else {
buff[buff_iter++] = 3; //dns
buff[buff_iter++] = dns_len & 0xFF;
memcpy(buff + buff_iter, dns_name, dns_len);
buff_iter += dns_len;
}
memcpy(buff + buff_iter, &port, 2); // dest port
buff_iter += 2;
if(buff_iter != write_n_bytes(sock, (char *) buff, buff_iter))
goto err;
if(4 != read_n_bytes(sock, (char *) buff, 4))
goto err;
if(buff[0] != 5 || buff[1] != 0)
goto err;
switch (buff[3]) {
case 1:
len = 4;
break;
case 4:
len = 16;
break;
case 3:
len = 0;
if(1 != read_n_bytes(sock, (char *) &len, 1))
goto err;
break;
default:
goto err;
}
if(len + 2 != read_n_bytes(sock, (char *) buff, len + 2))
goto err;
return SUCCESS;
}
break;
if(buff[1] == 2) {
// authentication
char in[2];
char out[515];
char *cur = out;
size_t c;
*cur++ = 1; // version
c = ulen & 0xFF;
*cur++ = c;
memcpy(cur, user, c);
cur += c;
c = passlen & 0xFF;
*cur++ = c;
memcpy(cur, pass, c);
cur += c;
if((cur - out) != write_n_bytes(sock, out, cur - out))
goto err;
if(2 != read_n_bytes(sock, in, 2))
goto err;
/* according to RFC 1929 the version field for the user/pass auth sub-
negotiation should be 1, which is kinda counter-intuitive, so there
are some socks5 proxies that return 5 instead. other programs like
curl work fine when the version is 5, so let's do the same and accept
either of them. */
if(!(in[0] == 5 || in[0] == 1))
goto err;
if(in[1] != 0)
return BLOCKED;
}
int buff_iter = 0;
buff[buff_iter++] = 5; // version
buff[buff_iter++] = 1; // connect
buff[buff_iter++] = 0; // reserved
if(!dns_len) {
buff[buff_iter++] = v6 ? 4 : 1; // ip v4/v6
memcpy(buff + buff_iter, ip.addr.v6, v6?16:4); // dest host
buff_iter += v6?16:4;
} else {
buff[buff_iter++] = 3; //dns
buff[buff_iter++] = dns_len & 0xFF;
memcpy(buff + buff_iter, dns_name, dns_len);
buff_iter += dns_len;
}
memcpy(buff + buff_iter, &port, 2); // dest port
buff_iter += 2;
if(buff_iter != write_n_bytes(sock, (char *) buff, buff_iter))
goto err;
if(4 != read_n_bytes(sock, (char *) buff, 4))
goto err;
if(buff[0] != 5 || buff[1] != 0)
goto err;
switch (buff[3]) {
case 1:
len = 4;
break;
case 4:
len = 16;
break;
case 3:
len = 0;
if(1 != read_n_bytes(sock, (char *) &len, 1))
goto err;
break;
default:
goto err;
}
if(len + 2 != read_n_bytes(sock, (char *) buff, len + 2))
goto err;
return SUCCESS;
}
break;
}
err:
@ -427,24 +427,33 @@ static int tunnel_to(int sock, ip_type ip, unsigned short port, proxy_type pt, c
#define DT "Dynamic chain"
#define ST "Strict chain"
#define RT "Random chain"
#define RRT "Round Robin chain"
static int start_chain(int *fd, proxy_data * pd, char *begin_mark) {
struct sockaddr_in addr;
char ip_buf[16];
int v6 = pd->ip.is_v6;
*fd = socket(PF_INET, SOCK_STREAM, 0);
*fd = socket(v6?PF_INET6:PF_INET, SOCK_STREAM, 0);
if(*fd == -1)
goto error;
pc_stringfromipv4(&pd->ip.octet[0], ip_buf);
char ip_buf[INET6_ADDRSTRLEN];
if(!inet_ntop(v6?AF_INET6:AF_INET,pd->ip.addr.v6,ip_buf,sizeof ip_buf))
goto error;
proxychains_write_log(LOG_PREFIX "%s " TP " %s:%d ",
begin_mark, ip_buf, htons(pd->port));
pd->ps = PLAY_STATE;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = (in_addr_t) pd->ip.as_int;
addr.sin_port = pd->port;
if(timed_connect(*fd, (struct sockaddr *) &addr, sizeof(addr))) {
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = pd->port,
.sin_addr.s_addr = (in_addr_t) pd->ip.addr.v4.as_int
};
struct sockaddr_in6 addr6 = {
.sin6_family = AF_INET6,
.sin6_port = pd->port,
};
if(v6) memcpy(&addr6.sin6_addr.s6_addr, pd->ip.addr.v6, 16);
if(timed_connect(*fd, (struct sockaddr *) (v6?(void*)&addr6:(void*)&addr), v6?sizeof(addr6):sizeof(addr))) {
pd->ps = DOWN_STATE;
goto error1;
}
@ -453,8 +462,10 @@ static int start_chain(int *fd, proxy_data * pd, char *begin_mark) {
error1:
proxychains_write_log(TP " timeout\n");
error:
if(*fd != -1)
if(*fd != -1) {
close(*fd);
*fd = -1;
}
return SOCKET_ERROR;
}
@ -466,7 +477,7 @@ static proxy_data *select_proxy(select_type how, proxy_data * pd, unsigned int p
case RANDOMLY:
do {
k++;
i = 0 + (unsigned int) (proxy_count * 1.0 * rand() / (RAND_MAX + 1.0));
i = rand() % proxy_count;
} while(pd[i].ps != PLAY_STATE && k < proxy_count * 100);
break;
case FIFOLY:
@ -511,41 +522,50 @@ static unsigned int calc_alive(proxy_data * pd, unsigned int proxy_count) {
}
static int chain_step(int ns, proxy_data * pfrom, proxy_data * pto) {
static int chain_step(int *ns, proxy_data * pfrom, proxy_data * pto) {
int retcode = -1;
char *hostname;
char *hostname, *errmsg = 0;
char hostname_buf[MSG_LEN_MAX];
char ip_buf[16];
char ip_buf[INET6_ADDRSTRLEN];
int v6 = pto->ip.is_v6;
PFUNC();
if(pto->ip.octet[0] == remote_dns_subnet) {
if(!at_get_host_for_ip(pto->ip, hostname_buf)) goto usenumericip;
if(!v6 && proxychains_resolver >= DNSLF_RDNS_START && pto->ip.addr.v4.octet[0] == remote_dns_subnet) {
if(!rdns_get_host_for_ip(pto->ip.addr.v4, hostname_buf)) goto usenumericip;
else hostname = hostname_buf;
} else {
usenumericip:
pc_stringfromipv4(&pto->ip.octet[0], ip_buf);
if(!inet_ntop(v6?AF_INET6:AF_INET,pto->ip.addr.v6,ip_buf,sizeof ip_buf)) {
pto->ps = DOWN_STATE;
errmsg = "<--ip conversion error!\n";
retcode = SOCKET_ERROR;
goto err;
}
hostname = ip_buf;
}
proxychains_write_log(TP " %s:%d ", hostname, htons(pto->port));
retcode = tunnel_to(ns, pto->ip, pto->port, pfrom->pt, pfrom->user, pfrom->pass);
retcode = tunnel_to(*ns, pto->ip, pto->port, pfrom->pt, pfrom->user, pfrom->pass);
switch (retcode) {
case SUCCESS:
pto->ps = BUSY_STATE;
break;
case BLOCKED:
pto->ps = BLOCKED_STATE;
proxychains_write_log("<--denied\n");
close(ns);
break;
errmsg = "<--denied\n";
goto err;
case SOCKET_ERROR:
pto->ps = DOWN_STATE;
proxychains_write_log("<--socket error or timeout!\n");
close(ns);
break;
errmsg = "<--socket error or timeout!\n";
goto err;
}
return retcode;
err:
if(errmsg) proxychains_write_log(errmsg);
if(*ns != -1) close(*ns);
*ns = -1;
return retcode;
}
int connect_proxy_chain(int sock, ip_type target_ip,
@ -554,15 +574,20 @@ int connect_proxy_chain(int sock, ip_type target_ip,
proxy_data p4;
proxy_data *p1, *p2, *p3;
int ns = -1;
int rc = -1;
unsigned int offset = 0;
unsigned int alive_count = 0;
unsigned int curr_len = 0;
unsigned int looped = 0; // went back to start of list in RR mode
unsigned int rr_loop_max = 14;
p3 = &p4;
PFUNC();
again:
rc = -1;
DUMP_PROXY_CHAIN(pd, proxy_count);
switch (ct) {
case DYNAMIC_TYPE:
@ -576,7 +601,7 @@ int connect_proxy_chain(int sock, ip_type target_ip,
p2 = select_proxy(FIFOLY, pd, proxy_count, &offset);
if(!p2)
break;
if(SUCCESS != chain_step(ns, p1, p2)) {
if(SUCCESS != chain_step(&ns, p1, p2)) {
PDEBUG("GOTO AGAIN 1\n");
goto again;
}
@ -585,7 +610,57 @@ int connect_proxy_chain(int sock, ip_type target_ip,
//proxychains_write_log(TP);
p3->ip = target_ip;
p3->port = target_port;
if(SUCCESS != chain_step(ns, p1, p3))
if(SUCCESS != chain_step(&ns, p1, p3))
goto error;
break;
case ROUND_ROBIN_TYPE:
alive_count = calc_alive(pd, proxy_count);
offset = proxychains_proxy_offset;
if(alive_count < max_chain)
goto error_more;
PDEBUG("1:rr_offset = %d\n", offset);
/* Check from current RR offset til end */
for (;rc != SUCCESS;) {
if (!(p1 = select_proxy(FIFOLY, pd, proxy_count, &offset))) {
/* We've reached the end of the list, go to the start */
offset = 0;
looped++;
if (looped > rr_loop_max) {
proxychains_proxy_offset = 0;
goto error_more;
} else {
PDEBUG("rr_type all proxies down, release all\n");
release_all(pd, proxy_count);
/* Each loop we wait 10ms more */
usleep(10000 * looped);
continue;
}
}
PDEBUG("2:rr_offset = %d\n", offset);
rc=start_chain(&ns, p1, RRT);
}
/* Create rest of chain using RR */
for(curr_len = 1; curr_len < max_chain;) {
PDEBUG("3:rr_offset = %d, curr_len = %d, max_chain = %d\n", offset, curr_len, max_chain);
p2 = select_proxy(FIFOLY, pd, proxy_count, &offset);
if(!p2) {
/* Try from the beginning to where we started */
offset = 0;
continue;
} else if(SUCCESS != chain_step(&ns, p1, p2)) {
PDEBUG("GOTO AGAIN 1\n");
goto again;
} else
p1 = p2;
curr_len++;
}
//proxychains_write_log(TP);
p3->ip = target_ip;
p3->port = target_port;
proxychains_proxy_offset = offset+1;
PDEBUG("pd_offset = %d, curr_len = %d\n", proxychains_proxy_offset, curr_len);
if(SUCCESS != chain_step(&ns, p1, p3))
goto error;
break;
@ -603,7 +678,7 @@ int connect_proxy_chain(int sock, ip_type target_ip,
while(offset < proxy_count) {
if(!(p2 = select_proxy(FIFOLY, pd, proxy_count, &offset)))
break;
if(SUCCESS != chain_step(ns, p1, p2)) {
if(SUCCESS != chain_step(&ns, p1, p2)) {
PDEBUG("chain_step failed\n");
goto error_strict;
}
@ -612,7 +687,7 @@ int connect_proxy_chain(int sock, ip_type target_ip,
//proxychains_write_log(TP);
p3->ip = target_ip;
p3->port = target_port;
if(SUCCESS != chain_step(ns, p1, p3))
if(SUCCESS != chain_step(&ns, p1, p3))
goto error;
break;
@ -628,7 +703,7 @@ int connect_proxy_chain(int sock, ip_type target_ip,
while(++curr_len < max_chain) {
if(!(p2 = select_proxy(RANDOMLY, pd, proxy_count, &offset)))
goto error_more;
if(SUCCESS != chain_step(ns, p1, p2)) {
if(SUCCESS != chain_step(&ns, p1, p2)) {
PDEBUG("GOTO AGAIN 2\n");
goto again;
}
@ -637,7 +712,7 @@ int connect_proxy_chain(int sock, ip_type target_ip,
//proxychains_write_log(TP);
p3->ip = target_ip;
p3->port = target_port;
if(SUCCESS != chain_step(ns, p1, p3))
if(SUCCESS != chain_step(&ns, p1, p3))
goto error;
}
@ -664,14 +739,13 @@ int connect_proxy_chain(int sock, ip_type target_ip,
return -1;
}
#include "hostentdb.h"
struct hostent_list hl;
static pthread_mutex_t servbyname_lock;
void core_initialize(void) {
hdb_init(&hl);
MUTEX_INIT(&servbyname_lock);
}
void core_unload(void) {
MUTEX_DESTROY(&servbyname_lock);
}
static void gethostbyname_data_setstring(struct gethostbyname_data* data, char* name) {
@ -679,6 +753,103 @@ static void gethostbyname_data_setstring(struct gethostbyname_data* data, char*
data->hostent_space.h_name = data->addr_name;
}
extern ip_type4 hostsreader_get_numeric_ip_for_name(const char* name);
struct hostent* proxy_gethostbyname_old(const char *name)
{
static struct hostent hostent_space;
static in_addr_t resolved_addr;
static char* resolved_addr_p;
static char addr_name[256];
int pipe_fd[2];
char buff[256];
in_addr_t addr;
pid_t pid;
int status, ret;
size_t l;
struct hostent* hp;
hostent_space.h_addr_list = &resolved_addr_p;
*hostent_space.h_addr_list = (char*)&resolved_addr;
resolved_addr = 0;
if(pc_isnumericipv4(name)) {
strcpy(buff, name);
goto got_buff;
}
gethostname(buff,sizeof(buff));
if(!strcmp(buff,name))
goto got_buff;
memset(buff, 0, sizeof(buff));
// TODO: this works only once, so cache it ...
// later
while ((hp=gethostent()))
if (!strcmp(hp->h_name,name))
return hp;
#ifdef HAVE_PIPE2
ret = pipe2(pipe_fd, O_CLOEXEC);
#else
ret = pipe(pipe_fd);
if(ret == 0) {
fcntl(pipe_fd[0], F_SETFD, FD_CLOEXEC);
fcntl(pipe_fd[1], F_SETFD, FD_CLOEXEC);
}
#endif
if(ret)
goto err;
pid = fork();
switch(pid) {
case 0: // child
proxychains_write_log("|DNS-request| %s \n", name);
close(pipe_fd[0]);
dup2(pipe_fd[1],1);
close(pipe_fd[1]);
// putenv("LD_PRELOAD=");
execlp("proxyresolv","proxyresolv",name,NULL);
perror("can't exec proxyresolv");
exit(2);
case -1: //error
close(pipe_fd[0]);
close(pipe_fd[1]);
perror("can't fork");
goto err;
default:
close(pipe_fd[1]);
waitpid(pid, &status, 0);
buff[0] = 0;
read(pipe_fd[0],&buff,sizeof(buff));
close(pipe_fd[0]);
got_buff:
l = strlen(buff);
if (!l) goto err_dns;
if (buff[l-1] == '\n') buff[l-1] = 0;
addr = inet_addr(buff);
if (addr == (in_addr_t) (-1))
goto err_dns;
memcpy(*(hostent_space.h_addr_list),
&addr ,sizeof(struct in_addr));
hostent_space.h_name = addr_name;
snprintf(addr_name, sizeof addr_name, "%s", buff);
hostent_space.h_length = sizeof (in_addr_t);
hostent_space.h_addrtype = AF_INET;
}
proxychains_write_log("|DNS-response| %s is %s\n",
name, inet_ntoa(*(struct in_addr*)&addr));
return &hostent_space;
err_dns:
proxychains_write_log("|DNS-response|: %s lookup error\n", name);
err:
return NULL;
}
struct hostent *proxy_gethostbyname(const char *name, struct gethostbyname_data* data) {
PFUNC();
char buff[256];
@ -694,26 +865,29 @@ struct hostent *proxy_gethostbyname(const char *name, struct gethostbyname_data*
data->hostent_space.h_addrtype = AF_INET;
data->hostent_space.h_length = sizeof(in_addr_t);
if(pc_isnumericipv4(name)) {
data->resolved_addr = inet_addr(name);
goto retname;
}
gethostname(buff, sizeof(buff));
if(!strcmp(buff, name)) {
data->resolved_addr = inet_addr(buff);
if(data->resolved_addr == (in_addr_t) (-1))
data->resolved_addr = (in_addr_t) (ip_type_localhost.as_int);
data->resolved_addr = (in_addr_t) (IPT4_LOCALHOST.as_int);
goto retname;
}
memset(buff, 0, sizeof(buff));
// this iterates over the "known hosts" db, usually /etc/hosts
ip_type hdb_res = hdb_get(&hl, (char*) name);
if(hdb_res.as_int != ip_type_invalid.as_int) {
ip_type4 hdb_res = hostsreader_get_numeric_ip_for_name(name);
if(hdb_res.as_int != IPT4_INVALID.as_int) {
data->resolved_addr = hdb_res.as_int;
goto retname;
}
data->resolved_addr = at_get_ip_for_host((char*) name, strlen(name)).as_int;
if(data->resolved_addr == (in_addr_t) ip_type_invalid.as_int) return NULL;
data->resolved_addr = rdns_get_ip_for_host((char*) name, strlen(name)).as_int;
if(data->resolved_addr == (in_addr_t) IPT4_INVALID.as_int) return NULL;
retname:
@ -726,7 +900,7 @@ struct hostent *proxy_gethostbyname(const char *name, struct gethostbyname_data*
struct addrinfo_data {
struct addrinfo addrinfo_space;
struct sockaddr sockaddr_space;
struct sockaddr_storage sockaddr_space;
char addr_name[256];
};
@ -735,14 +909,17 @@ void proxy_freeaddrinfo(struct addrinfo *res) {
free(res);
}
#ifdef IS_MAC
/* getservbyname on mac is using thread local storage, so we dont need mutex */
static int getservbyname_r(const char* name, const char* proto, struct servent* result_buf,
static int mygetservbyname_r(const char* name, const char* proto, struct servent* result_buf,
char* buf, size_t buflen, struct servent** result) {
PFUNC();
#ifdef HAVE_GNU_GETSERVBYNAME_R
PDEBUG("using host getservbyname_r\n");
return getservbyname_r(name, proto, result_buf, buf, buflen, result);
#endif
struct servent *res;
int ret;
(void) buf; (void) buflen;
MUTEX_LOCK(&servbyname_lock);
res = getservbyname(name, proto);
if(res) {
*result_buf = *res;
@ -752,9 +929,36 @@ static int getservbyname_r(const char* name, const char* proto, struct servent*
*result = NULL;
ret = ENOENT;
}
MUTEX_UNLOCK(&servbyname_lock);
return ret;
}
static int looks_like_numeric_ipv6(const char *node)
{
if(!strchr(node, ':')) return 0;
const char* p= node;
while(1) switch(*(p++)) {
case 0: return 1;
case ':': case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
break;
default: return 0;
}
}
static int my_inet_aton(const char *node, struct addrinfo_data* space)
{
int ret;
((struct sockaddr_in *) &space->sockaddr_space)->sin_family = AF_INET;
ret = inet_aton(node, &((struct sockaddr_in *) &space->sockaddr_space)->sin_addr);
if(ret || !looks_like_numeric_ipv6(node)) return ret;
ret = inet_pton(AF_INET6, node, &((struct sockaddr_in6 *) &space->sockaddr_space)->sin6_addr);
if(ret) ((struct sockaddr_in6 *) &space->sockaddr_space)->sin6_family = AF_INET6;
return ret;
}
#endif
int proxy_getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res) {
struct gethostbyname_data ghdata;
@ -764,50 +968,69 @@ int proxy_getaddrinfo(const char *node, const char *service, const struct addrin
struct servent se_buf;
struct addrinfo *p;
char buf[1024];
int port;
PFUNC();
int port, af = AF_INET;
PDEBUG("proxy_getaddrinfo node:%s service: %s, flags: %d\n",
node?node:"",service?service:"",hints?(int)hints->ai_flags:0);
// printf("proxy_getaddrinfo node %s service %s\n",node,service);
space = calloc(1, sizeof(struct addrinfo_data));
if(!space) goto err1;
if(node && !inet_aton(node, &((struct sockaddr_in *) &space->sockaddr_space)->sin_addr)) {
hp = proxy_gethostbyname(node, &ghdata);
if(!space) return EAI_MEMORY;
if(node && !my_inet_aton(node, space)) {
/* some folks (nmap) use getaddrinfo() with AI_NUMERICHOST to check whether a string
containing a numeric ip was passed. we must return failure in that case. */
if(hints && (hints->ai_flags & AI_NUMERICHOST)) {
err_nn:
free(space);
return EAI_NONAME;
}
if(proxychains_resolver == DNSLF_FORKEXEC)
hp = proxy_gethostbyname_old(node);
else
hp = proxy_gethostbyname(node, &ghdata);
if(hp)
memcpy(&((struct sockaddr_in *) &space->sockaddr_space)->sin_addr,
*(hp->h_addr_list), sizeof(in_addr_t));
else
goto err2;
goto err_nn;
} else if(node) {
af = ((struct sockaddr_in *) &space->sockaddr_space)->sin_family;
} else if(!node && !(hints->ai_flags & AI_PASSIVE)) {
af = ((struct sockaddr_in *) &space->sockaddr_space)->sin_family = AF_INET;
memcpy(&((struct sockaddr_in *) &space->sockaddr_space)->sin_addr,
(char[]){127,0,0,1}, 4);
}
if(service) getservbyname_r(service, NULL, &se_buf, buf, sizeof(buf), &se);
if(service) mygetservbyname_r(service, NULL, &se_buf, buf, sizeof(buf), &se);
port = se ? se->s_port : htons(atoi(service ? service : "0"));
((struct sockaddr_in *) &space->sockaddr_space)->sin_port = port;
if(af == AF_INET)
((struct sockaddr_in *) &space->sockaddr_space)->sin_port = port;
else
((struct sockaddr_in6 *) &space->sockaddr_space)->sin6_port = port;
*res = p = &space->addrinfo_space;
assert((size_t)p == (size_t) space);
p->ai_addr = &space->sockaddr_space;
p->ai_addr = (void*) &space->sockaddr_space;
if(node)
strncpy(space->addr_name, node, sizeof(space->addr_name));
snprintf(space->addr_name, sizeof(space->addr_name), "%s", node);
p->ai_canonname = space->addr_name;
p->ai_next = NULL;
p->ai_family = space->sockaddr_space.sa_family = AF_INET;
p->ai_addrlen = sizeof(space->sockaddr_space);
p->ai_family = space->sockaddr_space.ss_family = af;
p->ai_addrlen = af == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
if(hints) {
p->ai_socktype = hints->ai_socktype;
p->ai_flags = hints->ai_flags;
p->ai_protocol = hints->ai_protocol;
if(!p->ai_socktype && p->ai_protocol == IPPROTO_TCP)
p->ai_socktype = SOCK_STREAM;
} else {
#ifndef AI_V4MAPPED
#define AI_V4MAPPED 0
#endif
p->ai_flags = (AI_V4MAPPED | AI_ADDRCONFIG);
}
goto out;
err2:
free(space);
err1:
return 1;
out:
return 0;
}

View File

@ -23,8 +23,8 @@
#ifndef __CORE_HEADER
#define __CORE_HEADER
#define BUFF_SIZE 8*1024 // used to read responses from proxies.
#define MAX_LOCALNET 64
#define MAX_DNAT 64
#include "ip_type.h"
@ -41,14 +41,16 @@ typedef enum {
typedef enum {
HTTP_TYPE,
SOCKS4_TYPE,
SOCKS5_TYPE
SOCKS5_TYPE,
RAW_TYPE
} proxy_type;
typedef enum {
DYNAMIC_TYPE,
STRICT_TYPE,
RANDOM_TYPE}
chain_type;
RANDOM_TYPE,
ROUND_ROBIN_TYPE
} chain_type;
typedef enum {
PLAY_STATE,
@ -63,10 +65,25 @@ typedef enum {
} select_type;
typedef struct {
struct in_addr in_addr, netmask;
sa_family_t family;
unsigned short port;
union {
struct {
struct in_addr in_addr;
struct in_addr in_mask;
};
struct {
struct in6_addr in6_addr;
unsigned char in6_prefix;
};
};
} localaddr_arg;
typedef struct {
struct in_addr orig_dst, new_dst;
unsigned short orig_port, new_port;
} dnat_arg;
typedef struct {
ip_type ip;
unsigned short port;
@ -82,16 +99,22 @@ int connect_proxy_chain (int sock, ip_type target_ip, unsigned short target_port
void proxychains_write_log(char *str, ...);
typedef int (*close_t)(int);
typedef int (*close_range_t)(unsigned, unsigned, int);
typedef int (*connect_t)(int, const struct sockaddr *, socklen_t);
typedef struct hostent* (*gethostbyname_t)(const char *);
typedef int (*freeaddrinfo_t)(struct addrinfo *);
typedef void (*freeaddrinfo_t)(struct addrinfo *);
typedef struct hostent *(*gethostbyaddr_t) (const void *, socklen_t, int);
typedef int (*getaddrinfo_t)(const char *, const char *, const struct addrinfo *,
struct addrinfo **);
typedef int (*getnameinfo_t) (const struct sockaddr *, socklen_t, char *,
socklen_t, char *, socklen_t, int);
GN_NODELEN_T, char *, GN_SERVLEN_T, GN_FLAGS_T);
typedef ssize_t (*sendto_t) (int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
extern connect_t true_connect;
@ -105,10 +128,11 @@ struct gethostbyname_data {
struct hostent hostent_space;
in_addr_t resolved_addr;
char *resolved_addr_p[2];
char addr_name[1024 * 8];
char addr_name[256];
};
struct hostent* proxy_gethostbyname(const char *name, struct gethostbyname_data *data);
struct hostent* proxy_gethostbyname_old(const char *name);
int proxy_getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res);
@ -123,4 +147,5 @@ void core_unload(void);
//RcB: DEP "core.c"
//RcB: DEP "libproxychains.c"
//RcB: LINK "-Wl,--no-as-needed -ldl -lpthread"
//RcB: LINK "-Wl,--no-as-needed -ldl -lpthread"

231
src/daemon/daemon.c Normal file
View File

@ -0,0 +1,231 @@
/*
proxychains-ng DNS daemon
Copyright (C) 2020 rofl0r.
*/
#define _GNU_SOURCE
#include <unistd.h>
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <errno.h>
#include <limits.h>
#include "udpserver.h"
#include "sblist.h"
#include "hsearch.h"
#include "../remotedns.h"
#include "../ip_type.h"
#ifndef MAX
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#endif
static struct htab *ip_lookup_table;
static sblist *hostnames;
static unsigned remote_subnet;
static const struct server* server;
#ifndef CONFIG_LOG
#define CONFIG_LOG 1
#endif
#if CONFIG_LOG
/* we log to stderr because it's not using line buffering, i.e. malloc which would need
locking when called from different threads. for the same reason we use dprintf,
which writes directly to an fd. */
#define dolog(...) dprintf(2, __VA_ARGS__)
#else
static void dolog(const char* fmt, ...) { }
#endif
static char* my_inet_ntoa(unsigned char *ip_buf_4_bytes, char *outbuf_16_bytes) {
unsigned char *p;
char *o = outbuf_16_bytes;
unsigned char n;
for(p = ip_buf_4_bytes; p < ip_buf_4_bytes + 4; p++) {
n = *p;
if(*p >= 100) {
if(*p >= 200)
*(o++) = '2';
else
*(o++) = '1';
n %= 100;
}
if(*p >= 10) {
*(o++) = (n / 10) + '0';
n %= 10;
}
*(o++) = n + '0';
*(o++) = '.';
}
o[-1] = 0;
return outbuf_16_bytes;
}
/* buf needs to be long enough for an ipv6 addr, i.e. INET6_ADDRSTRLEN + 1 */
static char* ipstr(union sockaddr_union *su, char* buf) {
int af = SOCKADDR_UNION_AF(su);
void *ipdata = SOCKADDR_UNION_ADDRESS(su);
inet_ntop(af, ipdata, buf, INET6_ADDRSTRLEN+1);
char portbuf[7];
snprintf(portbuf, sizeof portbuf, ":%u", (unsigned) ntohs(SOCKADDR_UNION_PORT(su)));
strcat(buf, portbuf);
return buf;
}
static int usage(char *a0) {
dprintf(2,
"Proxychains-NG remote dns daemon\n"
"--------------------------------\n"
"usage: %s -i listenip -p port -r remotesubnet\n"
"all arguments are optional.\n"
"by default listenip is 127.0.0.1, port 1053 and remotesubnet 224.\n\n", a0
);
return 1;
}
unsigned index_from_ip(ip_type4 internalip) {
ip_type4 tmp = internalip;
uint32_t ret;
ret = tmp.octet[3] + (tmp.octet[2] << 8) + (tmp.octet[1] << 16);
ret -= 1;
return ret;
}
char *host_from_ip(ip_type4 internalip) {
char *res = NULL;
unsigned index = index_from_ip(internalip);
if(index < sblist_getsize(hostnames)) {
char **tmp = sblist_get(hostnames, index);
if(tmp && *tmp) res = *tmp;
}
return res;
}
ip_type4 get_ip_from_index(unsigned index) {
ip_type4 ret;
index++; // so we can start at .0.0.1
if(index > 0xFFFFFF)
return IPT4_INVALID;
ret.octet[0] = remote_subnet & 0xFF;
ret.octet[1] = (index & 0xFF0000) >> 16;
ret.octet[2] = (index & 0xFF00) >> 8;
ret.octet[3] = index & 0xFF;
return ret;
}
ip_type4 get_ip(char* hn) {
htab_value *v = htab_find(ip_lookup_table, hn);
if(v) return get_ip_from_index(v->n);
char *n = strdup(hn);
if(!n) return IPT4_INVALID;
if(!sblist_add(hostnames, &n)) {
o_out:;
free(n);
return IPT4_INVALID;
}
if(!htab_insert(ip_lookup_table, n, HTV_N(sblist_getsize(hostnames)-1))) {
sblist_delete(hostnames, sblist_getsize(hostnames)-1);
goto o_out;
}
return get_ip_from_index(sblist_getsize(hostnames)-1);
}
int main(int argc, char** argv) {
int ch;
const char *listenip = "127.0.0.1";
unsigned port = 1053;
remote_subnet = 224;
while((ch = getopt(argc, argv, ":r:i:p:")) != -1) {
switch(ch) {
case 'r':
remote_subnet = atoi(optarg);
break;
case 'i':
listenip = optarg;
break;
case 'p':
port = atoi(optarg);
break;
case ':':
dprintf(2, "error: option -%c requires an operand\n", optopt);
/* fall through */
case '?':
return usage(argv[0]);
}
}
signal(SIGPIPE, SIG_IGN);
struct server s;
if(server_setup(&s, listenip, port)) {
perror("server_setup");
return 1;
}
server = &s;
ip_lookup_table = htab_create(64);
hostnames = sblist_new(sizeof(char*), 64);
while(1) {
struct client c;
char ipstr_buf[INET6_ADDRSTRLEN+6+1];
char ip4str_buf[16];
struct at_msg msg, out;
size_t msgl = sizeof(msg);
int failed = 0;
#define FAIL() do { failed=1; goto sendresp; } while(0)
if(server_waitclient(&s, &c, &msg, &msgl)) continue;
msg.h.datalen = ntohs(msg.h.datalen);
if(msgl != sizeof(msg.h)+msg.h.datalen) {
dolog("%s: invalid datalen\n", ipstr(&c.addr, ipstr_buf));
FAIL();
}
out.h.msgtype = msg.h.msgtype;
if(msg.h.msgtype == ATM_GETIP) {
if(!memchr(msg.m.host, 0, msg.h.datalen)) {
dolog("%s: nul terminator missing\n", ipstr(&c.addr, ipstr_buf));
FAIL();
}
out.h.datalen = sizeof(ip_type4);
out.m.ip = get_ip(msg.m.host);
failed = !memcmp(&out.m.ip, &IPT4_INVALID, 4);
dolog("%s requested ip for %s (%s)\n", ipstr(&c.addr, ipstr_buf),
msg.m.host, failed?"FAIL":my_inet_ntoa((void*)&out.m.ip, ip4str_buf));
if(failed) FAIL();
} else if (msg.h.msgtype == ATM_GETNAME) {
if(msg.h.datalen != 4) {
dolog("%s: invalid len for getname request\n", ipstr(&c.addr, ipstr_buf));
FAIL();
}
char *hn = host_from_ip(msg.m.ip);
if(hn) {
size_t l = strlen(hn);
memcpy(out.m.host, hn, l+1);
out.h.datalen = l+1;
}
dolog("%s requested name for %s (%s)\n", ipstr(&c.addr, ipstr_buf),
my_inet_ntoa((void*) &msg.m.ip, ip4str_buf), hn?hn:"FAIL");
if(!hn) FAIL();
} else {
dolog("%s: unknown request %u\n", ipstr(&c.addr, ipstr_buf),
(unsigned) msg.h.msgtype);
}
sendresp:;
if(failed) {
out.h.msgtype = ATM_FAIL;
out.h.datalen = 0;
}
unsigned short dlen = out.h.datalen;
out.h.datalen = htons(dlen);
sendto(server->fd, &out, sizeof(out.h)+dlen, 0, (void*) &c.addr, SOCKADDR_UNION_LENGTH(&c.addr));
}
}

188
src/daemon/hsearch.c Normal file
View File

@ -0,0 +1,188 @@
/*
musl license, hsearch.c originally written by Szabolcs Nagy
Copyright © 2005-2020 Rich Felker, et al.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include "hsearch.h"
/*
open addressing hash table with 2^n table size
quadratic probing is used in case of hash collision
tab indices and hash are size_t
after resize fails with ENOMEM the state of tab is still usable
*/
typedef struct htab_entry {
char *key;
htab_value data;
} htab_entry;
struct elem {
htab_entry item;
size_t hash;
};
struct htab {
struct elem *elems;
size_t mask;
size_t used;
};
#define MINSIZE 8
#define MAXSIZE ((size_t)-1/2 + 1)
static size_t keyhash(char *k)
{
unsigned char *p = (void *)k;
size_t h = 0;
while (*p)
h = 31*h + *p++;
return h;
}
static int resize(struct htab *htab, size_t nel)
{
size_t newsize;
size_t i, j;
struct elem *e, *newe;
struct elem *oldtab = htab->elems;
struct elem *oldend = htab->elems + htab->mask + 1;
if (nel > MAXSIZE)
nel = MAXSIZE;
for (newsize = MINSIZE; newsize < nel; newsize *= 2);
htab->elems = calloc(newsize, sizeof *htab->elems);
if (!htab->elems) {
htab->elems = oldtab;
return 0;
}
htab->mask = newsize - 1;
if (!oldtab)
return 1;
for (e = oldtab; e < oldend; e++)
if (e->item.key) {
for (i=e->hash,j=1; ; i+=j++) {
newe = htab->elems + (i & htab->mask);
if (!newe->item.key)
break;
}
*newe = *e;
}
free(oldtab);
return 1;
}
static struct elem *lookup(struct htab *htab, char *key, size_t hash)
{
size_t i, j;
struct elem *e;
for (i=hash,j=1; ; i+=j++) {
e = htab->elems + (i & htab->mask);
if (!e->item.key ||
(e->hash==hash && strcmp(e->item.key, key)==0))
break;
}
return e;
}
struct htab *htab_create(size_t nel)
{
struct htab *r = calloc(1, sizeof *r);
if(r && !resize(r, nel)) {
free(r);
r = 0;
}
return r;
}
void htab_destroy(struct htab *htab)
{
free(htab->elems);
free(htab);
}
static htab_entry *htab_find_item(struct htab *htab, char* key)
{
size_t hash = keyhash(key);
struct elem *e = lookup(htab, key, hash);
if (e->item.key) {
return &e->item;
}
return 0;
}
htab_value* htab_find(struct htab *htab, char* key)
{
htab_entry *i = htab_find_item(htab, key);
if(i) return &i->data;
return 0;
}
int htab_delete(struct htab *htab, char* key)
{
htab_entry *i = htab_find_item(htab, key);
if(!i) return 0;
i->key = 0;
return 1;
}
int htab_insert(struct htab *htab, char* key, htab_value value)
{
size_t hash = keyhash(key);
struct elem *e = lookup(htab, key, hash);
if(e->item.key) {
/* it's not allowed to overwrite existing data */
return 0;
}
e->item.key = key;
e->item.data = value;
e->hash = hash;
if (++htab->used > htab->mask - htab->mask/4) {
if (!resize(htab, 2*htab->used)) {
htab->used--;
e->item.key = 0;
return 0;
}
}
return 1;
}
size_t htab_next(struct htab *htab, size_t iterator, char** key, htab_value **v)
{
size_t i;
for(i=iterator;i<htab->mask+1;++i) {
struct elem *e = htab->elems + i;
if(e->item.key) {
*key = e->item.key;
*v = &e->item.data;
return i+1;
}
}
return 0;
}

21
src/daemon/hsearch.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef HSEARCH_H
#define HSEARCH_H
#include <stdlib.h>
typedef union htab_value {
void *p;
size_t n;
} htab_value;
#define HTV_N(N) (htab_value) {.n = N}
#define HTV_P(P) (htab_value) {.p = P}
struct htab * htab_create(size_t);
void htab_destroy(struct htab *);
htab_value* htab_find(struct htab *, char* key);
int htab_insert(struct htab *, char*, htab_value);
int htab_delete(struct htab *htab, char* key);
size_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v);
#endif

73
src/daemon/sblist.c Normal file
View File

@ -0,0 +1,73 @@
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#include "sblist.h"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#define MY_PAGE_SIZE 4096
sblist* sblist_new(size_t itemsize, size_t blockitems) {
sblist* ret = (sblist*) malloc(sizeof(sblist));
sblist_init(ret, itemsize, blockitems);
return ret;
}
static void sblist_clear(sblist* l) {
l->items = NULL;
l->capa = 0;
l->count = 0;
}
void sblist_init(sblist* l, size_t itemsize, size_t blockitems) {
if(l) {
l->blockitems = blockitems ? blockitems : MY_PAGE_SIZE / itemsize;
l->itemsize = itemsize;
sblist_clear(l);
}
}
void sblist_free_items(sblist* l) {
if(l) {
if(l->items) free(l->items);
sblist_clear(l);
}
}
void sblist_free(sblist* l) {
if(l) {
sblist_free_items(l);
free(l);
}
}
char* sblist_item_from_index(sblist* l, size_t idx) {
return l->items + (idx * l->itemsize);
}
void* sblist_get(sblist* l, size_t item) {
if(item < l->count) return (void*) sblist_item_from_index(l, item);
return NULL;
}
int sblist_set(sblist* l, void* item, size_t pos) {
if(pos >= l->count) return 0;
memcpy(sblist_item_from_index(l, pos), item, l->itemsize);
return 1;
}
int sblist_grow_if_needed(sblist* l) {
char* temp;
if(l->count == l->capa) {
temp = realloc(l->items, (l->capa + l->blockitems) * l->itemsize);
if(!temp) return 0;
l->capa += l->blockitems;
l->items = temp;
}
return 1;
}
int sblist_add(sblist* l, void* item) {
if(!sblist_grow_if_needed(l)) return 0;
l->count++;
return sblist_set(l, item, l->count - 1);
}

92
src/daemon/sblist.h Normal file
View File

@ -0,0 +1,92 @@
#ifndef SBLIST_H
#define SBLIST_H
/* this file is part of libulz, as of commit 8ab361a27743aaf025323ee43b8b8876dc054fdd
modified for direct inclusion in microsocks. */
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h>
/*
* simple buffer list.
*
* this thing here is basically a generic dynamic array
* will realloc after every blockitems inserts
* can store items of any size.
*
* so think of it as a by-value list, as opposed to a typical by-ref list.
* you typically use it by having some struct on the stack, and pass a pointer
* to sblist_add, which will copy the contents into its internal memory.
*
*/
typedef struct {
size_t itemsize;
size_t blockitems;
size_t count;
size_t capa;
char* items;
} sblist;
#define sblist_getsize(X) ((X)->count)
#define sblist_get_count(X) ((X)->count)
#define sblist_empty(X) ((X)->count == 0)
// for dynamic style
sblist* sblist_new(size_t itemsize, size_t blockitems);
void sblist_free(sblist* l);
//for static style
void sblist_init(sblist* l, size_t itemsize, size_t blockitems);
void sblist_free_items(sblist* l);
// accessors
void* sblist_get(sblist* l, size_t item);
// returns 1 on success, 0 on OOM
int sblist_add(sblist* l, void* item);
int sblist_set(sblist* l, void* item, size_t pos);
void sblist_delete(sblist* l, size_t item);
char* sblist_item_from_index(sblist* l, size_t idx);
int sblist_grow_if_needed(sblist* l);
int sblist_insert(sblist* l, void* item, size_t pos);
/* same as sblist_add, but returns list index of new item, or -1 */
size_t sblist_addi(sblist* l, void* item);
void sblist_sort(sblist *l, int (*compar)(const void *, const void *));
/* insert element into presorted list, returns listindex of new entry or -1*/
size_t sblist_insert_sorted(sblist* l, void* o, int (*compar)(const void *, const void *));
#ifndef __COUNTER__
#define __COUNTER__ __LINE__
#endif
#define __sblist_concat_impl( x, y ) x##y
#define __sblist_macro_concat( x, y ) __sblist_concat_impl( x, y )
#define __sblist_iterator_name __sblist_macro_concat(sblist_iterator, __COUNTER__)
// use with custom iterator variable
#define sblist_iter_counter(LIST, ITER, PTR) \
for(size_t ITER = 0; (PTR = sblist_get(LIST, ITER)), ITER < sblist_getsize(LIST); ITER++)
// use with custom iterator variable, which is predeclared
#define sblist_iter_counter2(LIST, ITER, PTR) \
for(ITER = 0; (PTR = sblist_get(LIST, ITER)), ITER < sblist_getsize(LIST); ITER++)
// use with custom iterator variable, which is predeclared and signed
// useful for a loop which can delete items from the list, and then decrease the iterator var.
#define sblist_iter_counter2s(LIST, ITER, PTR) \
for(ITER = 0; (PTR = sblist_get(LIST, ITER)), ITER < (ssize_t) sblist_getsize(LIST); ITER++)
// uses "magic" iterator variable
#define sblist_iter(LIST, PTR) sblist_iter_counter(LIST, __sblist_iterator_name, PTR)
#ifdef __cplusplus
}
#endif
#pragma RcB2 DEP "sblist.c" "sblist_delete.c"
#endif

View File

@ -0,0 +1,9 @@
#include "sblist.h"
#include <string.h>
void sblist_delete(sblist* l, size_t item) {
if (l->count && item < l->count) {
memmove(sblist_item_from_index(l, item), sblist_item_from_index(l, item + 1), (sblist_getsize(l) - (item + 1)) * l->itemsize);
l->count--;
}
}

41
src/daemon/udpclient.c Normal file
View File

@ -0,0 +1,41 @@
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "../remotedns.h"
#include "../ip_type.h"
int main() {
int fd;
int port = 1053;
char srvn[] = "127.0.0.1";
struct sockaddr_in srva = {.sin_family = AF_INET, .sin_port = htons(port)};
inet_pton(AF_INET, srvn, &srva.sin_addr);
fd = socket(AF_INET, SOCK_DGRAM, 0);
char namebuf[260];
while(fgets(namebuf, sizeof namebuf, stdin)) {
size_t l = strlen(namebuf);
if(namebuf[l-1] == '\n') {
l--;
namebuf[l] = 0;
}
struct at_msg msg = {0};
unsigned msglen;
if(isdigit(namebuf[0])) {
msglen = 4;
msg.h.msgtype = ATM_GETNAME;
inet_aton(namebuf, (void*) &msg.m.ip);
} else {
msglen = l+1;
msg.h.msgtype = ATM_GETIP;
memcpy(msg.m.host, namebuf, msglen);
}
msg.h.datalen = htons(msglen);
sendto(fd, &msg, sizeof(msg.h)+msglen, 0, (void*)&srva, sizeof(srva));
char rcvbuf[512];
recvfrom(fd, rcvbuf, sizeof rcvbuf, 0, (void*)0, (void*)0);
}
}

65
src/daemon/udpserver.c Normal file
View File

@ -0,0 +1,65 @@
#include "udpserver.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int resolve(const char *host, unsigned short port, struct addrinfo** addr) {
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
.ai_flags = AI_PASSIVE,
};
char port_buf[8];
snprintf(port_buf, sizeof port_buf, "%u", port);
return getaddrinfo(host, port_buf, &hints, addr);
}
int resolve_sa(const char *host, unsigned short port, union sockaddr_union *res) {
struct addrinfo *ainfo = 0;
int ret;
SOCKADDR_UNION_AF(res) = AF_UNSPEC;
if((ret = resolve(host, port, &ainfo))) return ret;
memcpy(res, ainfo->ai_addr, ainfo->ai_addrlen);
freeaddrinfo(ainfo);
return 0;
}
int bindtoip(int fd, union sockaddr_union *bindaddr) {
socklen_t sz = SOCKADDR_UNION_LENGTH(bindaddr);
if(sz)
return bind(fd, (struct sockaddr*) bindaddr, sz);
return 0;
}
int server_waitclient(struct server *server, struct client* client, void* buf, size_t *buflen) {
socklen_t clen = sizeof client->addr;
ssize_t ret = recvfrom(server->fd, buf, *buflen, 0, (void*)&client->addr, &clen);
if(ret >= 0) {
*buflen = ret;
return 0;
}
return ret;
}
int server_setup(struct server *server, const char* listenip, unsigned short port) {
struct addrinfo *ainfo = 0;
if(resolve(listenip, port, &ainfo)) return -1;
struct addrinfo* p;
int listenfd = -1;
for(p = ainfo; p; p = p->ai_next) {
if((listenfd = socket(p->ai_family, SOCK_DGRAM, 0)) < 0)
continue;
int yes = 1;
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if(bind(listenfd, p->ai_addr, p->ai_addrlen) < 0) {
close(listenfd);
listenfd = -1;
continue;
}
break;
}
freeaddrinfo(ainfo);
if(listenfd < 0) return -2;
server->fd = listenfd;
return 0;
}

48
src/daemon/udpserver.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef SERVER_H
#define SERVER_H
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#pragma RcB2 DEP "udpserver.c"
union sockaddr_union {
struct sockaddr_in v4;
struct sockaddr_in6 v6;
};
#define SOCKADDR_UNION_AF(PTR) (PTR)->v4.sin_family
#define SOCKADDR_UNION_LENGTH(PTR) ( \
( SOCKADDR_UNION_AF(PTR) == AF_INET ) ? sizeof((PTR)->v4) : ( \
( SOCKADDR_UNION_AF(PTR) == AF_INET6 ) ? sizeof((PTR)->v6) : 0 ) )
#define SOCKADDR_UNION_ADDRESS(PTR) ( \
( SOCKADDR_UNION_AF(PTR) == AF_INET ) ? (void*) &(PTR)->v4.sin_addr : ( \
( SOCKADDR_UNION_AF(PTR) == AF_INET6 ) ? (void*) &(PTR)->v6.sin6_addr : (void*) 0 ) )
#define SOCKADDR_UNION_PORT(PTR) ( \
( SOCKADDR_UNION_AF(PTR) == AF_INET ) ? (PTR)->v4.sin_port : ( \
( SOCKADDR_UNION_AF(PTR) == AF_INET6 ) ? (PTR)->v6.sin6_port : 0 ) )
struct client {
union sockaddr_union addr;
};
struct server {
int fd;
};
int resolve(const char *host, unsigned short port, struct addrinfo** addr);
int resolve_sa(const char *host, unsigned short port, union sockaddr_union *res);
int bindtoip(int fd, union sockaddr_union *bindaddr);
int server_waitclient(struct server *server, struct client* client, void* buf, size_t *buflen);
int server_setup(struct server *server, const char* listenip, unsigned short port);
#endif

31
src/debug.c Normal file
View File

@ -0,0 +1,31 @@
#ifdef DEBUG
# include "core.h"
# include "common.h"
# include "debug.h"
#include <arpa/inet.h>
void dump_proxy_chain(proxy_data *pchain, unsigned int count) {
char ip_buf[INET6_ADDRSTRLEN];
for (; count; pchain++, count--) {
if(!inet_ntop(pchain->ip.is_v6?AF_INET6:AF_INET,pchain->ip.addr.v6,ip_buf,sizeof ip_buf)) {
proxychains_write_log(LOG_PREFIX "error: ip address conversion failed\n");
continue;
}
PDEBUG("[%s] %s %s:%d", proxy_state_strmap[pchain->ps],
proxy_type_strmap[pchain->pt],
ip_buf, htons(pchain->port));
if (*pchain->user || *pchain->pass) {
PSTDERR(" [u=%s,p=%s]", pchain->user, pchain->pass);
}
PSTDERR("\n");
}
}
#else
// Do not allow this translation unit to end up empty
// for non-DEBUG builds, to satisfy ISO C standards.
typedef int __appease_iso_compilers__;
#endif

View File

@ -1,13 +1,24 @@
#ifndef DEBUG_H
#define DEBUG_H
#ifdef DEBUG
# include <stdio.h>
# define PDEBUG(fmt, args...) do { dprintf(2,"DEBUG:"fmt, ## args); } while(0)
#ifdef DEBUG
# define PSTDERR(fmt, args...) do { dprintf(2,fmt, ## args); } while(0)
# define PDEBUG(fmt, args...) PSTDERR("DEBUG:pid[%d]:" fmt, getpid(), ## args)
# define DEBUGDECL(args...) args
# define DUMP_PROXY_CHAIN(A, B) dump_proxy_chain(A, B)
#else
# define PDEBUG(fmt, args...) do {} while (0)
# define DEBUGDECL(args...)
# define DUMP_PROXY_CHAIN(args...) do {} while (0)
#endif
# define PFUNC() do { PDEBUG("pid[%d]:%s\n", getpid(), __FUNCTION__); } while(0)
# define PFUNC() do { PDEBUG("%s()\n", __FUNCTION__); } while(0)
#include "core.h"
void dump_proxy_chain(proxy_data *pchain, unsigned int count);
#endif
#endif

View File

@ -1,56 +0,0 @@
#include <stdint.h>
#include <string.h>
#include <netdb.h>
#include <stdlib.h>
#include "ip_type.h"
#include "hash.h"
#include "stringdump.h"
#include "hostentdb.h"
#include "common.h"
#include "debug.h"
#define STEP 16
static void hdb_add(struct hostent_list* hl, char* host, ip_type ip) {
if(hl->count +1 > hl->capa) {
void * nu = realloc(hl->entries, (hl->capa + STEP) * sizeof(struct hostent_entry));
if(!nu) return;
hl->entries = nu;
hl->capa += STEP;
}
struct hostent_entry *h = &hl->entries[hl->count];
h->hash = dalias_hash(host);
h->ip.as_int = ip.as_int;
h->str = dumpstring(host, strlen(host) + 1);
if(h->str) hl->count++;
}
static void hdb_fill(struct hostent_list *hl) {
struct hostent* hp;
while((hp = gethostent()))
if(hp->h_addrtype == AF_INET && hp->h_length == sizeof(in_addr_t)) {
hdb_add(hl, hp->h_name, (ip_type) { .as_int = *((in_addr_t*)(hp->h_addr_list[0])) });
}
}
void hdb_init(struct hostent_list *hl) {
memset(hl, 0, sizeof *hl);
hdb_fill(hl);
}
ip_type hdb_get(struct hostent_list *hl, char* host) {
size_t i;
PFUNC();
uint32_t hash = dalias_hash(host);
for(i = 0; i < hl->count; i++) {
if(hl->entries[i].hash == hash && !strcmp(hl->entries[i].str, host)) {
#ifdef DEBUG
char ipbuf[16];
pc_stringfromipv4(hl->entries[i].ip.octet, ipbuf);
PDEBUG("got ip %s for hostent entry %s\n", ipbuf, host);
#endif
return hl->entries[i].ip;
}
}
return ip_type_invalid;
}

View File

@ -1,23 +0,0 @@
#ifndef HOSTENTDB_H
#define HOSTENTDB_H
#include "ip_type.h"
#include <unistd.h>
struct hostent_entry {
uint32_t hash;
ip_type ip;
char* str;
};
struct hostent_list {
size_t count;
size_t capa;
struct hostent_entry *entries;
};
void hdb_init(struct hostent_list *hl);
ip_type hdb_get(struct hostent_list *hl, char* host);
//RcB: DEP "hostendb.c"
#endif

96
src/hostsreader.c Normal file
View File

@ -0,0 +1,96 @@
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "common.h"
/*
simple reader for /etc/hosts
it only supports comments, blank lines and lines consisting of an ipv4 hostname pair.
this is required so we can return entries from the host db without messing up the
non-thread-safe state of libc's gethostent().
*/
struct hostsreader {
FILE *f;
char* ip, *name;
};
int hostsreader_open(struct hostsreader *ctx) {
if(!(ctx->f = fopen("/etc/hosts", "r"))) return 0;
return 1;
}
void hostsreader_close(struct hostsreader *ctx) {
fclose(ctx->f);
}
int hostsreader_get(struct hostsreader *ctx, char* buf, size_t bufsize) {
while(1) {
if(!fgets(buf, bufsize, ctx->f)) return 0;
if(*buf == '#') continue;
char *p = buf;
size_t l = bufsize;
ctx->ip = p;
while(*p && !isspace(*p) && l) {
p++;
l--;
}
if(!l || !*p || p == ctx->ip) continue;
*p = 0;
p++;
while(*p && isspace(*p) && l) {
p++;
l--;
}
if(!l || !*p) continue;
ctx->name = p;
while(*p && !isspace(*p) && l) {
p++;
l--;
}
if(!l || !*p) continue;
*p = 0;
if(pc_isnumericipv4(ctx->ip)) return 1;
}
}
char* hostsreader_get_ip_for_name(const char* name, char* buf, size_t bufsize) {
struct hostsreader ctx;
char *res = 0;
if(!hostsreader_open(&ctx)) return 0;
while(hostsreader_get(&ctx, buf, bufsize)) {
if(!strcmp(ctx.name, name)) {
res = ctx.ip;
break;
}
}
hostsreader_close(&ctx);
return res;
}
#include "ip_type.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
ip_type4 hostsreader_get_numeric_ip_for_name(const char* name) {
char *hres;
char buf[320];
if((hres = hostsreader_get_ip_for_name(name, buf, sizeof buf))) {
struct in_addr c;
inet_aton(hres, &c);
ip_type4 res;
memcpy(res.octet, &c.s_addr, 4);
return res;
} else return IPT4_INVALID;
}
#ifdef HOSTSREADER_TEST
#include "ip_type.c"
int main(int a, char**b) {
char buf[256];
if(a != 2) return 1;
char * ret = hostsreader_get_ip_for_name(b[1], buf, sizeof buf);
printf("%s\n", ret ? ret : "null");
}
#endif

View File

@ -1,5 +0,0 @@
#include "ip_type.h"
const ip_type ip_type_invalid = { .as_int = -1 };
const ip_type ip_type_localhost = { {127, 0, 0, 1} };

View File

@ -6,10 +6,20 @@
typedef union {
unsigned char octet[4];
uint32_t as_int;
} ip_type4;
typedef struct {
union {
ip_type4 v4;
unsigned char v6[16];
} addr;
char is_v6;
} ip_type;
extern const ip_type ip_type_invalid;
extern const ip_type ip_type_localhost;
#define IPT4_INT(X) (ip_type4){.as_int = (X)}
#define IPT4_INVALID IPT4_INT(-1)
#define IPT4_BYTES(A,B,C,D) (ip_type4){.octet = {(A), (B), (C), (D)} }
#define IPT4_LOCALHOST IPT4_BYTES(127,0,0,1)
//RcB: DEP "ip_type.c"
#endif

File diff suppressed because it is too large Load Diff

View File

@ -7,10 +7,7 @@
* *
***************************************************************************/
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
@ -19,12 +16,17 @@
#include <sys/types.h>
#include <sys/wait.h>
#ifdef IS_MAC
#define _DARWIN_C_SOURCE
#endif
#include <dlfcn.h>
#include "common.h"
static int usage(char **argv) {
printf("\nUsage:\t%s -q -f config_file program_name [arguments]\n"
"\t-q makes proxychains quiet - this overrides the config setting\n"
"\t-f allows to manually specify a configfile to use\n"
"\t-f allows one to manually specify a configfile to use\n"
"\tfor example : proxychains telnet somehost.com\n" "More help in README file\n\n", argv[0]);
return EXIT_FAILURE;
}
@ -33,7 +35,9 @@ static const char *dll_name = DLL_NAME;
static char own_dir[256];
static const char *dll_dirs[] = {
#ifndef SUPER_SECURE /* CVE-2015-3887 */
".",
#endif
own_dir,
LIB_DIR,
"/lib",
@ -47,8 +51,12 @@ static void set_own_dir(const char *argv0) {
size_t l = strlen(argv0);
while(l && argv0[l - 1] != '/')
l--;
if(l == 0)
if(l == 0 || l >= sizeof(own_dir))
#ifdef SUPER_SECURE
memcpy(own_dir, "/dev/null/", 11);
#else
memcpy(own_dir, ".", 2);
#endif
else {
memcpy(own_dir, argv0, l - 1);
own_dir[l] = 0;
@ -66,6 +74,9 @@ int main(int argc, char *argv[]) {
size_t i;
const char *prefix = NULL;
if(argc == 2 && !strcmp(argv[1], "--help"))
return usage(argv);
for(i = 0; i < MAX_COMMANDLINE_FLAGS; i++) {
if(start_argv < argc && argv[start_argv][0] == '-') {
if(argv[start_argv][1] == 'q') {
@ -89,7 +100,7 @@ int main(int argc, char *argv[]) {
/* check if path of config file has not been passed via command line */
path = get_config_path(path, pbuf, sizeof(pbuf));
if(!quiet)
fprintf(stderr, LOG_PREFIX "config file found: %s\n", path);
@ -102,8 +113,10 @@ int main(int argc, char *argv[]) {
// search DLL
set_own_dir(argv[0]);
Dl_info dli;
dladdr(own_dir, &dli);
set_own_dir(dli.dli_fname);
i = 0;
while(dll_dirs[i]) {
@ -122,16 +135,31 @@ int main(int argc, char *argv[]) {
if(!quiet)
fprintf(stderr, LOG_PREFIX "preloading %s/%s\n", prefix, dll_name);
#ifndef IS_MAC
snprintf(buf, sizeof(buf), "LD_PRELOAD=%s/%s", prefix, dll_name);
putenv(buf);
#if defined(IS_MAC) || defined(IS_OPENBSD)
#define LD_PRELOAD_SEP ":"
#else
snprintf(buf, sizeof(buf), "DYLD_INSERT_LIBRARIES=%s/%s", prefix, dll_name);
putenv(buf);
putenv("DYLD_FORCE_FLAT_NAMESPACE=1");
/* Dynlinkers for Linux and most BSDs seem to support space
as LD_PRELOAD separator, with colon added only recently.
We use the old syntax for maximum compat */
#define LD_PRELOAD_SEP " "
#endif
#ifdef IS_MAC
putenv("DYLD_FORCE_FLAT_NAMESPACE=1");
#define LD_PRELOAD_ENV "DYLD_INSERT_LIBRARIES"
#else
#define LD_PRELOAD_ENV "LD_PRELOAD"
#endif
char *old_val = getenv(LD_PRELOAD_ENV);
snprintf(buf, sizeof(buf), LD_PRELOAD_ENV "=%s/%s%s%s",
prefix, dll_name,
/* append previous LD_PRELOAD content, if existent */
old_val ? LD_PRELOAD_SEP : "",
old_val ? old_val : "");
putenv(buf);
execvp(argv[start_argv], &argv[start_argv]);
perror("proxychains can't load process....");
fprintf(stderr, "proxychains: can't load process '%s'.", argv[start_argv]);
perror(" (hint: it's probably a typo)");
return EXIT_FAILURE;
}

View File

@ -1,26 +0,0 @@
#!/bin/sh
echo "ProxyChains-3.1 (http://proxychains.sf.net)"
usage() {
echo " usage:"
echo " $0 [h] [f config-file] <prog> [args]"
exit
}
if [ $# = 0 ] ; then
usage
fi
if [ $1 = "-h" ]; then
usage
fi
if [ "$1" = "-f" ]; then
export PROXYCHAINS_CONF_FILE=$2;
shift;
shift;
fi
export LD_PRELOAD=libproxychains.so.3
exec "$@"

View File

@ -22,20 +22,58 @@ strict_chain
# all proxies must be online to play in chain
# otherwise EINTR is returned to the app
#
#round_robin_chain
#
# Round Robin - Each connection will be done via chained proxies
# of chain_len length
# all proxies chained in the order as they appear in the list
# at least one proxy must be online to play in chain
# (dead proxies are skipped).
# the start of the current proxy chain is the proxy after the last
# proxy in the previously invoked proxy chain.
# if the end of the proxy chain is reached while looking for proxies
# start at the beginning again.
# otherwise EINTR is returned to the app
# These semantics are not guaranteed in a multithreaded environment.
#
#random_chain
#
# Random - Each connection will be done via random proxy
# (or proxy chain, see chain_len) from the list.
# this option is good to test your IDS :)
# Make sense only if random_chain
# Make sense only if random_chain or round_robin_chain
#chain_len = 2
# Quiet mode (no output from library)
#quiet_mode
# Proxy DNS requests - no leak for DNS data
proxy_dns
## Proxy DNS requests - no leak for DNS data
# (disable all of the 3 items below to not proxy your DNS requests)
# method 1. this uses the proxychains4 style method to do remote dns:
# a thread is spawned that serves DNS requests and hands down an ip
# assigned from an internal list (via remote_dns_subnet).
# this is the easiest (setup-wise) and fastest method, however on
# systems with buggy libcs and very complex software like webbrowsers
# this might not work and/or cause crashes.
proxy_dns
# method 2. use the old proxyresolv script to proxy DNS requests
# in proxychains 3.1 style. requires `proxyresolv` in $PATH
# plus a dynamically linked `dig` binary.
# this is a lot slower than `proxy_dns`, doesn't support .onion URLs,
# but might be more compatible with complex software like webbrowsers.
#proxy_dns_old
# method 3. use proxychains4-daemon process to serve remote DNS requests.
# this is similar to the threaded `proxy_dns` method, however it requires
# that proxychains4-daemon is already running on the specified address.
# on the plus side it doesn't do malloc/threads so it should be quite
# compatible with complex, async-unsafe software.
# note that if you don't start proxychains4-daemon before using this,
# the process will simply hang.
#proxy_dns_daemon 127.0.0.1:1053
# set the class A subnet number to use for the internal remote DNS mapping
# we use the reserved 224.x.x.x range by default,
@ -56,6 +94,9 @@ tcp_connect_time_out 8000
### Examples for localnet exclusion
## localnet ranges will *not* use a proxy to connect.
## note that localnet works only when plain IP addresses are passed to the app,
## the hostname resolves via /etc/hosts, or proxy_dns is disabled or proxy_dns_old used.
## Exclude connections to 192.168.1.0/24 with port 80
# localnet 192.168.1.0:80/255.255.255.0
@ -64,22 +105,42 @@ tcp_connect_time_out 8000
## Exclude connections to ANYwhere with port 80
# localnet 0.0.0.0:80/0.0.0.0
# localnet [::]:80/0
## RFC5735 Loopback address range
## RFC6890 Loopback address range
## if you enable this, you have to make sure remote_dns_subnet is not 127
## you'll need to enable it if you want to use an application that
## connects to localhost.
# localnet 127.0.0.0/255.0.0.0
# localnet ::1/128
## RFC1918 Private Address Ranges
# localnet 10.0.0.0/255.0.0.0
# localnet 172.16.0.0/255.240.0.0
# localnet 192.168.0.0/255.255.0.0
### Examples for dnat
## Trying to proxy connections to destinations which are dnatted,
## will result in proxying connections to the new given destinations.
## Whenever I connect to 1.1.1.1 on port 1234 actually connect to 1.1.1.2 on port 443
# dnat 1.1.1.1:1234 1.1.1.2:443
## Whenever I connect to 1.1.1.1 on port 443 actually connect to 1.1.1.2 on port 443
## (no need to write :443 again)
# dnat 1.1.1.2:443 1.1.1.2
## No matter what port I connect to on 1.1.1.1 port actually connect to 1.1.1.2 on port 443
# dnat 1.1.1.1 1.1.1.2:443
## Always, instead of connecting to 1.1.1.1, connect to 1.1.1.2
# dnat 1.1.1.1 1.1.1.2
# ProxyList format
# type host port [user pass]
# type ip port [user pass]
# (values separated by 'tab' or 'blank')
#
# only numeric ipv4 addresses are valid
#
#
# Examples:
#
@ -89,7 +150,8 @@ tcp_connect_time_out 8000
# http 192.168.39.93 8080
#
#
# proxy types: http, socks4, socks5
# proxy types: http, socks4, socks5, raw
# * raw: The traffic is simply forwarded to the proxy without modification.
# ( auth types supported: "basic"-http "user/pass"-socks )
#
[ProxyList]

View File

@ -1,8 +1,8 @@
#!/bin/sh
# This script is called by proxychains to resolve DNS names
# This is a legacy script that uses "dig" or "drill" to do DNS lookups via TCP.
# DNS server used to resolve names
DNS_SERVER=4.2.2.2
test -z "$DNS_SERVER" && DNS_SERVER=8.8.8.8
if [ $# = 0 ] ; then
@ -12,5 +12,12 @@ if [ $# = 0 ] ; then
fi
export LD_PRELOAD=libproxychains.so
dig $1 @$DNS_SERVER +tcp | awk '/A.+[0-9]+\.[0-9]+\.[0-9]/{print $5;}'
test -z $LD_PRELOAD && export LD_PRELOAD=libproxychains4.so
if type dig 1>/dev/null 2>&1 ; then
dig $1 @$DNS_SERVER +tcp | awk '/A.?[0-9]+\.[0-9]+\.[0-9]/{print $5;}'
elif type drill 1>/dev/null 2>&1 ; then
drill -t4 $1 @$DNS_SERVER | awk '/A.+[0-9]+\.[0-9]+\.[0-9]/{print $5;}'
else
echo "error: neither dig nor drill found" >&2
fi

99
src/rdns.c Normal file
View File

@ -0,0 +1,99 @@
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include "rdns.h"
#include "allocator_thread.h"
#include "remotedns.h"
#ifndef HAVE_SOCK_CLOEXEC
#define SOCK_CLOEXEC 0
#endif
//static enum dns_lookup_flavor dns_flavor;
#define dns_flavor rdns_get_flavor()
static struct sockaddr_in rdns_server;
size_t rdns_daemon_get_host_for_ip(ip_type4 ip, char* readbuf) {
struct at_msg msg = {
.h.msgtype = ATM_GETNAME,
.h.datalen = htons(4),
.m.ip = ip,
};
int fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
sendto(fd, &msg, sizeof(msg.h)+4, 0, (void*)&rdns_server, sizeof(rdns_server));
recvfrom(fd, &msg, sizeof msg, 0, (void*)0, (void*)0);
close(fd);
msg.h.datalen = ntohs(msg.h.datalen);
if(!msg.h.datalen || msg.h.datalen > 256) return 0;
memcpy(readbuf, msg.m.host, msg.h.datalen);
return msg.h.datalen - 1;
}
static ip_type4 rdns_daemon_get_ip_for_host(char* host, size_t len) {
struct at_msg msg = {
.h.msgtype = ATM_GETIP,
};
if(len >= 256) return IPT4_INT(-1);
memcpy(msg.m.host, host, len+1);
msg.h.datalen = htons(len+1);
int fd = socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC, 0);
sendto(fd, &msg, sizeof(msg.h)+len+1, 0, (void*)&rdns_server, sizeof(rdns_server));
recvfrom(fd, &msg, sizeof msg, 0, (void*)0, (void*)0);
close(fd);
if(ntohs(msg.h.datalen) != 4) return IPT4_INT(-1);
return msg.m.ip;
}
const char *rdns_resolver_string(enum dns_lookup_flavor flavor) {
static const char tab[][7] = {
[DNSLF_LIBC] = "off",
[DNSLF_FORKEXEC] = "old",
[DNSLF_RDNS_THREAD] = "thread",
[DNSLF_RDNS_DAEMON] = "daemon",
};
return tab[flavor];
}
void rdns_init(enum dns_lookup_flavor flavor) {
static int init_done = 0;
if(!init_done) switch(flavor) {
case DNSLF_RDNS_THREAD:
at_init();
break;
case DNSLF_RDNS_DAEMON:
default:
break;
}
init_done = 1;
}
void rdns_set_daemon(struct sockaddr_in* addr) {
rdns_server = *addr;
}
#if 0
enum dns_lookup_flavor rdns_get_flavor(void) {
return dns_flavor;
}
#endif
size_t rdns_get_host_for_ip(ip_type4 ip, char* readbuf) {
switch(dns_flavor) {
case DNSLF_RDNS_THREAD: return at_get_host_for_ip(ip, readbuf);
case DNSLF_RDNS_DAEMON: return rdns_daemon_get_host_for_ip(ip, readbuf);
default:
abort();
}
}
ip_type4 rdns_get_ip_for_host(char* host, size_t len) {
switch(dns_flavor) {
case DNSLF_RDNS_THREAD: return at_get_ip_for_host(host, len);
case DNSLF_RDNS_DAEMON: return rdns_daemon_get_ip_for_host(host, len);
default:
abort();
}
}

28
src/rdns.h Normal file
View File

@ -0,0 +1,28 @@
#ifndef RDNS_H
#define RDNS_H
#include <unistd.h>
#include <netinet/in.h>
#include "ip_type.h"
#include "remotedns.h"
enum dns_lookup_flavor {
DNSLF_LIBC = 0,
DNSLF_FORKEXEC,
DNSLF_RDNS_START,
DNSLF_RDNS_THREAD = DNSLF_RDNS_START,
DNSLF_RDNS_DAEMON,
};
void rdns_init(enum dns_lookup_flavor flavor);
void rdns_set_daemon(struct sockaddr_in* addr);
const char *rdns_resolver_string(enum dns_lookup_flavor flavor);
size_t rdns_get_host_for_ip(ip_type4 ip, char* readbuf);
ip_type4 rdns_get_ip_for_host(char* host, size_t len);
//enum dns_lookup_flavor rdns_get_flavor(void);
#define rdns_get_flavor() proxychains_resolver
extern enum dns_lookup_flavor proxychains_resolver;
#endif

31
src/remotedns.h Normal file
View File

@ -0,0 +1,31 @@
#ifndef REMOTEDNS_H
#define REMOTEDNS_H
#include <unistd.h>
#include "ip_type.h"
#define MSG_LEN_MAX 256
enum at_msgtype {
ATM_GETIP = 0,
ATM_GETNAME,
ATM_FAIL,
ATM_EXIT,
};
struct at_msghdr {
unsigned char msgtype; /* at_msgtype */
char reserved;
unsigned short datalen;
};
struct at_msg {
struct at_msghdr h;
union {
char host[260];
ip_type4 ip;
} m;
};
#endif

View File

@ -1,53 +0,0 @@
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#ifndef PAGE_SIZE
#define PAGE_SIZE 4096
#endif
#include "shm.h"
#include "debug.h"
#if 0
#include <sys/mman.h>
#include <sys/ipc.h>
#include <sys/shm.h>
/* allocates shared memory which can be accessed from the parent and its childs */
void *shm_realloc(void* old, size_t old_size, size_t new_size) {
//PFUNC();
void *nu = mmap(NULL, new_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
if(old) {
if(!nu) return NULL;
assert(new_size >= old_size);
memcpy(nu, old, old_size);
munmap(old, old_size);
}
return nu;
}
#endif
void stringpool_init(struct stringpool* sp) {
PFUNC();
memset(sp, 0, sizeof *sp);
}
char* stringpool_add(struct stringpool *sp, char* s, size_t len) {
//PFUNC();
if(len > sp->alloced - sp->used) {
size_t newsz = sp->used + len;
size_t inc = PAGE_SIZE - (newsz % PAGE_SIZE);
newsz += (inc == PAGE_SIZE) ? 0 : inc;
void* p = realloc(sp->start, newsz);
if(p) {
sp->start = p;
sp->alloced = newsz;
} else
return 0;
}
char* ret = sp->start + sp->used;
memcpy(ret, s, len);
sp->used += len;
return ret;
}

View File

@ -1,17 +0,0 @@
#ifndef SHM_H
#define SHM_H
#include <unistd.h>
struct stringpool {
size_t alloced;
size_t used;
char* start;
};
void stringpool_init(struct stringpool* sp);
char* stringpool_add(struct stringpool *sp, char* s, size_t len);
#if 0
void *shm_realloc(void* old, size_t old_size, size_t new_size);
#endif
//RcB: DEP "shm.c"
#endif

View File

@ -1,13 +0,0 @@
#include "stringdump.h"
#include "debug.h"
struct stringpool mem;
char *dumpstring(char* s, size_t len) {
PFUNC();
return stringpool_add(&mem, s, len);
}
void dumpstring_init(void) {
stringpool_init(&mem);
}

View File

@ -1,12 +0,0 @@
#ifndef STRINGDUMP_H
#define STRINGDUMP_H
#include "shm.h"
#include <unistd.h>
char *dumpstring(char* s, size_t len);
void dumpstring_init(void);
//RcB: DEP "stringdump.h"
#endif

6
src/version.c Normal file
View File

@ -0,0 +1,6 @@
#include "version.h"
static const char version[] = VERSION;
const char *proxychains_get_version(void) {
return version;
}

View File

@ -3,39 +3,84 @@
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <assert.h>
#include <string.h>
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#endif
int main(void) {
static int doit(const char* host, const char* service) {
struct addrinfo *result;
struct addrinfo *res;
int error;
/* resolve the domain name into a list of addresses */
error = getaddrinfo("www.example.com", NULL, NULL, &result);
error = getaddrinfo(host, service, NULL, &result);
if (error != 0)
{
{
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
return EXIT_FAILURE;
}
}
/* loop over all returned results and do inverse lookup */
for (res = result; res != NULL; res = res->ai_next)
{
{
char hostname[NI_MAXHOST] = "";
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0);
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0);
if (error != 0)
{
fprintf(stderr, "error in getnameinfo: %s\n", gai_strerror(error));
continue;
}
if (*hostname != '\0')
printf("hostname: %s\n", hostname);
}
int port = 0;
if(res->ai_family == AF_INET) port = ((struct sockaddr_in*)res->ai_addr)->sin_port;
else if(res->ai_family == AF_INET6) port = ((struct sockaddr_in6*)res->ai_addr)->sin6_port;
port = ntohs(port);
printf("hostname: %s, port: %d\n", hostname, port);
}
freeaddrinfo(result);
return EXIT_SUCCESS;
}
/* reproduce use of getaddrinfo as used by nmap 7.91's canonicalize_address */
int canonicalize_address(struct sockaddr_storage *ss, struct sockaddr_storage *output) {
char canonical_ip_string[NI_MAXHOST];
struct addrinfo *ai;
int rc;
/* Convert address to string. */
rc = getnameinfo((struct sockaddr *) ss, sizeof(*ss),
canonical_ip_string, sizeof(canonical_ip_string), NULL, 0, NI_NUMERICHOST);
assert(rc == 0);
struct addrinfo hints = {
.ai_family = ss->ss_family,
.ai_socktype = SOCK_DGRAM,
.ai_flags = AI_NUMERICHOST,
};
rc = getaddrinfo(canonical_ip_string, NULL, &hints, &ai);
if (rc != 0 || ai == NULL)
return -1;
assert(ai->ai_addrlen > 0 && ai->ai_addrlen <= (int) sizeof(*output));
memcpy(output, ai->ai_addr, ai->ai_addrlen);
freeaddrinfo(ai);
return 0;
}
int main(void) {
int ret;
ret = doit("www.example.com", NULL);
ret = doit("www.example.com", "80");
struct sockaddr_storage o, ss = {.ss_family = PF_INET};
struct sockaddr_in *v4 = &ss;
struct sockaddr_in6 *v6 = &ss;
memcpy(&v4->sin_addr, "\x7f\0\0\1", 4);
ret = canonicalize_address(&ss, &o);
assert (ret == 0);
ss.ss_family = PF_INET6;
memcpy(&v6->sin6_addr, "\0\0\0\0" "\0\0\0\0" "\0\0\0\0""\0\0\0\1", 16);
ret = canonicalize_address(&ss, &o);
assert (ret == 0);
return ret;
}

View File

@ -0,0 +1,23 @@
#include <stdio.h>
#include <netdb.h>
#include "../src/common.c"
void printhostent(struct hostent *hp) {
char ipbuf[16];
pc_stringfromipv4(hp->h_addr_list[0], ipbuf);
printf("alias: %p, len: %d, name: %s, addrlist: %p, addrtype: %d, ip: %s\n",
hp->h_aliases,
hp->h_length,
hp->h_name,
hp->h_addr_list,
hp->h_addrtype,
ipbuf
);
}
int main(int argc, char**argv) {
struct hostent* ret;
if(argc == 1) return 1;
ret = gethostbyname(argv[1]);
if(ret) printhostent(ret);
return 0;
}

View File

@ -1,6 +1,6 @@
#include <netdb.h>
#include <stdio.h>
#include "../src/common.h"
#include "../src/common.c"
void printhostent(struct hostent *hp) {
char ipbuf[16];

139
tests/test_getnameinfo.c Normal file
View File

@ -0,0 +1,139 @@
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define satosin(x) ((struct sockaddr_in *) &(x))
#define SOCKADDR(x) (satosin(x)->sin_addr.s_addr)
#define SOCKADDR_2(x) (satosin(x)->sin_addr)
#define SOCKPORT(x) (satosin(x)->sin_port)
#define SOCKFAMILY(x) (satosin(x)->sin_family)
#define ASSERT(X) { if(!(X)) printf("ASSERTION FAILED: %s @%s:%d\n", # X, __FILE__, __LINE__); }
#define CLR() { hbuf[0] = 0; sbuf[0] = 0; }
int main() {
struct sockaddr_in a = {0}, *sa = &a;
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
a.sin_port = htons(80);
memcpy( &a.sin_addr , (char[]) {127,0,0,1}, 4);
int ret;
if ((ret = getnameinfo((void*)sa, 0, hbuf, sizeof(hbuf), sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == EAI_FAMILY);
CLR();
if ((ret = getnameinfo((void*)sa, sizeof a, hbuf, sizeof(hbuf), sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == EAI_FAMILY);
CLR();
SOCKFAMILY(a) = AF_INET;
if ((ret = getnameinfo((void*)sa, sizeof a, hbuf, 1, sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == EAI_OVERFLOW);
CLR();
if ((ret = getnameinfo((void*)sa, sizeof a, hbuf, 0, sbuf,
1, NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == EAI_OVERFLOW);
CLR();
if ((ret = getnameinfo((void*)sa, sizeof(a) - 1, hbuf, 0, sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == EAI_FAMILY);
CLR();
if ((ret = getnameinfo((void*)sa, sizeof a, hbuf, 0, sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == 0 && !strcmp("80", sbuf));
CLR();
if ((ret = getnameinfo((void*)sa, sizeof a, hbuf, sizeof hbuf, sbuf,
0, NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == 0 && !strcmp("127.0.0.1",hbuf));
CLR();
if ((ret = getnameinfo((void*)sa, sizeof a, hbuf, sizeof(hbuf), sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == 0 && !strcmp("127.0.0.1",hbuf) && !strcmp("80", sbuf));
CLR();
struct sockaddr_in6 b = {0}, *sb = &b;
b.sin6_port = htons(8080);
b.sin6_family = AF_INET6;
memcpy(&b.sin6_addr,"\0\0\0\0\0\0\0\0\0\0\xff\xff\xc0\xa8\1\2", 16);
if ((ret = getnameinfo((void*)sb, sizeof b, hbuf, sizeof(hbuf), sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == 0 && !strcmp("192.168.1.2",hbuf) && !strcmp("8080", sbuf));
CLR();
b.sin6_scope_id = 3;
memcpy(&b.sin6_addr,"\0\0\xaa\0\0\0\0\0\0\0\0\xff\xc0\xa8\1\2", 16);
if ((ret = getnameinfo((void*)sb, sizeof b, hbuf, sizeof(hbuf), sbuf,
sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV | NI_NUMERICSCOPE)) == 0)
printf("host=%s, serv=%s\n", hbuf, sbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == 0);
b.sin6_port = 0;
b.sin6_scope_id = 0;
memcpy(&b.sin6_addr,"\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\1", 16);
if ((ret = getnameinfo((void*)sb, sizeof b, hbuf, sizeof(hbuf), NULL,
0, NI_NUMERICHOST)) == 0)
printf("host=%s\n", hbuf);
else
printf("%s\n", gai_strerror(ret));
ASSERT(ret == 0);
return 0;
}

66
tests/test_sendto.c Normal file
View File

@ -0,0 +1,66 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#ifndef MSG_FASTOPEN
# define MSG_FASTOPEN 0x20000000
#endif
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
if (argc < 4) {
printf("Usage: %s host port method(connect or sendto)\n", argv[0]);
return 1;
}
const char *hostname = argv[1];
const int portno = atoi(argv[2]);
const char *method = argv[3];
char request[BUFSIZ];
sprintf(request, "GET / HTTP/1.0\r\nHost: %s\r\n\r\n", hostname);
int sockfd, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[BUFSIZ];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr, "%s: no such host\n", hostname);
return 1;
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (!strcmp(method, "connect")) {
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
error("connect");
n = send(sockfd, request, strlen(request), 0);
} else if (!strcmp(method, "sendto")) {
n = sendto(sockfd, request, strlen(request), MSG_FASTOPEN, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
} else {
printf("Unknown method %s\n", method);
return 1;
}
if (n < 0)
error("send");
memset(buffer, 0, BUFSIZ);
n = read(sockfd, buffer, BUFSIZ - 1);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n", buffer);
close(sockfd);
return 0;
}

42
tests/test_v4_in_v6.c Normal file
View File

@ -0,0 +1,42 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
static void v4_to_v6(const struct in_addr *v4, struct in6_addr *v6) {
memset(v6, 0, sizeof(*v6));
v6->s6_addr[10]=0xff;
v6->s6_addr[11]=0xff;
memcpy(&v6->s6_addr[12], &v4->s_addr, 4);
}
int main(void) {
struct addrinfo *result;
struct addrinfo *res;
const struct addrinfo hints = { .ai_family = AF_INET };
int error, sock;
/* resolve the domain name into a list of addresses */
error = getaddrinfo("www.example.com", NULL, &hints, &result);
if (error != 0) {
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
return EXIT_FAILURE;
}
if((sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
perror("socket");
return EXIT_FAILURE;
}
struct sockaddr_in6 a = { .sin6_family = AF_INET6,
.sin6_port = htons(80) };
v4_to_v6(&((struct sockaddr_in *)result->ai_addr)->sin_addr, &a.sin6_addr);
freeaddrinfo(result);
if((error = connect(sock, (struct sockaddr *)&a, sizeof(a))) == -1) {
perror("connect");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

64
tools/install.sh Executable file
View File

@ -0,0 +1,64 @@
#!/bin/sh
#
# This is an actually-safe install command which installs the new
# file atomically in the new location, rather than overwriting
# existing files.
#
usage() {
printf "usage: %s [-D] [-l] [-m mode] src dest\n" "$0" 1>&2
exit 1
}
mkdirp=
symlink=
mode=755
while getopts Dlm: name ; do
case "$name" in
D) mkdirp=yes ;;
l) symlink=yes ;;
m) mode=$OPTARG ;;
?) usage ;;
esac
done
shift $(($OPTIND - 1))
test "$#" -eq 2 || usage
src=$1
dst=$2
tmp="$dst.tmp.$$"
case "$dst" in
*/) printf "%s: %s ends in /\n", "$0" "$dst" 1>&2 ; exit 1 ;;
esac
set -C
set -e
if test "$mkdirp" ; then
umask 022
case "$2" in
*/*) mkdir -p "${dst%/*}" ;;
esac
fi
trap 'rm -f "$tmp"' EXIT INT QUIT TERM HUP
umask 077
if test "$symlink" ; then
ln -s "$1" "$tmp"
else
cat < "$1" > "$tmp"
chmod "$mode" "$tmp"
fi
mv -f "$tmp" "$2"
test -d "$2" && {
rm -f "$2/$tmp"
printf "%s: %s is a directory\n" "$0" "$dst" 1>&2
exit 1
}
exit 0

12
tools/version.sh Normal file
View File

@ -0,0 +1,12 @@
#!/bin/sh
if test -d .git ; then
if type git >/dev/null 2>&1 ; then
git describe --tags --match 'v[0-9]*' 2>/dev/null \
| sed -e 's/^v//' -e 's/-/-git-/'
else
sed 's/$/-git/' < VERSION
fi
else
cat VERSION
fi