Simple introduction to SSH tunnel construction

Source: Internet
Author: User
Tags vps free ssh openssh server ssh access ssh port ssh server
I've heard of this technology, and I'm interested in it.

I want to visit my machine in the company at home (write programs, check data, next movie).

Company in order to prevent us with the XX software blocked its port or server address.

Companies do not let us on the XX website, limited the URL or even IP.

Companies do not let us see the information about XX, and even spend the money to buy XX equipment, to filter the content. A look at the contents of XX, the link is interrupted.

My father is a computer, he is in the home router on the hands and feet, I can not see XXX.

With these questions, let's start with what is the SSH tunnel.

What is an SSH tunnel

Our computer is in the upper-right corner, connected to the Internet via the company's firewall-enabled router (and of course, there are switches that connect you and the router in the middle, but the switch does not play a critical role in our problem). The bottom right part is a Web site server, which is part of our corporate firewall policy, which means that the company does not want us to access this server. There is also a machine in the upper right corner and it belongs to us. But this machine is not in our company, in other words, he is not limited by the company's firewall. Last but not least, we are able to access the machine directly through the Internet in the company. Or the machine outside the company's firewall needs to have a separate Internet IP, and the company's firewall rules won't block the machine, and the machine is running a openssh server.

Now, we know exactly where we are in the Internet environment. And it's not hard to understand why we can't access that server in the company because a firewall between a-B on line a-b-c is blocking access to that server. At the same time, we quickly noticed that there was no obstruction between the lines a-b-d and d-c. Believe you have thought that the firewall between a-B does not block access to machine D. So we can create a channel a-b-d-c through machine D to access the data on machine C.

This channel can be built with a lot of technology, here we just show how to use the SSH server to establish such a channel-he is called SSH tunnel.

How to establish a local SSH tunnel

Before we plan to build a local SSH tunnel, we must be aware of the following data:

IP address of intermediate server D

To access the IP address of server C

To access the port of server C

Requires access to the 234.234.234.234 FTP service, which is port 21

Intermediate server is 123.123.123.123

Now we use the following command to achieve our purpose.

Ssh-n-f-l 2121:234.234.234.234:21 123.123.123.123

FTP localhost:2121 # now accesses the local 2121 port to connect to the 234.234.234.234 21 port.

Here we use the SSH client's three parameters, the following we explain each:

-N tells the SSH client that this connection does not need to execute any commands. Just do port forwarding

-F tells the SSH client to run in the background

-l do local map port, three parts separated by colon mean

The local port number to use

IP address of the target machine to be accessed (ip:234.234.234.234)

Target Machine Port (port: 21) to be accessed

The last parameter is the IP address of the intermediary machine we used to build the tunnel (ip:123.123.123.123)

Let's repeat the behavior of the-l parameter. The meaning of-l x:y:z is that the z port of the machine with IP Y is mapped to the X port of the local machine through an intermediary server.

After this command was successfully executed, we had the ability to bypass the corporate firewall and successfully accessed one of our favorite FTP servers.

How to set up a remote SSH tunnel

By establishing the local SSH tunnel, we successfully bypassed the firewall to start downloading resources on the FTP. So what if we want to see the download progress when we're at home? Most corporate networks are connected to the Internet via routers, and the company's internal machines do not directly connect to the Internet, which is not directly accessible via the Internet. It is impossible to access machine A in the company through the line d-b-a. Perhaps you have noticed that although the d-b-a is not connected in this direction, there is no problem with the connection in this direction a-b-d. So, can we use an already connected a-b-d direction of connection to complete the d-b-a direction of access? The answer is yes, this is the purpose of the remote SSH tunnel.

As with local ssh, we need to understand the following parameters before establishing a remote SSH tunnel:

The IP address of the remote machine that requires access to the internal machine (this is 123.123.123.123)

The IP address of the internal machine that needs to be accessible to the remote machine (this is because it wants to map this machine, so the IP is 127.0.0.1)

The port number of the internal machine that needs to be accessible to the remote machine (port: 22)

After the above parameters are clear, we use the following command to establish a remote SSH tunnel

Ssh-n-f-r 2222:127.0.0.1:22 123.123.123.123

Now, on the machine where IP is 123.123.123.123, we can log in with the following command to the company's IP is 192.168.0.100 machine.

Ssh-p 2222 localhost

-n,-f These two parameters we have already introduced in the local SSH tunnel. Now we're going to focus on parameter-R. The meanings of the three parts of this parameter are:

Ports Used by remote machines (2222)

IP address of the internal machine that needs to be mapped (127.0.0.1)

Ports for internal machines that need to be mapped (22)

For example, the-R x:y:z maps the Z-port of our internal Y machine to the X port on the remote machine.

Some tips for building an SSH tunnel

Automatic re-connect

The tunnel may be disconnected for some reason, for example, a machine restart, a long time without data communication and a router cut off, and so on. So we can program the reconnection of the tunnel, for example a simple loop or use DJB's daemontools. In either case, you should avoid a program that is stuck with a password when you re-connect. For a safe way to avoid entering your password, refer to my how to implement secure password-free SSH login. Note here that if you control the tunnel connection through other programs, you should avoid putting the SSH client in the background, that is, removing the-f parameter.

Stay connected for long periods of time

Some routers disconnect a connection that is not communicating for a long time. The SSH client's tcpkeepalive option avoids this problem, which is turned on by default. If it is closed, you can add-o tcpkeepalive=yes to the command on SSH to open it.

Another way is to remove the-n parameter and add a regular command that produces the output. For example: Top or Vmstat. An example of this approach is given below:

Ssh-r 2222:localhost:22 123.123.123.123 "Vmstat 30"

Check tunnel status

Sometimes the tunnel is jammed for some reason, for example: the router is brought into the stalled state due to the large amount of data transmitted. This time, often the SSH client does not quit, but the card dies there. One workaround is to use the Serveraliveinterval and Serveralivecountmax options of the SSH client. Serveraliveinterval will send a request to the server to request a server response after a set time after the tunnel has no communication. If the server does not respond after a Serveralivecountmax request, the SSH client automatically disconnects and exits, handing control over to your monitoring program. The two options are set by adding-O serveraliveinterval=n and-o serveralivecountmax=m at SSH. where n, m can be defined by itself.

How to bind a port to an external address

Using the method above, the mapped port can only be bound on the 127.0.0.1 interface. In other words, it can only be accessed by the local machine itself. How can I get other machines to access this port? We can bind this mapped port on the 0.0.0.0 interface by adding the parameter-B 0.0.0.0. You also need to open an option-gatewayports on the SSH server side. By default, it should be open. If it is closed, you can change gatewayports No to gatewayports Yes in/etc/sshd_config to open it.

How to find an intermediary server

If you use ADSL at home, most of you will be lucky. General ADSL (for example, Unicom ADSL) has an Internet address. You only need to map out an SSH port on your home router that has a OPENSSH server machine installed. At the same time, some virtual hosts that provide SSH access can also be used for this purpose. For example: Hostmonser or Dreamhost.

Establishing a SOCKS server via SSH tunneling

If we need to access a lot of resources with an intermediary server, mapping is obviously not a smart approach (in fact, gaoming does not use this method). Fortunately, the SSH client provides us with the ability to establish a SOCKS server through an SSH tunnel.

We can build a socks server through 123.123.123.123 by the following command.

Ssh-n-f-d 1080 123.123.123 # binds the port on the 127.0.0.1

Ssh-n-f-d 0.0.0.0:1080 123.123.123.123 # bind ports on 0.0.0.0

The SOCKS server established via SSH is using the SOCKS5 protocol, which should be paid special attention when setting up the socks agent for the application.

SSH command

One, man ssh

See what options SSH commands have.
Because it's too long, this only shows the relevant options

> Man ssh-d [bind_address:]port specifies a local ' dynamic ' application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the speci-fied bin  D_address. Whenever a connection is made to this port, the connection are forwarded over the secure channel, and the application proto  Col is then used to determine where to connect to from the remote machine.  Currently the SOCKS4 and SOCKS5 protocols are supported, and SSH would act as a SOCKS server.  Only Root can forward privileged ports.             Dynamic Port forwardings can also is specified in the configuration file.  IPV6 addresses can be specified by enclosing the address in square brackets.  Only the superuser can forward privileged ports.  By default, the local port was bound in accordance with the Gatewayports setting. However, an explicit bind_address is used to bind the connection to a specificAddress. The bind_address of ' localhost ' indicates that the listening port is bound for local use only, while an empt     Y address or ' * ' indicates that the port should is available from all inter-faces.  -F requests SSH to go to background just before command execution.   This is useful if SSH are going to ask for passwords or passphrases, and the user wants it in the back-ground.  This implies-n.             The recommended-to-start X11 programs at a remote site was with something like Ssh-f host xterm.  If The exitonforwardfailure configuration option is set to "yes", then a client started with-f'll wait for all remote     Port forwards to is successfully established before placing itself in the background. -L [Bind_address:]port:host:hostport specifies that the given port on the local (client) host are to be Forwar  Ded to the given host and port on the remote side. This works by AllocatinG A socket to listen to port in the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection are forwarded over the secure channel, and a Connect  Ion is made to host port Hostport from the remote machine.  Port Forwardings can also is specified in the configuration file.  IPV6 addresses can be specified by enclosing the address in square brackets.  Only the superuser can forward privileged ports.  By default, the local port was bound in accordance with the Gatewayports setting.  However, an explicit bind_address is used to bind the connection to a specific address. The bind_address of ' localhost ' indicates that the listening port is bound for local use only, while an empt     Y address or ' * ' indicates that the port should is available from all interfaces.  -N does not execute a remote command. This is useful-just forwarding ports (Protocol version 2 only). -R [Bind_address:]port:host:hostport specifies that the given port on the remote (server) host was to be Forwar  Ded to the given host and port on the local side. This works by allocating a socket to listen to port on the remote side, and whenever a conn             Ection is made to this port, the connection are forwarded over the secure channel, and a connection are made to host port             Hostport from the local machine.  Port Forwardings can also is specified in the configuration file.  Privileged ports can is forwarded only if logging in as root on the remote machine.             IPV6 addresses can be specified by enclosing the address in square brackets.  By default, the listening socket on the server is bound to the loopback interface only.  This is overridden by specifying a bind_address. An empty bind_address, or the address ' * ', indicates-the-remote socket should listen on all interfaceS. Specifying a remote bind_address would only succeed if the server's Gatewayports option is enabled (see SSH             D_config (5)).  If The port argument is ' 0 ', the listen port would be dynamically allocated on the server and reported to the client at run  Time. When used together with-o forward the allocated port would be printed to the standard OUTPU T.

