How To Create Socks (SSH Tunneling) As A Service By SSH Command On CentOS

by Unix on February 16, 2016

This guide will show you how to establish a secure connection for browsing the web through a tunnel between your computer and your server. With this method, you will set up a tunnel between your computer and your server. All your web traffic will be encrypted and forwarded from your server on to its final destination.

Socket Secure (SOCKS) is an Internet protocol that exchanges network packets between a client and server through a proxy server. SOCKS5 additionally provides authentication so only authorized users may access a server. Practically, a SOCKS server proxies TCP connections to an arbitrary IP address, and provides a means for UDP packets to be forwarded.

It works by launching a SOCKS proxy server on your computer using SSH. It will listen on a local port and your browser will connect to the web using that service.

Creating the SOCKS Server

The first step is to create the SOCKS server and establish a connection to your server with following command

# ssh -fNT -D <your_ip_server>:<define_socks_port> <user_name>@<your_ip_server>

Options
-f: go to background
-N: do not execute a remote program
-T: disable pseudo-tty allocation
-D: Define port forwarding and talks to the clients via SOCSK5 or SOCKS4 protocols

Running as a service

The first, Create a user called name “socks” and setup this account login to your server via SSH private key without password.

# useradd socks

To setup this account login your service via SSH private key, please read this article

The second, Login with socks and type the following command

# mkdir /opt/socks
# chown root.root -R /opt/socks
# chmod 700 /opt/socks
# touch /opt/socks/run.sh
# chmod +x /opt/socks/run.sh
# cp -R /home/socks/.ssh/id_rsa /opt/socks/

Append bellow content to /opt/socks/run.sh

#/bin/bash
IPS="1.1.1.1 2.2.2.2 3.3.3.3"
SOCKS_PORT=9999
SSH_PORT=22
SSH_USER=socks

# Auto get list IPs on your server
# IPS=`ifconfig | grep "inet a" | awk '{print $2}' | grep -v "127.0" | cut -d: -f2`

for IP in $IPS
do
        echo "Building socks $IP"
        ssh -D $IP:$SOCKS_PORT -fN -p $SSH_PORT  -i /opt/socks/id_rsa $SSH_USER@$IP
done

Leave a Comment

Previous post:

Next post: