Showing posts with label ssh. Show all posts
Showing posts with label ssh. Show all posts

Tuesday, April 10, 2012

SSH Keys Authentication With PuTTY

SkyHi @ Tuesday, April 10, 2012

5 Generate A Private/Public Key Pair

We can use PuTTYgen to create a private/public key pair. Start it by double-clicking its executable file. Make sure you select SSH-2 RSA underType of key to generate and specify 1024 as the Number of bits in a generated key. Then click on Generate:
Please move the mouse pointer over the blank area during the key generation to generate some randomness:
Now a private/public key pair has been generated. Under Key comment, you can enter any comment; normally you use your email address here. Then specify a Key passphrase and repeat it under Confirm passphrase. You'll need that passphrase to log in to SSH with your new key. Then click on Save publick key and save it in some safe location on your computer. You are free to choose a filename and extension, but it should be one that lets you remember for which system it is.
Then click on Save private key. You can save it in the same location as the public key - it should be a location that only you can access and that you don't lose! (If you lose the keys and have disabled username/password logins, then you can't log in anymore!) Again, you're free to choose a filename, but this time the extension must be .ppk:
Then copy the public key from the PuTTYgen window:

6 Save The Public Key On The Server

Then log in to your SSH server (if you have closed the previous SSH session already), still with the username and password, and paste the public key into the file ~/.ssh/authorized_keys2 (in one line!) like this:
mkdir ~/.ssh
chmod 700 ~/.ssh
vi ~/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EA[...]Lg5whU0zMuYE5IZu8ZudnP6ds= myname@example.com
That file must be write/readable only by that user, so we run
chmod 600 ~/.ssh/authorized_keys


7 Attach The Private Key To The PuTTY Profile

Now launch PuTTY again and load the profile of your SSH server (192.168.0.100):
Then go to SSH -> Auth and click on Browse:
Browse your file system and select your previously created private key:
Then go to Session again and click on Save:
Now we have attached the private key to our 192.168.0.100 PuTTY profile.

8 Our First Key-Based Login

Now everything is ready for our first key-based login to our SSH server. Click on Open:
As you can see, the public key is now used for authentication, and you are asked for the passphrase (the one you specified in chapter 5):

REFERENCES

Friday, February 10, 2012

CentOS SSH X11 Forwarding

SkyHi @ Friday, February 10, 2012
To setup SSH X11 forwarding on CentOS, we need to:
0. To install KDE Desktop, type this:
yum groupinstall "X Window System" "KDE (K Desktop Environment)"
To install Gnome Desktop, type this:
yum groupinstall "X Window System" "GNOME Desktop Environment"
After the installation is finished, type this to start KDE or GNOME:
startx
1. On the remote server, edit /etc/ssh/sshd_config, and set the following values:
X11Forwarding yes
X11DisplayOffset 10
X11UseLocalhost yes
2. On the remote server, install the package xorg-x11-xauth:
# yum install xorg-x11-xauth
3. On the remote server, install the fontconfig packages:
# yum install fonts-xorg-base (CentOS 4)
# yum install xorg-x11-fonts-base liberation-fonts (CentOS 5)
4. Now login to the remote server using "-Y" option:
local$ ssh -Y remote_server
5. In the remote server, run your X program, such as the xterm:
remote$ xterm
And you shall see the X program pop up in your local desktop.
You can also add the following into your $HOME/.ssh/config:
ForwardAgent yes
ForwardX11 yes
ForwardX11Trusted yes
6. service sshd restart

Requirements for Remotely Displaying Applications

In order to run an application on one Linux system and have it display on another system there are a couple of prerequisites.
Firstly, the system on which the application is to be displayed must be running an X server. If the system is a Mac OS X, UNIX orLinux based system with a desktop environment running then this is no problem. If the system is running Windows, however, then you must install an X server on it before you can display applications from a remote system. A number of commercial and free Windows based X servers are available for this purpose and a web search should provide you with a list of options.
Secondly, the system on which the application is being run (as opposed to the system which the application is to be displayed) must be configured to allow SSH access. Details on configuring SSH on a CentOS system can be found in the chapter entitledConfiguring CentOS Remote Access using SSH. Finally, SSH must be configured to allow X11 Forwarding. To verify this, load the/etc/ssh/ssh_config file into an editor and make sure that the following directive is set:
X11Forward yes
Once the above requirements are met it is time to remotely display an application.

