Version 1.8.0.0
[socat.git] / EXAMPLES
blob51b10ffcc78fc74b432a7e0a85350d084997bb72
2 // Examples for using socat (and filan)
5 //"$" means normal user, "#" requires privileges, "//" starts a comment
7 ///////////////////////////////////////////////////////////////////////////////
8 // Similar to netcat
10 // Connect to 10.1.1.1 on port 80 and relay to and from stdio
11 $ socat - TCP:10.1.1.1:80       # similar to "netcat 10.1.1.1 80"
13 // Listen on port 25, wait for an incoming connection, use CR+NL on this
14 // connection, relay data to and from stdio;
15 // then emulate a mailserver by hand :-)
16 # socat - TCP-LISTEN:25,crlf
18 // Listen on port 25, wait for an incoming connection, use CR+NL on this
19 // connection, relay data to and from stdio, but have line editing and history;
20 // then emulate a mailserver by hand :-)
21 # socat READLINE TCP-LISTEN:25,crlf
23 // Provide a transient history enabled front end to stupid line based
24 // interactive programs 
25 $ socat \
26         READLINE \
27         EXEC:"nslookup",pty,ctty,setsid,echo=0
28 // Same works for ftp (but password is not hidden)
30 // You may also use a file based history list
31 $ socat \
32         READLINE,history=.nslookup_hist \
33         EXEC:"nslookup",pty,ctty,setsid,echo=0
34 // Using ~ as abbreviation for $HOME does not work!
36 // Poor mans 'telnetd' replacement
37 # socat \
38         TCP-L:2023,reuseaddr,fork \
39         EXEC:/bin/login,pty,setsid,setpgid,stderr,ctty
40 // and here an appropriate client:
41 $ socat \
42         -,raw,echo=0 \
43         TCP:172.16.181.130:2023
44 // Use ssl with client and server certificate for improved security;
45 // replace /bin/login by /bin/bash when using SSL client authentication, can be
46 // run without root then
48 // This is a cool trick, proposed by Christophe Lohr, to dump communications to
49 // two files; it would also work for other manipulations (recode, compress...)
50 // and it might also work with netcat ;-)
51 $ socat \
52         TCP-LISTEN:5555 \
53         SYSTEM:'tee l2r | socat - "TCP:remote:5555" | tee r2l' 
55 ///////////////////////////////////////////////////////////////////////////////
56 // Emergence solution because usleep(1) is not always available
57 // this will "sleep" for 0.1s
58 $ socat -T 0.1 PIPE PIPE
60 ///////////////////////////////////////////////////////////////////////////////
61 // A very primitive HTTP/1.0 echo server (problems: sends reply headers before
62 // request; hangs if client does not shutdown - HTTP keep-alive) 
63 // wait for a connection on port 8000; do not wait for request, but immediately
64 // start a shell that sends reply headers and an empty line; then echo all
65 // incoming data back to client
66 $ socat \
67         TCP-LISTEN:8000,crlf \
68         SYSTEM:"echo HTTP/1.0 200; echo Content-Type\: text/plain; echo; cat"
70 // A less primitive HTTP echo server that sends back not only the reqest but
71 // also server and client address and port. Might have portability issues with
72 // echo
73 $ socat -T 1 -d -d \
74         TCP-L:10081,reuseaddr,fork,crlf \
75         SYSTEM:"echo -e \"\\\"HTTP/1.0 200 OK\\\nDocumentType: text/html\\\n\\\n<html>date: \$\(date\)<br>server:\$SOCAT_SOCKADDR:\$SOCAT_SOCKPORT<br>client: \$SOCAT_PEERADDR:\$SOCAT_PEERPORT\\\n<pre>\\\"\"; cat; echo -e \"\\\"\\\n</pre></html>\\\"\""
77 ///////////////////////////////////////////////////////////////////////////////
78 // For communicating with an attached modem, I had reasonable results with
79 // following command line. Required privileges depend on device mode.
80 // After leaving socat, type "sane".
81 // Replace /dev/ttyS0 by the correct serial line or with /dev/modem
82 $ socat \
83         READLINE \
84         /dev/ttyS0,raw,echo=0,crlf
85 // or
86 $ socat \
87         READLINE \
88         /dev/ttyS0,raw,echo=0,crlf,nonblock
89 // then enter "at$"
91 ///////////////////////////////////////////////////////////////////////////////
92 // Relay TCP port 80 from everywhere (internet, intranet, dmz) through your
93 // firewall to your DMZ webserver (like plug-gw) 
94 // Listen on port 80; whenever a connection is made, fork a new process (parent
95 // Process keeps accepting connections), su to nobody, and connect to 
96 // www.dmz.mydomain.org on port 80.
97 // Attention: this is a substitute for a reverse proxy without providing
98 // application level security.
99 # socat \
100         TCP-LISTEN:80,reuseaddr,fork,su=nobody \
101         TCP:www.dmz.mydomain.org:80
102 // Note: parent process keeps running as root, su after forking
104 ///////////////////////////////////////////////////////////////////////////////
105 // Relay mail from your DMZ server through your firewall.
106 // accept connections only on dmz interface and allow connections only from
107 // smtp.dmz.mydomain.org. 
108 // the advantages over plug-gw and other relays are:
109 // * you can bind to an IP address (even an alias), therefore enhance security
110 // * in your OS you can create several IP aliases and bind another socat daemon
111 //   to each, making several application servers addressable
112 // * lots of options, like switching user, chroot, IP performance tuning
113 // * no need for inetd
114 # socat -lm -d -d \
115         TCP-LISTEN:25,bind=fw.dmz.mydomain.org,fork,su=nobody,range=smtp.dmz.mydomain.org/32 \
116         TCP:smtp.intra.mydomain.org:25
118 ///////////////////////////////////////////////////////////////////////////////
119 // Convert line terminator in ascii streams, stdin to stdout
120 // use unidirectional mode, convert nl to crnl
121 $ socat -u - -,crlf
122 // or cr to nl
123 $ socat -u -,cr -
125 // Save piped data similar to 'tee':
126 // copies stdin to stdout, but writes everything to the file too
127 $ socat \
128         -,echo=0 \
129         OPEN:/tmp/myfile,create,trunc,ignoreeof!!/tmp/myfile
131 ///////////////////////////////////////////////////////////////////////////////
132 // Intrusion testing
134 // Found an XWindow Server behind IP filters with FTP data hole? (you are
135 // lucky!) 
136 // prepare your host:
137 # rm -f /tmp/.X11-unix/X1
138 // relay a pseudo display :1 on your machine to victim:0
139 # socat \
140         UNIX-LISTEN:/tmp/.X11-unix/X1,fork \
141         TCP:host.victim.org:6000,sp=20 &
142 // and try to take a screendump (must be very lucky - when server has not even
143 // host based authentication!)
144 # xwd -root -display :1 -silent >victim.xwd
146 // You sit behind a socks firewall that has IP filters but lazily allows socks
147 // connections to loopback and has only host based X11 security.
148 // like above, but from your inside client:
149 # socat \
150         UNIX-LISTEN:/tmp/.X11-unix/X1,fork \
151         SOCKS4:firewall:loopback:6000
152 // or for the HTTP proxy:
153 # socat \
154         UNIX-LISTEN:/tmp/.X11-unix/X1,fork \
155         PROXY:firewall:loopback:6000
157 ///////////////////////////////////////////////////////////////////////////////
158 // forms of stdin with stdout, all equivalent
159 $ socat PIPE -
160 $ socat PIPE STDIO
161 $ socat PIPE STDIN!!STDOUT
162 $ socat PIPE STDIO!!STDIO
163 $ socat PIPE -!!-
164 $ socat PIPE FD:0!!FD:1
165 $ socat PIPE 0!!1
166 $ socat PIPE /dev/stdin!!/dev/stdout    // when your OS provides these
168 ///////////////////////////////////////////////////////////////////////////////
169 // some echo address examples
170 $ socat - PIPE
171 $ socat - PIPE:/tmp/pipi                // other version of echo
172 $ socat - PIPE:/tmp/pipi,nonblock!!/tmp/pipi    // other version of echo
173 $ socat - EXEC:/bin/cat         // another echo
174 $ socat - SYSTEM:/bin/cat               // another echo
175 $ socat - TCP:loopback:7        // if inetd echo/TCP service activated
176 $ socat - UDP:loopback:7        // if inetd echo/UDP service activated
177 $ socat - /tmp/hugo,trunc,ignoreeof!!/tmp/hugo  // with delay
178 $ socat - UDP:loopback:2000,bind=:2000  // self "connection"
179 $ socat - TCP:loopback:2000,bind=:2000  // Linux bug?
180 # socat - IP:loopback:222       // raw protocol, self "connected" (attention,
181 // Linux might drop packets with less than 8 bytes payload)
183 ///////////////////////////////////////////////////////////////////////////////
184 // unidirectional data transfer
185 $ socat -u - -
186 // like "tail -f", but start with showing all file contents:
187 $ socat -u FILE:/var/log/syslog.debug,ignoreeof -       
188 // like "tail -f", but do not show existing file contents:
189 $ socat -u FILE:/var/log/syslog.debug,ignoreeof,seek-end -
190 // write to new file, create with given permission and group (must be member) - race condition with group!!!
191 $ socat -u - CREATE:/tmp/outfile1,group=floppy,perm=0640
193 // for an existing file /tmp/outfile1
194 # socat -u - FILE:/tmp/outfile1,group=floppy,perm=0700,user=4321
197 ///////////////////////////////////////////////////////////////////////////////
198 // File handling
199 $ socat - FILE:/tmp/outfile1,ignoreeof!!FILE:/tmp/outfile1,append       // prints outfile1, then echoes input and protocols into file (appends to old data)
201 ///////////////////////////////////////////////////////////////////////////////
202 // UNIX socket handling
204 // Create a listening unix socket
205 $ rm -f /tmp/mysocket; socat UNIX-LISTEN:/tmp/mysocket -
206 // From another terminal, connect to this socket
207 $ socat UNIX:/tmp/mysocket -
208 // then transfer data bidirectionally
211 ///////////////////////////////////////////////////////////////////////////////
212 // Transport examples
214 // Socks relay (externally socksify applications);
215 // your ssh client and OS are not socksified, but you want to pass a socks
216 // server with ssh:
217 $ socat \
218         TCP-LISTEN:10022,fork \
219         SOCKS4:socks.mydomain.org:ssh-serv:22
220 $ ssh -p 10022 loopback 
221 // or better define a ProxyCommand in ~/.ssh/config:
222 ProxyCommand socat - SOCKS:socks.mydomain.org:%h:%p
223 // and with proxy:
224 ProxyCommand socat - PROXY:proxy.mydomain.org:%h:%p,proxyport=8000
226 ///////////////////////////////////////////////////////////////////////////////
227 // Application examples
229 // run sendmail daemon with your favorite network options
230 # socat \
231         TCP-LISTEN:25,fork,ip-ttl=4,ip-tos=7,tcp-maxseg=576 \
232         EXEC:"/usr/sbin/sendmail -bs",nofork
234 // Local mail delivery over UNIX socket - no SUID program required
235 # socat \
236         UNIX-LISTEN:/tmp/postoffice,fork,perm-early=0666 \
237         EXEC:"/usr/sbin/sendmail -bs"
238 $ socat - /tmp/postoffice
240 ///////////////////////////////////////////////////////////////////////////////
241 // Uses of filan
242 // See what your operating system opens for you
243 $ filan
244 // or if that was too detailled
245 $ filan -s
246 // See what file descriptors are passed via exec function
247 $ socat - EXEC:"filan -s",nofork
248 $ socat - EXEC:"filan -s"
249 $ socat - EXEC:"filan -s",pipes,stderr
250 $ socat - EXEC:"filan -s",pipes
251 $ socat - EXEC:"filan -s",pty
252 // see what's done by your shell and with option "pipes"
253 $ socat - SYSTEM:"filan -s",pipes
254 // see if gdb gives you an equivalent environment or opens some files for your program
255 $ gdb ./filan
256 (gdb) r -s
257 (gdb) r
259 ///////////////////////////////////////////////////////////////////////////////
260 // Want to use chat from the ppp package?
261 // Note: some OS's do not need "-e" for echo to print control characters
262 // Note: chat might send bytes one by one
263 // With AIX, a similar program is available under the name "pppdial"
264 $ socat -d -d \
265         TCP:localhost:25,crlf,nodelay \
266         EXEC:'/usr/sbin/chat -v -s "\"220 \"" "\"HELO loopback\"" "\"250 \"" "\"MAIL FROM: <hugo@localhost>\"" "\"250 \"" "\"RCPT TO: root\"" "\"250 \"" "\"DATA\"" "\"354 \"" "\"test1'$(echo -e "\r.")'\"" "\"250 \"" "\"QUIT\"" "\"221 \""',pty,echo=0,cr
268 //////////////////////////////////////////////////////////////////////////////
269 // IP6
271 # socat \
272         READLINE \
273         TCP6:[::1]:21   # if your inetd/ftp is listening on ip6
275 //////////////////////////////////////////////////////////////////////////////
276 // VSOCK
277 # Start a linux VM with cid=21
278 #    qemu-system-x86_64 -m 1G -smp 2 -cpu host -M accel=kvm \
279 #     -drive if=virtio,file=/path/to/fedora.img,format=qcow2  \
280 #     -device vhost-vsock-pci,guest-cid=21
282 # guest listens on port 1234 and host connects to it
283 guest$ socat - VSOCK-LISTEN:1234
284 host$ socat - VSOCK-CONNECT:21:1234
286 # Host (well know CID_HOST = 2) listens on port 4321 and guest connects to it
287 host$ socat - VSOCK-LISTEN:4321
288 guest$ socat - VSOCK-CONNECT:2:4321
290 ///////////////////////////////////////////////////////////////////////////////
291 // Application server solutions
292 // Run a program (here: /bin/sh) chrooted, unprivileged; 
293 // parent process stays in real / running as root
294 # socat -d -d - EXEC:/bin/sh,chroot=/home/sandbox,su=sandbox,pty
296 // Make a program available on the network chrooted, unprivileged; 
297 // parent process stays in / running as root
298 // script path is already chrooted
299 # ./socat -lm -d -d \
300         TCP-LISTEN:5555,fork \
301         EXEC:/bin/myscript,chroot=/home/sandbox,su=sandbox,pty,stderr
302 // To avoid terminal problems, you might - instead of telnet - connect using
303 $ socat \
304         -,icanon=0,echo=0 \
305         TCP:target:5555; reset
308 // Access local display from ssh server, when ssh port forwarding is disabled
309 // Socat must be installed on ssh server host
310 // Might have to use xauth...
311 // This example is one-shot because ssh can handle only one channel
312 xterm1$ socat -d -d \
313         EXEC:"ssh www.dest-unreach.org rm -f /tmp/.X11-unix/X9; ~/bin/socat -d -d unix-l\:/tmp/.X11-unix/X9\,fork -" \
314         UNIX:/tmp/.X11-unix/X0
315 xterm2$ ssh target
316 target$ DISPLAY=:9 myxapplication
318 // Touch with perms:
319 // no race condition for perms (applied with creat() call)
320 $ socat -u \
321         /dev/null \
322         CREAT:/tmp/tempfile,perm=0600
324 // Touch with owner and perms:
325 // race condition before changing owner, but who cares - only root may access
326 # socat -u \
327         /dev/null \
328         CREAT:/tmp/tempfile,user=user1,perm=0600
330 // Invoke an interactive ssh with EXEC
331 // First example passes control chars (^C etc.) to remote server as usual
332 socat \
333         -,echo=0,raw \
334         EXEC:'ssh server',pty,setsid,ctty
335 // Second example interprets control chars on local command line
336 socat \
337         -,echo=0,icanon=0 \
338         EXEC:'ssh server',pty,setsid,ctty
339 // afterwards, type "reset"!
341 // Convince ssh to provide an "interactive" shell to your script
342 // three main versions for entering password:
343 // 1) from your TTY; have 10 seconds to enter password:
344 (sleep 10; echo "ls"; sleep 1) |socat - EXEC:'ssh server',pty
345 // 2) from XWindows (DISPLAY !); again 10 seconds
346 (sleep 10; echo "ls"; sleep 1) |socat - EXEC:'ssh server',pty,setsid
347 // 3) from script
348 (sleep 5; echo PASSWORD; echo ls; sleep 1) |./socat - EXEC:'ssh server',pty,setsid,ctty
351 // Download with proxy CONNECT
352 // use echo -e if required for \n
353 $ (echo -e "CONNECT 128.129.130.131:80 HTTP/1.0\n"; sleep 5; echo -e "GET /download/file HTTP/1.0\n"; sleep 10) |
354 socat -d -d -t 3600 - tcp:proxy:8080,crlf
356 // Retrieve a file from an sshd site with sourceforge style entry menu; 
357 // fill in your personal values; cat lets you enter your password (will be
358 // visible on screen)
359 $ (sleep 10; read pass; echo $pass; sleep 10; echo M; sleep 5; echo cat FILENAME; sleep 10) |
360 ./socat -d -d -ly - EXEC:'ssh -c 3des -l USER cf.sourceforge.net',pty,setsid,ctty |
361 tee FILENAME
363 // Multicast community on local network: start the following command on all
364 // participating hosts; like a conference call:
365 # socat -d -d -d -d  - \
366         UDP-DATAGRAM:224.0.0.2:6666,bind=:6666,ip-add-membership=224.0.0.2:eth0,bindtodevice=eth0
367 // or
368 $ socat -d -d -d -d  - \
369         UDP-DATAGRAM:224.0.0.2:6666,bind=:6666,ip-add-membership=224.0.0.2:eth0
370 // Possible reasons for failure:
371 // iptables or other filters (open your filters as required)
372 // Packets leave via wrong interface (set route: ...)
373 // Socket bound to specific address
375 //=============================================================================
376 // GENERIC FUNCTION CALLS
378 // ioctl(): open CD drive (given value valid on Linux)
379 // on my Linux system I find in /usr/include/linux/cdrom.h the define:
380 // #define CDROMEJECT           0x5309 /* Ejects the cdrom media */
381 // The following command makes something like ioctl(fd, CDROMEJECT, NULL)
382 // (don't care about the read error):
383 $ socat /dev/cdrom,o-nonblock,ioctl-void=0x5309 -
385 // setsockopt(): SO_REUSEADDR
386 // The following command performs - beyond lots of overhead - something like:
387 // myint=1; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &myint, sizeof(myint))
388 $ socat -u UDP-RECV:7777,setsockopt-int=1:2:1 -
389 // setsockopt(): SO_BINDTODEVICE
391 // Ways to apply SO_BINDTODEVICE without using the special socat address option
392 // so-bindtodevice:
393 // with string argument:
394 $ sudo socat TCP-L:7777,setsockopt-string=1:25:eth0 PIPE
395 // with binary argument:
396 $ sudo socat TCP-L:7777,setsockopt-bin=1:25:x6574683000 PIPE
398 ===============================================================================
400 // Not tested, just ideas, or have problems
403 // Traverse firewall for making internal telnet server accessible for outside
404 // telnet client, when only outbound traffic (syn-filter) is allowed:
405 //   on external client run "double server". this process waits for a
406 // connection from localhost on port 10023, and, when it is established, waits
407 // for a connection from anywhere to port 20023:
408 ext$ socat -d \
409         TCP-LISTEN:10023,range=localhost \
410         TCP-LISTEN:20023
411 //   on internal server run double client:
412 int$ socat -d \
413         TCP:localhost:23 \
414         TCP:extclient:10023
415 //   or, with socks firewall:
416 int$ socat -d \
417         TCP:localhost:23 \
418         SOCKS:socksserver:extclient:10023
419 //   login with:
420 ext$ telnet localhost 20023
422 // YOU can make a double server capable of handling multiple instances:
423 ext$ socat -d \
424         TCP-LISTEN:10023,range=localhost,fork \
425         TCP-LISTEN:20023,reuseaddr
427 // Access remote display via ssh, when ssh port forwarding is disabled
428 $ socat -d -d \
429         EXEC:"ssh target socat - UNIX:/tmp/.X11-unix/X0" \
430         TCP-LISTEN:6030
431 $ xclock -display localhost:30
433 // Relay multiple webserver addresses through your firewall into your DMZ:
434 // Make IP aliases on your firewall, and then:
435 # socat -d -d \
436         TCP-L:80,bind=fw-addr1,fork \
437         TCP:dmz-www1:80
438 # socat -d -d \
439         TCP-L:80,bind=fw-addr2,fork \
440         TCP:dmz-www2:80
441 // and for improved security:
442 # socat -d -d \
443         TCP-L:80,bind=fw-addr3,su=nobody,fork \
444         TCP:dmz-www3:80
446 // Proxy an arbitrary IP protocol over your firewall (answers won't work)
447 # socat -d -d \
448         IP:0.0.0.0:150,bind=fwnonsec \
449         IP:sec-host:150,bind=fwsec
451 // Proxy an unsupported IP protocol over your firewall, point to point
452 // end points see firewall interfaces as IP peers!
453 # socat -d -d \
454         IP:nonsec-host:150,bind=fwnonsec \
455         IP:sec-host:150,bind=fwsec
456 // note that, for IPsec, you might face problems that are known with NAT