Even if you are an experienced.nix guru there are a couple of examples further down that are only available in later versions of. Take a look at.
First The Basics Breaking down the SSH Command LineThe following ssh example command uses common parameters often seen when connecting to a remote SSH server. Localhost:$ ssh -v -p 22 -C neo@ remoteserver-v: Print debug information, particularly helpful when debugging an authentication problem. Can be used multiple times to print additional information.-p 22: Specify which port to connect to on the remote SSH server. 22 is not required as this is the default, but if any other port is listening connect to it using the -p parameter.
The listening port is configured in the sshdconfig file using the Port 2222 format.-C: Compression is enabled on the connection using this parameter. If you are using the terminal over a slow link or viewing lots of text this can speed up the connection as it will compress the data transferred on the fly.neo@: The string before the @ symbol denotes the username to authenticate with against the remote server. Leaving out the user@ will default to using the username of the account you are currently logged in to ($ whoami). User can also be specified with the -l parameter.remoteserver: The hostname ssh is connecting to, this can be a fully qualified domain name, an IP address or any host in your local machines hosts file. To connect to a host that resolves to both IPv4 and IPv6 you can specify parameter -4 or -6 to the command line so it resolves correctly.Apart from remoteserver, each of the above parameters is optional.
Using a Configuration FileWhile many users are familiar with the sshdconfig file, there is also a client configuration file for the ssh command. This defaults to /.ssh/config but can also be specified as a parameter with the -F option. Host remoteserverHostName remoteserver.thematrix.ioUser neoPort 2112IdentityFile /home/test/.ssh/remoteserver.privatekeyHost.Port 2222In the above example ssh configuration file you can see two Host entries.
The first is a specific host entry with Port 2112 configured, as well as a custom IdentifyFile and username. The second is a wildcard value of. that will match all hosts. Note that the first configuration option found will be used, so the most specific should be at the top of the configuration.
More information is found in the man page ( man sshconfig).The configuration file can save a lot of typing by including advanced configuration shortcuts any time a connection is made to particular hosts. Copy Files over SSH with SCPThe ssh client comes with two other very handy tools for moving files around over an encrypted ssh connection. The commands are scp and sftp. See examples below for basic usage.
Note that many parameters for the ssh can be applied to these commands also. Localhost:$ scp mypic.png neo@ remoteserver:/media/data/mypic2.pngIn this example, the file mypic.png was copied to the remoteserver to file system location /media/data and renamed to mypic2.png.Don't forget the difference in the port parameter. This is a gotcha that hits everyone using scp on the command line.
The port parameter is -P not -p as it is in the ssh client.! You will forget, but don't worry everyone does.For those familiar with command line ftp, many of the commands are similar when using sftp. You can push, put and ls to your hearts desire.
Sftp neo@ remoteserver Practical ExamplesIn many of these examples, we could achieve the result using several methods. As in all our and example command sheets, the focus is practical examples that get the job done.1. Proxy Traffic over SSH using SOCKSThe SSH Proxy feature has been placed at number 1 for good reason. It is more powerful than many users realise giving you access to any system that the remote server can reach, using almost any application. The ssh client can tunnel traffic over the connection using a SOCKS proxy server with a quick one liner. A key thing to understand is that traffic to the remote systems will have a source of the remote server. For example in a web server log file.
Localhost:$ ssh -D 8888 user@remoteserverlocalhost:$ netstat -pan grep 8888tcp 0 0 127.0.0.1:8888 0.0.0.0:. LISTEN 23880/sshHere we start the socks proxy server running on TCP port 8888, the second command checks that the port is now listening. The 127.0.0.1 indicates the service is running on localhost only. We can use a slightly different command to listen on all interfaces including ethernet or wifi, this will allow other applications (browsers or other) on our network to connect to the ssh socks proxy service.
Localhost:$ ssh -D 0.0.0.0:8888 user@remoteserverNow we can configure our browser to connect to the socks proxy. In Firefox select preferences general network settings. Add the IP address and the port for the browser to connect to.Note the option at the bottom of the form to force browser DNS requests to also go over the socks proxy. If you are using the proxy to encrypt your web traffic on the local network you will definitely want to select this option so the DNS requests are also tunnelled over the SSH connection.
Enable Socks Proxy on ChromeUsing a command line parameter when launching Chrome will use the socks proxy and also tunnel DNS requests from the browser over the socks5 proxy. Trust but verify, use (tcpdump not port 22) to confirm the DNS requests are no longer visible. Localhost:$ google-chrome -proxy-server='socks5://192.168.1.10:8888' Using other applications with the ProxyKeep in mind that there are many other applications that can utilise a socks proxy. A web browser is simply the most popular. Some applications will have configuration options for use of the proxy. Others may need some help by using a helper program that talks the socks protocol. An example of this is.
Using this tool we can for example use Microsoft RDP over the socks proxy. Localhost:$ proxychains rdesktop $RemoteWindowsServerThe configuration options for the socks proxy are set in the proxychains configuration file. Hot Tip: Using remote desktop from Linux to Windows? Try the client.
A more modern implementation than rdesktop with much smoother interaction. Use Case for the SSH Socks ProxyYou are in a cafe or hotel having to use the somewhat sketchy WIFI. From our Laptop we run the ssh proxy locally and establish an ssh tunnel into our home network using a our local Rasberry Pi. Using the browser or other applications configured for the SOCKS proxy we can access any network services on our home network or browse to the Internet via our Home Network Connection. Everything between our Laptop and the Home Server (across the WIFI and Internet to home) is encrypted in the SSH tunnel.2.
SSH Tunnel (port forward)In its simplest form an SSH tunnel opens a port on your local system that connects through to another port at the other end of the tunnel. Localhost:$ ssh -L 9999: 127.0.0.1:80 user@remoteserverLets break down the -L parameter. Think of -L as the Local listening side. So in our example above the port 9999 is listening on localhost and port forwards through to port 80 on remoteserver, note that the 127.0.0.1 refers to localhost on the remote server!Lets take it up a notch. In this following example the port that is listening can be connected to from other hosts on the local network.
Localhost:$ ssh -L 0.0.0.0:9999:127.0.0.1:80 user@remoteserverIn these examples the port we are connecting is a listening web server. It could also be a proxy server or any other TCP service.3. SSH Tunnel Forward to Secondary Remote hostWe can use the same options seen above to have the tunnel connect to another service running on a secondary system from the remote server. Localhost:$ ssh -L 0.0.0.0:9999:10.10.10.10:80 user@remoteserverIn this example we are forwarding the tunnel from remoteserver to the web server running on 10.10.10.10.
The traffic from remoteserver - 10.10.10.10 is no longer within the ssh tunnel. The web server on 10.10.10.10 will see remoteserver as the source of the web requests.4. SSH Reverse TunnelIn this scenario we want to setup a listening port on the remote server that will connect back to a local port on our localhost (or other system). Localhost:$ ssh -v -R 0.0.0.0:1999:127.0.0.1:902 192.168.1.100 user@remoteserverWith this ssh session established a connection to the remoteserver port 1999 will be forwarded to port 902 on our local client.5. SSH Reverse ProxyIn this case we are establishing a SOCKS proxy with our ssh connection, however the proxy is listening at the remote server end. With connections to that remote socks proxy now emerging from the tunnel as traffic originating from our localhost. Requires OpenSSH version 7.6+.
Localhost:$ ssh -v -R 0.0.0.0:1999 192.168.1.100 user@remoteserver Troubleshooting Remote SSH TunnelsIf you are having trouble getting the remote SSH options to work, check with netstat which interface the listening port is attached too. Even though we have specified 0.0.0.0 in the above examples, if GatewayPorts is set to no in the sshdconfig then the listener will only bind to localhost (127.0.0.1).
Security WarningNote that when you are opening tunnels and socks proxies you may be exposing internal network resources to untrusted networks (like the Internet!). This can be a serious security risk so ensure you understand what is listening and what it has access too.6. Establish a VPN over SSHA common term amongst offensive security folks (pentesters / red teams / etc), is to pivot into a network. Once you have a connection established on one system that system becomes a gateway point for further access to the network. This is known as pivoting and enables lateral movement through the network.We can use the SSH proxy for this and proxychains, however there are some limitations. For example we cannot use raw sockets, so SYN scans cannot be used to port scan the Internal network.Using this more advanced VPN option we move the connectivity down to layer 3. We can then route traffic through the tunnel using standard network routing.This technique uses ssh, iptables, tun interfaces and routing.First we need these options set in the sshdconfig.
Since we are making interface changes on the remote system and the client system, we will need root privileges on both sides. PermitRootLogin yesPermitTunnel yesThen we will establish our ssh connection using the parameter that requests tun devices be initialised. Localhost:# ssh -v -w any root@remoteserverNow you should have a tun device when you show interfaces ( # ip a). Next step is to add IP addresses to the tunnel interfaces.SSH Client Side: localhost:# ip addr add 10.10.10.2/32 peer 10.10.10.10 dev tun0localhost:# ip tun0 upSSH Server Side: remoteserver:# ip addr add 10.10.10.10/32 peer 10.10.10.2 dev tun0remoteserver:# ip tun0 upNow we should have a direct route to the other host ( route -n and ping 10.10.10.10).It is now possible to route any subnet through the other side host.
Localhost:# route add -net 10.10.10.0 netmask 255.255.255.0 dev tun0On the remote side we need to enable ipforward and iptables. Remoteserver:# echo 1 /proc/sys/net/ipv4/ipforwardremoteserver:# iptables -t nat -A POSTROUTING -s 10.10.10.2 -o enp7s0 -j MASQUERADEBoom! Layer three VPN through an SSH tunnel. Now that's winning.Any trouble, try and ping to see where its broken. Since we are playing at layer 3 our icmp packets should be jumping through that tunnel.7. Copy your SSH key (ssh-copy-id)There are multiple ways to achieve this however this command is a shortcut that saves time.
What does it actually do? This command replicates what you can also do manually. Copying the /.ssh/idrsa.pub (or the default) key from your system and adds it to an /.ssh/authorizedkeys file on the remote server. Localhost:$ ssh-copy-id user@remoteserver8. Run Command Remotely (non-interactive)The ssh command can be chained to other commands for the usual piping fun.
Add the command you want to run on the remote host as a final parameter in quotes. Localhost:$ ssh remoteserver 'cat /var/log/nginx/access.log' grep badstuff.phpIn this example the grep is being performed on the local system after the log file has been pushed across the ssh session.
If the file is large it would be more efficient to run the grep on the remote side by enclosing the pipe and grep in the double quotes.Another example performs the same function as the ssh-copy-id short cut in Tip 7. Localhost:$ cat /.ssh/idrsa.pub ssh remoteserver 'cat.ssh/authorizedkeys'9. Remote Packet Capture & View in WiresharkI grabbed this one from our. Use it for a remote packet capture with the results feeding directly into your local Wireshark GUI.:$ ssh root@remoteserver 'tcpdump -c 1000 -nn -w - not port 22' wireshark -k -i -10. SSH Copy Folder from Local to RemoteA neat trick that compresses a folder using bzip2 (that's the -j in the tar command), then extracts the bzip2 stream on the other side creating a duplicate of the folder on the remote server. Localhost:$ tar -cvj /datafolder ssh remoteserver 'tar -xj -C /datafolder'Copy remote folder to local tar archiveTo go the other way, copying a remote folder to a local archive.
Handy for quick backups of remote resources. Localhost:$ ssh user@remoteserver 'tar -jcf - /path/to/backup' dir.tar.bz211.
Remote GUI Applications with SSH x11 ForwardingIf the client and remote server both have X installed. It is possible to run a GUI command remotely, with the Window appearing on your local desktop. This feature has been around since the beginning of time, but can still be very useful. Run a remote web browser or even the VMWawre Workstation console as I do in this example. Localhost:$ ssh -X remoteserver vmwareRequires X11Forwarding yes in the sshdconfig.12.
Copy files remotely with rsync and SSHUsing the rsync has many advantages over scp, if periodically need to backup a directory, large numbers of files or very large files it should be used. It has the ability to recover from failed transfers and only copy differences between two locations saving bandwidth and time.The example here uses gzip compression (-z) and archive mode (-a) that includes recursive copy.:$ rsync -az /home/testuser/data remoteserver:backup/13.
SSH over Tor NetworkThe anonymised Tor Network can tunnel SSH traffic by using the torsocks command. The following command will proxy the ssh connection through the Tor network. Localhost:$ torsocks ssh myuntracableuser@remoteserverwill use the localhost port 9050 to proxy traffic. As always when using tor serious consideration must be taken to understand what traffic is being tunnelled and other operational security (opsec) concerns. Where are your DNS requests going?14. SSH to EC2 instanceWhen using SSH to connect to your EC2 instance within Amazon you will need to use a private key.
Download the key (extension.pem) from your Amazon EC2 control panel and change the permissions ( chmod 400 my-ec2-ssh-key.pem. Keep this key somewhere safe or put it in your /.ssh/ folder.
Localhost:$ ssh -i /.ssh/my-ec2-key.pem ubuntu@my-ec2-publicThe -i parameter tells the ssh client to use this key. This would be an ideal example of where to use the /.ssh/config to configure the use of the key automatically when connecting to the ec2 host. Host my-ec2-publicHostname ec2???compute-1.amazonaws.comUser ubuntuIdentityFile /.ssh/my-ec2-key.pem15.
Edit text files with VIM over ssh/scpFor all those vim users out there, this one can save some time. Using vim we can edit files over scp with one command. Using this method creates a file in /tmp on the local system and then copies it back once we write the file in vim. Localhost:$ vim scp://user@remoteserver//etc/hostsNote the format is slightly different to regular scp. After the host we have a double //. This references the absolute path.
A single slash will have a path that is relative to the users home directory.warning. (netrw) cannot determine method (format: protocol://user@hostname:port/path)If you see this error, double check the format of your command. It usually means there is a syntax error.16. Mount remote SSH location as local folder with SSHFSUsing sshfs - an ssh filesystem client, we can mount a local directory to a remote location with all file interaction taking place over the encrypted ssh session. Localhost:$ apt install sshfsOn Ubuntu and Debian based system we install the sshfs package and then mount the remote location. Localhost:$ sshfs user@remoteserver:/media/data /data/17. SSH Multiplex using ControlPathBy default when you have an existing connection to a remote server with ssh, a second connection using ssh or scp will establish a new session with the overhead of authentication.
Using the ControlPath options we can have the existing session be used for all subsequent connections. This will speed things up significantly. It is noticeable even on a local network but even more so when connecting to remote resources.
Host remoteserverHostName remoteserver.example.orgControlMaster autoControlPath /.ssh/control/%r@%h:%pControlPersist 10mControlPath denotes a socket that is checked by new connections to see if there is an existing ssh session that can be used. The ControlPersist option above means even after you exit the terminal, the existing session will remain open for 10 minutes, so if you were to reconnect within that time you would use that existing socket.
See the sshconfig man page for more information.18. Stream Video over SSH using VLC + SFTPLong time users of ssh and vlc (Video Lan Client) are not always of aware of this handy option for when you need to watch video over the network. Using the vlc option to File Open Network Stream one can enter the location as a an sftp:// location. A prompt will appear for authentication details if password is required. Two Factor AuthenticationMost readers will understand the value in using Two Factor Authentication, the same benefits that apply to your banking or Google Account can be applied to your SSH service.Of course ssh comes with a form of Two Factor capability included, that being a passphrase and an SSH key.
An advantage of using a hardware based token or the is the fact that they are generally coming from a second physical device.See our 8 minute guide to getting started with.20. Bouncing through jump hosts with ssh and -JWhen network segmentation means you are jumping through multiple ssh hosts to get to a final destination network or host, this jump host shortcut might be just what you need. Requires OpenSSH version 7.3+.
Localhost:$ ssh -J host1,host2,host3 user@host4.internalA key thing to understand here is that this is not the same as ssh host1 then user@host1:$ ssh host2, the -J jump parameter uses forwarding trickery so that the localhost is establishing the session with the next host in the chain. So our localhost is authenticating with host4 in the above example; meaning our localhost keys are used and the session from localhost to host4 is encrypted end to end.To use this ability in the sshconfig use the ProxyJump configuration option. If you regularly have to jump through multiple hosts; use the config file and your alias to host4 will save you a lot of time.21.
Block SSH Brute Force Attempts with iptablesAnyone who has managed an SSH service on the Internet, and viewed the logs will be aware of the amount of SSH brute force attempts that take place every hour of every day. An immediate way to reduce the noise in your logs is to move SSH to a port other than 22. Make the change in the sshdconfig file using the Port ## configuration option.Using iptables we can also block attempts to connect to the port from sources that reach a certain threshold. A way to do this is to use, as this not only blocks SSH but will also perform a bunch of other host based intrusion detection functions (HIDS).22. Modify Port Forwarding within a session with CAnd our final ssh example is for modifying port forwarding on the fly within an existing ssh session. Picture this example scenario.
You are deep in a network; perhaps you have jumped through half a dozen jump hosts and need a local port on your workstation forwarded to Microsoft SMB on the old Windows 2003 system you spotted (ms08-67 anyone?).After hitting enter try typing C in your terminal. This a control escape sequence within the session that allows to make changes to the existing connection. Localhost:$ Cssh -hCommands:-Lbindaddress:port:host:hostport Request local forward-Rbindaddress:port:host:hostport Request remote forward-Dbindaddress:port Request dynamic forward-KLbindaddress:port Cancel local forward-KRbindaddress:port Cancel remote forward-KDbindaddress:port Cancel dynamic forwardssh -L 1445:remote-win2k3:445Forwarding port.You can see here we have forwarded our local port 1445 to the Windows 2003 host we found on the internal network. Now launch msfconsole and we are good to go (assuming you were planning on exploiting that host).
Wrapping UpThese ssh examples, tips and commands are intended to give you a starting point; additional detail on each of the commands and capabilities is available using the man pages ( man ssh, man sshconfig, man sshdconfig).Being able to reach out and run commands on systems anywhere in the world has always fascinated me. By developing your skills with tools such as ssh you will become more productive and effective at whatever game you play.Thanks for reading and if you have any comments or suggestions please drop me a note using the contact form.
When You’ll Want to Use Reverse SSH TunnelingSometimes, remote computers can be hard to reach. The site they are located at may have tight firewall rules in place, or perhaps the local admin has set up complex rules. How do you reach such a computer if you need to connect to it?Let’s establish some labels. Your computer is the local computer because it is near you. The computer you are going to connect to is the remote computer because it is in a different location than you.To differentiate between the local and remote computers used in this article, the remote computer is called “howtogeek” and is running Ubuntu Linux (with purple terminal windows). The local computer is called “Sulaco” and is running Manjaro Linux (with yellow terminal windows).Normally you’d fire up an from the local computer and connect to the remote computer. That isn’t an option in the networking scenario we’re describing. It really doesn’t matter what the specific network issue is—this is useful whenever you can’t SSH straight to a remote computer.But if the networking configuration on your end is straightforward, the remote computer can connect to you.
That alone isn’t sufficient for your needs, however, because it doesn’t provide you with a working command-line session on the remote computer. But it is a start. You have an established connection between the two computers.The answer lies in reverse SSH tunneling. What Is Reverse SSH Tunneling?Reverse SSH tunneling allows you to use that established connection to set up a new connection from your local computer back to the remote computer.Because the original connection came from the remote computer to you, using it to go in the other direction is using it “in reverse.” And because SSH is secure, you’re putting a secure connection inside an existing secure connection. This means your connection to the remote computer acts as a private tunnel inside the original connection.And so we arrive at the name “reverse SSH tunneling.” How Does It Work?Reverse SSH tunneling relies on the remote computer using the established connection to listen for new connection requests from the local computer.The remote computer listens on a network port on the local computer. If it detects an SSH request to that port, it relays that connection request back to itself, down the established connection.
This provides a new connection from the local computer to the remote computer.It’s easier to set up than it is to describe. Using SSH Reverse TunnelingSSH will already be installed on your Linux computer, but you may need to start the SSH daemon (sshd) if the local computer has never accepted SSH connections before. Sudo systemctl start sshdTo have the SSH daemon start each time you reboot your computer, use this command: sudo systemctl enable sshdOn the remote computer, we use the following command. The -R (reverse) option tells ssh that new SSH sessions must be created on the remote computer. The “43022:localhost:22” tells ssh that connection requests to port 43022 on the local computer should be forwarded to port 22 on the remote computer. Port 43022 was chosen because it is. It isn’t a special number.
dave@sulaco.local is the user account the remote computer is going to connect to on the local computer.ssh -R 43022:localhost:22 dave@sulaco.localYou may get a warning about having never connected to the local computer before. Or you may see a warning as the connection details are added to the list of recognized SSH hosts. What you see—if anything—depends on whether connections have ever been made from the remote computer to the local computer.You will be prompted for the password of the account you are using to connect to the local computer.Note that when the connection has been made the command prompt changes from dave@howtogeek to dave@sulaco.We’re now connected to the local computer from the remote computer. That means we can issue commands to it. Let’s use the who command to see the logins on the local computer. WhoWe can see that the person with the user account called dave has logged in to the local computer, and the remote computer has connected (using the same user credentials) from IP address 192.168.4.25.RELATED: Connecting to the Remote ComputerBecause the connection from the remote computer is successful, and it is listening for connections, we can try to connect to the remote computer from the local one.The remote computer is listening on port 43022 on the local computer. So—somewhat counter-intuitively—to make a connection to the remote computer, we ask ssh to make a connection the local computer, on port 43022. That connection request will be forward to the remote computer.
Ssh localhost -p 43022We are prompted for the user account password, then connected to the remote computer from the local computer. Our Manjaro computer happily says, “Welcome to Ubuntu 18.04.2 LTS”.Note that the command prompt has changed from dave@sulaco to dave@howtogeek. We’ve achieved our goal of making an SSH connection to our hard-to-reach remote computer. Using SSH With KeysTo make it more convenient to connect from the remote computer to the local computer, we can set up SSH keys.On the remote computer, type this command: ssh-keygenYou will be prompted for a passphrase. You can press Enter to ignore the passphrase questions, but this is not recommended.
It would mean that anyone on the remote computer could make an SSH connection to your local computer without being challenged for a password.Three or four words separated by symbols will make a robust passphrase.Your SSH keys will be generated.We need to transfer the public key to the local computer.