Remotely Displaying a CentOS Application

The first step in remotely displaying an application is to move to the system where the application is to be displayed. At this system, ssh into the remote system so that you have a command prompt. This can be achieved using the ssh command. When using the ssh command we need to use the -X flag to tell ssh that we plan to tunnel X traffic through the connection:
ssh -X user@hostname
In the above example username is the user name to use to log into the remote system and hostname is the hostname or IP address of the remote system. Enter your password at the login prompt. Once logged in, run the following command to see the DISPLAY setting:
echo $DISPLAY
The command should output something similar to the following:
localhost:10.0
To display an application simply run it from the command prompt. For example:
gedit
When run, the above command should run the gedit tool on the remote system, but display the output on the local system.

Trusted X11 Forwarding

If the /etc/ssh/ssh_config file on the remote system contains the following line, then it is possible to use trusted X11 forwarding:
ForwardX11Trusted yes
Trusted X11 forwarding is slightly faster than untrusted forwarding since it does not engage the X11 security controls. The -Y flag is needed when using trusted X11 forwarding:
ssh -Y user@hostname

Compressed X11 Forwarding

When using slower links the X11 data can be compressed using the -C flag:
ssh -X -C user@hostname

Wednesday, November 30, 2011

CentOS 6 with chrooted SFTP-only users + SSH hardening

SkyHi @ Wednesday, November 30, 2011
 Having a new server deployment to do, I wanted to take some time to get a working OpenSSH implementation under CentOS 6 to allow for SFTP-only users in a chrooted environment. This process is rather simple (these days) and here’s both my sshd_config file as well as some other notes to help you along your way as well.
You’ll note some of the restrictions are excessive for most people but for my implementation the crypto overhead is fine.
/etc/ssh/sshd_config
AddressFamily inet
#ListenAddress 0.0.0.0
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
KeyRegenerationInterval 1h
ServerKeyBits 4096
SyslogFacility AUTHPRIV
LogLevel VERBOSE
LoginGraceTime 1m
PermitRootLogin no
StrictModes yes
MaxAuthTries 4
MaxSessions 5
PasswordAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
RSAAuthentication no
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
UsePAM yes
Ciphers aes256-ctr,aes256-cbc
MACs hmac-sha1
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS
AllowAgentForwarding no
AllowTcpForwarding no
GatewayPorts no
X11Forwarding no
PrintMotd no
PrintLastLog no
TCPKeepAlive yes
UsePrivilegeSeparation yes
ClientAliveInterval 300
ClientAliveCountMax 0
ShowPatchLevel no
UseDNS yes
PidFile /var/run/sshd.pid
MaxStartups 20
PermitTunnel no
Subsystem sftp internal-sftp
Match Group sftpusers
ChrootDirectory /home/%u
PasswordAuthentication no
ForceCommand internal-sftp
ServerKeyBits Note
If you change your ServerKeyBits be sure to purge your existing keys (/rm /etc/ssh/ssh_host_*) and restart sshd to allow them to regenerate.
Configure proper permissions
chown root:root /home/[username]
chmod 711 /home/[username]
Setup the .ssh directory
mkdir /home/[username]/.ssh
chown root:sftpusers /home/[username]/.ssh
chmod 750 /home/[username]/.ssh
Setup the authorized_keys file
touch /home/[username]/.ssh/authorized_keys
chown root:sftpusers /home/[username]/.ssh/authorized_keys
chmod 440 /home/[username]/.ssh/authorized_keys
Create a directory accessible by the user
mkdir /home/[username]/storage
chown [username]:[username] /home/[username]/storage
chmod 760 /home/[username]/storage
Note, you’ll likely want to generate a public/private SSH keypair (ssh-keygen -t rsa) for the user and ensure permissions are as they should be above. This must be done unless you re-enable password authentication.


REFERENCES
http://www.uncompiled.com/2011/09/centos-6-with-chrooted-sftp-only-users-ssh-hardening/

Thursday, August 11, 2011

Rate limiting login attempts with iptables

SkyHi @ Thursday, August 11, 2011
Rate limiting login attempts is an easy way to prevent some of the high speed password guessing attacks. However, it's hard to limit distributed attacks and many run at a low pace over weeks or months. I personally prefer to avoid using automated response tools like fail2ban. And this is for two reasons:

Legitimate users sometimes forget their passwords. I don't want to ban legitimate users from my server, forcing me to manually enable their accounts again (or worse, try to figure out which of the 100/1000 banned IP addresses is theirs).
An IP address is not a good identifier for a user. If you have multiple users behind a single IP (for example, a school that runs NAT on 500 student machines) a single user making a few bad guesses can land you in a world of pain. At the same time the majority of the password guessing attempts I see are distributed.

Therefore I don't consider fail2ban (and similar automated response tools) a very good approach to securing a server against brute force attacks. A simple IPTables rules set to cut down on the log spam (which I have on most of my linux servers) is something like this:

iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set
iptables -I INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP


It prevents more than 4 connection attempts from a single IP to ssh in any 60 second period. The rest can be handled by ensuring passwords are reasonably strong. On high security servers forcing the users to use public key authentication is another way to stop guessing.

REFERENCES
http://serverfault.com/questions/216995/is-it-worth-the-effort-to-block-failed-login-attempts

Thursday, February 10, 2011

Howto use SSH local and remote port forwarding

SkyHi @ Thursday, February 10, 2011
Port forwarding, or tunneling, is a way to forward otherwise insecure TCP traffic through SSH Secure Shell. You can secure for example POP3, SMTP and HTTP connections that would otherwise be insecure.

There are two kinds of port forwarding: local and remote forwarding. They are also called outgoing and incoming tunnels, respectively.
Local port forwarding forwards traffic coming to a local port to a specified remote port. For example, all traffic coming to port 1234 on the client could be forwarded to port 23 on the server (host).
Note: The value of localhost is resolved after the Secure Shell connection has been established – so when defining local forwarding (outgoing tunnels), localhost refers to the server (remote host computer) you have connected to.
Remote port forwarding does the opposite: it forwards traffic coming to a remote port to a specified local port. For example, all traffic coming to port 1234 on the server (host) could be forwarded to port 23 on the client (localhost).
Local port forwarding
Accessing a service (in this example SSH port tcp/22, but it could be anything like a web server on tcp/80) on a machine at work (172.16.10.10) from your machine at home (192.168.10.10), simply by connecting to the server work.example.org at work :
$ ssh user@work.example.org -L 10000:172.16.10.10:22
We see the service is available on the loopback interface only, listening on port tcp/10000 :
$ netstat -tunelp | grep 10000
tcp 0 0 127.0.0.1:10000 0.0.0.0:* LISTEN 1000 71679 12468/ssh
From your home machine, you should be able to connect to the machine at work :
$ ssh root@localhost -p 10000
Local port forward for anyone at home !
If you want other people on your home subnet to be able to reach the machine at work by SSH, add the option -g :
$ ssh user@work.example.org -L 10000:172.16.10.10:22 -g
We now see the service is available on all interfaces on your home computer, available for anyone to connect to on the local subnet :
$ netstat -tunelp | grep 10000

tcp 0 0 0.0.0.0:10000 0.0.0.0:* LISTEN 1000 72265 12543/ssh
Anyone on your local subnet should be able to connect to the machine at work by doing this :
$ ssh root@192.168.10.10 -p 10000
Remote port forwarding
Giving access to a service (SSH port tcp/22) on your home machine (192.168.10.10) to people at work
$ ssh user@work.example.org -R 10000:192.168.1.10:22
We see on our server at work (on the loopback interface on port tcp/10000) that we have access to our SSH server at home :
work.example.org$ netstat -tunelp | grep 10000

tcp 0 0 127.0.0.1:10000 0.0.0.0:* LISTEN 0 73719534 3809/1
People logged in on the machine work.example.org now should be able to SSH into your home machine by doing :
work.example.org$ ssh user@localhost -p 10000
Remote port forwarding for anyone at work !
If you want everybody on the subnet at work to be able to SSH into your home machine, there’s no -g option for remote forward, so you need to change the SSH configuration of work.example.org, add to sshd_config :
GatewayPorts yes
Connect just as before :
home$ ssh user@work.example.org -R 10000:192.168.1.10:22
Now, it’s listening on all interfaces on the server at work :
work.example.org$ netstat -tunelp | grep 10000

tcp 0 0 0.0.0.0:10000 0.0.0.0:* LISTEN 0 73721060 4426/1
Anyone at work can now connect to your home machine by SSH via the server :
anyone.example.org$ ssh anyone@work.example.org -p 10000
Notes
- You would need to log in as root if you want services to listen on a port < 1024.
- Don’t forget to open necessary ports on any firewall either at home or work.
- Unfortunately you can only forward services running on TCP, but there’s a way to forward UDP through SSH using netcat

REFERENCES
http://www.debianadmin.com/howto-use-ssh-local-and-remote-port-forwarding.html

Reverse ssh port forwarding

SkyHi @ Thursday, February 10, 2011
Bypassing corporate firewall with reverse ssh port forwarding
Probably lots of you are behind some sort of very restrictive corporate firewall. Unable to access your office pc from home because of firewall policies. In normal cases this scenario is more than welcomed. No outsiders should be allowed to access internal parts of secure network! Ideally companies will setup secure VPN access thus allowing its employees to access their work computers and do some work remotely. What if you aren’t one of the lucky ones having such option? You desperately need to access your office pc?

The problem

current

//
As shown on the picture above, we have our office PC behind very restrictive corporate firewall connected to Internet. Firewall will not allow any traffic originating from Internet to internal network except previously initiated traffic. Meaning you can contact remote hosts on Internet from your office PC and they can respond, but remote computers can’t initiate connection to your office PC. This is of course huge problem if you have to access your work materials on office PC from your home. Additionally corporate firewall will only allow certain traffic from your office PC to remote hosts. Meaning you can only establish FTP, SSH, HTTP, POP3… communications, all other ports are blocked.
So how can you access your office PC? One way is to setup corporate VPN access allowing secure connections to internal network. Another method is to setup a port forwarding on corporate firewall so it redirects certain ports to your office PC. But if you don’t have the means to accomplish any of this then the only way to do it is to use ssh tunnels and reverse port forwarding.

The solution

So if we can only contact remote hosts on certain ports, the solution would be to contact remote hosts via allowed port and piggyback the connection on already established link.
reverese-ssh
Something like shown on the picture above. Fortunately we can do this with ssh, all we need to do is met some requirements.
// //


Real life example

I will assume that home PC is connected via dynamically assigned IP address. First thing you will need to make sure you have ssh server installed on your home PC and it should be accessible from Internet. If you have some NAT routers, be sure to forward port 22 to your home PC. Secondly you will need to setup a dyndns account so you can connect to your home PC regardless of IP address changes. Now the goal will be to connect to ssh server on our office PC. so the port in question will be 22 if you wish to forward another port change it in your configuration accordingly.
For the purpose of this example i will name my home PC: bhome.dyndns.com office computer name will be bwork.office.com
bwork computer uses private IP range of 192.168.0.0/24 with address 192.168.0.100
So if the firewall is preventing outside connections to our bwork computer we must initiate connection from it.
We can do this with simple ssh command:

council# ssh -R 2210:localhost:22 user@bhome.dyndns.com(ninja)
 
So what just happened here?
We are initiating ssh connection “ssh” with reverse port forwarding option “-R” which will then open listening port “2210:” who is going to be forwarded back to localhost’s port “:22″ and all this will happen on remote computer “bhome.dyndns.com”.
This connection represents the green line in the diagram above, and it’s a legit connection as far as corporate firewall is concerned.
So if we now open up a terminal on bhome computer, and type in:
#
ninja#ssh -p 2210 user@localhost
 
we will try to connect to localhost (bhome.dyndns.com) on port 2210. Since that port is setuped by remote ssh connection it will tunnel the request back via that link to the bwork.office.com computer. This is the red line on the diagram above. Looking from firewall’s perspective it’s a legit traffic, since it is responding traffic on already initiated link from bwork computer.

Real life example 2

What if your home computer is not always on-line? Or perhaps you wish to access your office computer from multiple locations? For this you will have to have some dedicated server or VPS outside the corporate firewall.
reverese-ssh2So to accomplish this we will use the same command as previously, only this time we will open up a reverse ssh tunnel to remote server or VPS.
For the purpose of this example we will name the server bserver.outside.com with IP 89.xxx.xx.4
ssh -R 2210:localhost:22 bserver.outside.com
again this will open up reverse ssh tunnel to the machine 89.xxx.xx.4 (bserver.outside.com). So when we login to the server and issue the command:
ssh -p 2210 localhost
we will end up with bwork computer’s ssh login prompt.

Can I use this previously established reverse ssh tunnel to the server to directly connect to my office computer?

// //


Of course, but some slight modifications are required.
By default ssh tunnels only bind to local address, and can be accessible only locally. Meaning, in the example above, you can’t just type:
ssh -p 2210 bserver.outside.com
on your home PC and be connected to your office PC
If you run:
netstat -ntl
on bserver you will see that the port 2210 is only listening on 127.0.0.1 IP address. To get it listen on interface connected to Internet we must enable GatewayPorts option in ssh server’s configuration.
By default GatewayPorts are disabled in sshd, we can simply enable them:
nano /etc/ssh/sshd_config
then add:
GatewayPorts clientspecified
save the file and restart sshd:
/etc/init.d/ssh restart
we could have just enable GatewayPorts by typing On instead of clientspecified, that would route any ssh tunnel to network interface. This way we can control which tunnel will be accessible from outside, and on which interface.
So if we initiate reverse ssh tunnel like this:
ssh -R 89.xxx.xx.4:2210:localhost:22 bserver.outside.com
we will have bserver listening on port 2210 on network interface bound to ip 89.xxx.xx.4 and forwarding all traffic via established tunnel to bwork computer. If you omit the 89.xxx.xx.4 address from the command above server will again listen on port 2210 only on local loopback interface. If you have multiple network interfaces on server be sure to select the one you can connect to.
reverese-ssh3So now when we run:
ssh -p 2210 bserver.outside.com
from our home PC we will initiate ssh connection on port 2210 towards server bserver.outside.com (blue line). Server will then forward that traffic to office PC (red line) via the previously established reverse ssh tunnel (gren line). Of course you will have to open up port 2210 on server’s firewall to be able to connect.
// //


Some more fun with reverse tunnels.

But i have a printer behind that corporate firewall. How can i connect to it? Easy… remember the first example? the command ssh -R is taking 5 arguments of which 4 are mandatory
ssh -R [bind_address:]port:host:hostport
bind_address is the network address on which port will be listening, and forwarded to host (connected to network from which reverse tunnel originated) on hostport.
so if we issue the command like this on our bwork pc:
ssh -R 89.xxx.xx.4:2211:192.168.0.10:631 bserver.outside.com
we will get something like this:
reverese-ssh4so again we have previously established reverse ssh tunnel listening on port 2210 to channel the ssh connection towards office PC. Now with this new command we established the reverse ssh tunnel (yellow line) towards bserver which will listen for incoming connections on port 2211. When the home pc makes a data connection to port 2211 on bserver (brown line) it is then forwarded to office PC (black line) which is then redirected towards office printer at address 192.168.0.10 on port 631 (violet line). Remember, all this traffic is passing trough corporate firewall as legit traffic, even if the illustration perhaps shows otherwise.

Automating the task

So by now we should have covered the basics on how to bypass corporate firewall in order to get to your office computer and network equipment. Now ssh -R isn’t really practical, it consumes one terminal, and as soon as it shuts down there is no tunnel and no outside connectivity for that matter. The easiest thing to do is putting a cron job that will connect to remote server if the connection fails, office computer reboots etc.
First of all generate ssh keys, and add them to ssh-agent so that script won’t ask you for remote server’s password all the time.
Next we will add two extra parameters to our command -N and -f so that the connection goes into the background.
the command will look like:
ssh -N -f -R [bind_address:]port:host:hostport
next we need a shell script that will be triggered by the cron. For this example we will use the Real life example 2.
#!/bin/sh
COMMAND="ssh -N -f -R 89.xxx.xx.4:2210:localhost:22 bserver.outside.com"
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND
now edit this code so it suits your needs, and save it in your home dir as reverse_ssh_tunnel.sh
Now we need to add a crontab entry which will trigger this script every 5 minutes.
crontab -e
and add:
*/5 * * * * /bin/sh /home/username/reverse_ssh_tunnel.sh
If you are connecting to different user name on remote server you can edit your commands so they look like:
ssh -R [bind_address]:port:host:host_port username@remote_host


REFERENCES
http://rhnotebook.wordpress.com/2010/02/13/reverse-ssh-port-forwarding-t-o-i-c-o-r-g/

Thursday, November 25, 2010

25 Best SSH Commands / Tricks