Here is a list of the options used to simply introduce:

-d [listening address] The listening port   is used to connect the remote SSH to the local port to form SOCK4 or SOCK5 service, (students who use shadowsocks science should be familiar with the internet);-F let SSH service run into the background, Do outside forward proxy SSH command run in the background more worry;-l SSH will listen on the local port, all data operations on this port will penetrate to the corresponding configuration port of SSH remote address;-n do not execute remote command, it is useful when SSH is used as tunnel; SSH will listen to a port on the remote server and forward all the port data to the local settings port;

Diagram above configuration

-D penetrates remote access services to the local port and provides sock services; ▲PORT:SOCK5 │┌────┴────────┐┌─────────────┐│localhost│────port:22── ────│remote│└─────────────┘└─────────────┘-l a service that can be accessed remotely host+port through to the local, on the local port to provide                  Should pass through the service; ▲bindaddr:port▲servicehost:port││ ┌───┴─────────┐┌────┴────────┐│localhost│────port:22──────│remote│└──────    ───────┘└─────────────┘-r a service accessed by the function host+port penetrate to remote, on the remote machine designated port to provide the transmission service; ▲servicehost:port▲bindaddr:port││┌───┴── ───────┐┌────┴────────┐│localhost│────port:22──────│remote│└───────────── ┘└─────────────┘ 

For the sake of convenience, assume that you have the following resources

Vps:root@outside_vps outside the wall

Native: localhost

Second, through the outside of the wall ECS to provide SOCK5 science Internet

Command

Ssh-n-f-d Root@outside_vps

Enter the password, after execution, local 1080 port is monitored, provide sock5 service, use Chrome+switchyomega can configure science to surf the Internet, the effect and shadowsocks same.

Third, the local service penetrates to the external network 80 port

A local service listening 3003 port, here with Nodejs simple implementation:

S.jsrequire (' http '). Createserver (function (req, res) {  res.end (' xxx ');}). Listen (3003);> node s

SSH to the remote VPS, the remote VPS port monitoring is set as follows, allowing sshd to listen to the IP outside of localhost:

(Add-o gatewayports=yes effect in ssh parameters)

> vim/etc/ssh/sshd_config# gatewayports:no------changed into a  -----gatewayports:yes

Local boot

Ssh-f-n-r outside_vps:80:localhost:3003 Root@outside_vps

After launch, the browser input Outside_vps, directly access to the local 3003 service

Tips: Here can be the local HTTP service to the external network, the same can be the local 22 port transmission (cautious use of sub-function, so that the password is too weak or have a security vulnerability to give people an advantage)

Iv. Service agents

Scenario: When a can only access b,b can connect to C, a requires access to a service of C, and cannot have a access to other services of C.

At this point, the-l parameter comes in handy. We use the B host through the ssh-l, the C above the development of the service agent to a port of B let a use, at this time a can only access to the C Agent service, and access to the other services C;

To pass C's MySQL service through to B, for example:

Execute on B

Ssh-n-f-o gatewayports=yes-l *:3336:c:3306 root@c

Access on a

Mysql-hb-uuser-p3336-p

After entering the password, the same as accessing the C port!

Above the scene, in the network isolation, B as the exit machine may appear, of course, this proxy with Nginx TCP Proxy can also be easily implemented.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.