SkyHi @ Thursday, November 25, 2010
OpenSSH is a FREE version of the SSH connectivity tools that technical users of the Internet rely on. Users of telnet, rlogin, and ftp may not realize that their password is transmitted across the Internet unencrypted, but it is. OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other attacks. Additionally, OpenSSH provides secure tunneling capabilities and several authentication methods, and supports all SSH protocol versions.

SSH is an awesome powerful tool, there are unlimited possibility when it comes to SSH, heres the top Voted SSH commands
1) Copy ssh keys to user@host to enable password-less ssh logins.

ssh-copy-id user@host

To generate the keys use the command ssh-keygen
2) Start a tunnel from some machine’s port 80 to your local post 2001

ssh -N -L2001:localhost:80 somemachine

Now you can acces the website by going to http://localhost:2001/
3) Output your microphone to a remote computer’s speaker

dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp

This will output the sound from your microphone port to the ssh target computer’s speaker port. The sound quality is very bad, so you will hear a lot of hissing.
4) Compare a remote file with a local file

ssh user@host cat /path/to/remotefile | diff /path/to/localfile -

Useful for checking if there are differences between local and remote files.
5) Mount folder/filesystem through SSH

sshfs name@server:/path/to/folder /path/to/mount/point

Install SSHFS from http://fuse.sourceforge.net/sshfs.html
Will allow you to mount a folder security over a network.
6) SSH connection through host in the middle

ssh -t reachable_host ssh unreachable_host

Unreachable_host is unavailable from local network, but it’s available from reachable_host’s network. This command creates a connection to unreachable_host through “hidden” connection to reachable_host.
7) Copy from host1 to host2, through your host
ssh root@host1 “cd /somedir/tocopy/ && tar -cf – .” | ssh root@host2 “cd /samedir/tocopyto/ && tar -xf -”

Good if only you have access to host1 and host2, but they have no access to your host (so ncat won’t work) and they have no direct access to each other.

8) Run any GUI program remotely

ssh -fX @

The SSH server configuration requires:

X11Forwarding yes # this is default in Debian

And it’s convenient too:

Compression delayed
9) Create a persistent connection to a machine

ssh -MNf @

Create a persistent SSH connection to the host in the background. Combine this with settings in your ~/.ssh/config:
Host host
ControlPath ~/.ssh/master-%r@%h:%p
ControlMaster no
All the SSH connections to the machine will then go through the persisten SSH socket. This is very useful if you are using SSH to synchronize files (using rsync/sftp/cvs/svn) on a regular basis because it won’t create a new socket each time to open an ssh connection.
10) Attach screen over ssh

ssh -t remote_host screen -r

Directly attach a remote screen session (saves a useless parent bash process)
11) Port Knocking!

knock 3000 4000 5000 && ssh -p user@host && knock 5000 4000 3000

Knock on ports to open a port to a service (ssh for example) and knock again to close the port. You have to install knockd.
See example config file below.
[options]
logfile = /var/log/knockd.log
[openSSH]
sequence = 3000,4000,5000
seq_timeout = 5
command = /sbin/iptables -A INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn
[closeSSH]
sequence = 5000,4000,3000
seq_timeout = 5
command = /sbin/iptables -D INPUT -i eth0 -s %IP% -p tcp –dport 22 -j ACCEPT
tcpflags = syn
12) Remove a line in a text file. Useful to fix

ssh-keygen -R

In this case it’s better do to use the dedicated tool
13) Run complex remote shell cmds over ssh, without escaping quotes

ssh host -l user $(> ~/.ssh/authorized_keys”

If you use Mac OS X or some other *nix variant that doesn’t come with ssh-copy-id, this one-liner will allow you to add your public key to a remote machine so you can subsequently ssh to that machine without a password.
17) Live ssh network throughput test

yes | pv | ssh $host “cat > /dev/null”

connects to host via ssh and displays the live transfer speed, directing all transferred data to /dev/null
needs pv installed
Debian: ‘apt-get install pv’
Fedora: ‘yum install pv’ (may need the ‘extras’ repository enabled)
18) How to establish a remote Gnu screen session that you can re-connect to

ssh -t user@some.domain.com /usr/bin/screen -xRR

Long before tabbed terminals existed, people have been using Gnu screen to open many shells in a single text terminal. Combined with ssh, it gives you the ability to have many open shells with a single remote connection using the above options. If you detach with “Ctrl-a d” or if the ssh session is accidentally terminated, all processes running in your remote shells remain undisturbed, ready for you to reconnect. Other useful screen commands are “Ctrl-a c” (open new shell) and “Ctrl-a a” (alternate between shells). Read this quick reference for more screen commands: http://aperiodic.net/screen/quick_reference
19) Resume scp of a big file

rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file

It can resume a failed secure copy ( usefull when you transfer big files like db dumps through vpn ) using rsync.
It requires rsync installed in both hosts.
rsync –partial –progress –rsh=ssh $file_source $user@$host:$destination_file local -> remote
or
rsync –partial –progress –rsh=ssh $user@$host:$remote_file $destination_file remote -> local
20) Analyze traffic remotely over ssh w/ wireshark

ssh root@server.com ‘tshark -f “port !22″ -w -’ | wireshark -k -i -

This captures traffic on a remote machine with tshark, sends the raw pcap data over the ssh link, and displays it in wireshark. Hitting ctrl+C will stop the capture and unfortunately close your wireshark window. This can be worked-around by passing -c # to tshark to only capture a certain # of packets, or redirecting the data through a named pipe rather than piping directly from ssh to wireshark. I recommend filtering as much as you can in the tshark command to conserve bandwidth. tshark can be replaced with tcpdump thusly:
ssh root@example.com tcpdump -w – ‘port !22′ | wireshark -k -i -
21) Have an ssh session open forever

autossh -M50000 -t server.example.com ‘screen -raAd mysession’

Open a ssh session opened forever, great on laptops losing Internet connectivity when switching WIFI spots.
22) Harder, Faster, Stronger SSH clients

ssh -4 -C -c blowfish-cbc

We force IPv4, compress the stream, specify the cypher stream to be Blowfish. I suppose you could use aes256-ctr as well for cypher spec. I’m of course leaving out things like master control sessions and such as that may not be available on your shell although that would speed things up as well.
23) Throttle bandwidth with cstream

tar -cj /backup | cstream -t 777k | ssh host ‘tar -xj -C /backup’

this bzips a folder and transfers it over the network to “host” at 777k bit/s.
cstream can do a lot more, have a look http://www.cons.org/cracauer/cstream.html#usage
for example:
echo w00t, i’m 733+ | cstream -b1 -t2
24) Transfer SSH public key to another machine in one step

ssh-keygen; ssh-copy-id user@host; ssh user@host

This command sequence allows simple setup of (gasp!) password-less SSH logins. Be careful, as if you already have an SSH keypair in your ~/.ssh directory on the local machine, there is a possibility ssh-keygen may overwrite them. ssh-copy-id copies the public key to the remote host and appends it to the remote account’s ~/.ssh/authorized_keys file. When trying ssh, if you used no passphrase for your key, the remote shell appears soon after invoking ssh user@host.
25) Copy stdin to your X11 buffer

ssh user@host cat /path/to/some/file | xclip

Have you ever had to scp a file to your work machine in order to copy its contents to a mail? xclip can help you with that. It copies its stdin to the X11 buffer, so all you have to do is middle-click to paste the content of that looong file :)




====================================================================================
An almost invisible ssh connection

ssh -T user@host /bin/bash -i

sudo lsof -i :22

http://news.ycombinator.com/item?id=1536126

http://news.ycombinator.com/item?id=874666

http://news.ycombinator.com/item?id=1624010


REFERENCES
http://blog.urfix.com/25-ssh-commands-tricks/

Saturday, November 13, 2010

Howto Linux / UNIX setup SSH with DSA public key authentication (password less login)

SkyHi @ Saturday, November 13, 2010
Q. How do you set-up SSH with DSA public key authentication? I have Linux laptop called tom and remote Linux server called jerry. How do I setup DSA based authentication so I don’t have to type password?

A. DSA public key authentication can only be established on a per system / user basis only i.e. it is not system wide. You will be setting up ssh with DSA public key authentication for SSH version 2 on two machines:

#1 machine : your laptop called tom
#2 machine : your remote server called jerry
Command to type on your laptop/desktop (local computer)

First login to local computer called tom and type the following command.
Step #1: Generate DSA Key Pair

Use ssh-keygen command as follows:
$ ssh-keygen -t dsa
Output:

Enter file in which to save the key (/home/vivek/.ssh/id_dsa): Press [Enter] key
Enter passphrase (empty for no passphrase): myPassword
Enter same passphrase again: myPassword
Your identification has been saved in /home/vivek/.ssh/id_dsa.
Your public key has been saved in /home/vivek/.ssh/id_dsa.pub.
The key fingerprint is:
04:be:15:ca:1d:0a:1e:e2:a7:e5:de:98:4f:b1:a6:01 vivek@vivek-desktop

Caution: a) Please enter a passphrase different from your account password and confirm the same.
b) The public key is written to /home/you/.ssh/id_dsa.pub.
c) The private key is written to /home/you/.ssh/id_dsa.
d) It is important you never-ever give out your private key.
Step #2: Set directory permission

Next make sure you have correct permission on .ssh directory:
$ cd
$ chmod 755 .ssh
Step #3: Copy public key

Now copy file ~/.ssh/id_dsa.pub on Machine #1 (tom) to remote server jerry as ~/.ssh/authorized_keys:
$ scp ~/.ssh/id_dsa.pub user@jerry:.ssh/authorized_keys
Command to type on your remote server called jerry

Login to your remote server and make sure permissions are set correct:
$ chmod 600 ~/.ssh/authorized_keys
Task: How do I login from client to server with DSA key?

Use scp or ssh as follows from your local computer:
$ ssh user@jerry
$ ssh user@remote-server.com
$ scp file user@jerry:/tmp

You will still be asked for the passphrase for the DSA key file each time you connect to remote server called jerry, unless you either did not enter a passphrase when generating the DSA key pair.
Task: How do I login from client to server with DSA key but without typing a passhrase i.e. password-less login?

Type the following command at shell prompt:
$ exec /usr/bin/ssh-agent $SHELL
$ ssh-add
Output:

Enter passphrase for /home/vivek/.ssh/id_dsa: myPassword
Identity added: /home/vivek/.ssh/id_dsa (/home/vivek/.ssh/id_dsa)

Type your passhrase once. Now, you should not be prompted for a password whenever you use ssh, scp, or sftp command.

If you are using GUI such as Gnome use the command:
$ ssh-askpass
OR
$ /usr/lib/openssh/gnome-ssh-askpass

To save your passphrase during your GNOME session under Debian / Ubuntu, do as follows:
a) Click on System
b) Select Preferences
c) Select Session
d) Click on New
e) Enter "OpenSSH Password Management" in the Name text area
f) Enter /usr/lib/openssh/gnome-ssh-askpass in the command text area.
Howto Linux / UNIX setup SSH with DSA public key authentication
g) Click on close to save the changes
h) Log out and then log back into GNOME. After GNOME is started, a dialog box will appear prompting you for your passphrase. Enter the passphrase requested. From this point on, you should not be prompted for a password by ssh, scp, or sftp.


Install / Append SSH Key In A Remote Linux / UNIX Servers Authorized_keys

by Vivek Gite on May 6, 2010 · 4 comments

How do I install my SSH public key ~/.ssh/id_rsa.pub onto a remote Linux / UNIX server automatically from Linux workstation / Apple OS X laptop without using scp and/or copy & paste method?

You need to use the ssh-copy-id script that uses ssh to log into a remote machine using a login password. The syntax is as follows:

ssh-copy-id -i ~/.ssh/id_rsa.pub user@server.example.com
ssh-copy-id -i ~/.ssh/id_dsa.pub user@server.example.com

Step # 1: Create Keys

Type the following ssh-keygen command to generates, manages and converts authentication keys for your workstation / laptop:
ssh-keygen
Make sure you protect keys with the passphrase.
Step # 2: Install Keys

Install key in a remote server called www-03.nixcraft.in, enter:
ssh-copy-id -i ~/.ssh/id_dsa.pub username@www-03.nixcraft.in
Step #3: Use keychain for password less login

OpenSSH offers RSA and DSA authentication to remote systems without supplying a password. keychain is a special bash script designed to make key-based authentication incredibly convenient and flexible. Add following lines to your ~/.bash_profile

/usr/bin/keychain $HOME/.ssh/id_rsa
source $HOME/.keychain/$HOSTNAME-sh

Save and close the file.
References:

* man ssh-copy-id


REFERENCES
http://www.cyberciti.biz/faq/ssh-password-less-login-with-dsa-publickey-authentication/
http://www.cyberciti.biz/faq/install-ssh-identity-key-remote-host/