
SSH Kung Fu  - stasel
http://blog.tjll.net/ssh-kung-fu/
======
patio11
A trick I learned recently: create .ssh/config

File format: as many of the following blocks as you like

    
    
      Host $ALIAS <-- whatever you want here
      Hostname www.example.com
      User someuser
      Port 1234
    

You can now ssh to that server as that user by doing "ssh $ALIAS" on the
command line, without needing to specify the port or user with the usual
command line arguments, or necessarily spell out the entire host name.

~~~
deanclatworthy
I've been doing this for a while now, but my file is now huge and it's
cumbersome to edit. Is there no utility to mange that file?

~~~
datr
I've worked around this by creating a ~/.ssh/config.d directory and splitting
my configuration out into multiple files (normally by project). I then use
dotdee[1] to watch that directory and automatically rebuild ~/.ssh/config
anytime there is a change.

[1] [https://launchpad.net/dotdee](https://launchpad.net/dotdee)

------
hf
A few commenters do not seem to be aware that it is perfectly possible to use
passphrase-protected keys for automated tasks (cronjobs and the like).

The excellent (though unfortunately named) keychain[0] utility provides a
ready and powerful abstraction for _both_ ssh-agent and gpg-agent.

[0] [https://github.com/funtoo/keychain](https://github.com/funtoo/keychain)

~~~
dmourati
Huge fan. The old IBM SSH developerworks series is my favorite primer for
folks new to SSH:

[http://www.ibm.com/developerworks/library/l-keyc.html](http://www.ibm.com/developerworks/library/l-keyc.html)
[http://www.ibm.com/developerworks/library/l-keyc2/](http://www.ibm.com/developerworks/library/l-keyc2/)
[http://www.ibm.com/developerworks/library/l-keyc3/](http://www.ibm.com/developerworks/library/l-keyc3/)

------
peteretep
From the article:

    
    
        > No more password prompts
    

Is that - you ask - because he's using ssh-agent? No, it's because he doesn't
tell you you should be using a password-protected key. Some kung fu.

~~~
WestCoastJustin
There are many cases where you do not want, or cannot have a password
protected ssh trust. For example, say you have a central nagios host
monitoring a network, that nagios host needs to connect to remote machines to
run interesting monitoring scripts (disk % full, raid controller query, mpio
checks, etc), in these cases you do not want to have a password blocking the
ssh trust. You will also find this type of thing happening in many continuous
deployment workflows as bits are moving from one machine to the other. This is
_very common_ practice.

~~~
mverwijs
No, in _that_ case, you limit the commands that nagios is allowed to executed
using this specific, passphrase-less key.

In this case you would limit this ssh-key to only be able to execute the
nagios monitoring scripts. Nothing else.

You do this in ~/.ssh/config on the remote machine.

~~~
rickr
I believe you mean ~/.ssh/authorized_keys?

For anyone interested here's an SO question with an example:
[http://stackoverflow.com/questions/402615/how-to-restrict-
ss...](http://stackoverflow.com/questions/402615/how-to-restrict-ssh-users-to-
a-predefined-set-of-commands-after-login)

------
hf
The situation with beginner-friendly SSH tutorials is, in a much lesser degree
perhaps, comparable to the crypto texts: Good will alone does more harm than
good.

This treatment ssh does not mention ssh-agent and, more importantly perhaps,
implies that there is a certain virtue in having private keys unprotected by
sturdy passphrases lying around.

There is not; most emphatically not.

~~~
voltagex_
Hypothetically, if one was reading this article and had a large number of
unprotected private keys around, one could change the password on these keys
by issuing

    
    
       ssh-keygen -f id_rsa -p

------
edwintorok
The article mentions ECDSA, but doesn't mention Ed25519, which is supported
since OpenSSH 6.5:
[https://lwn.net/Articles/583485/](https://lwn.net/Articles/583485/)

As a bonus Ed25519 keys unconditionally use bcrypt for protecting the private
key

------
icebraining
This is why reading the man pages is useful; you'd get all this and more,
including:

    
    
      - X11 Forwarding
      - Reverse forwarding (bind listening sockets on the remote machine,
                            redirecting to a local service)
      - SSH-Based VPNs

------
ak217
Best trick I learned in the past few years is SSH control sequences.

Disconnected from your host but not timed out yet? Press Enter, ~, . and the
client will quit.

~~~
themckman
Ohh my, the day I learned this was one of the happiest in all my life. You can
also configure this in your .ssh/config with EscapeChar, if you find yourself
SSHing into other machines from a machine you're already SSHed into.

~~~
eieio
You can also use send a double tilde ( Enter, ~, ~) to pass a tilde to your
inner ssh session. So killing a session within a session is Enter, ~, ~, .

------
terhechte
> Sharing Connections

I've tried this before, and what effectively always happened (to me) is that
as soon as I started copying a file, I couldn't continue working in Vim
anymore until the file was done transmitting because the copying would eat all
the bandwidth. There may be a flag or setting around this, but I've never
found it. When I open two connections, it is usually fine.

~~~
XorNot
I've found it just tends to have the primary connection die, and never tries
to reconnect. ServerKeepAlives or what have you don't seem to help either -
the link goes dead, and I won't be able to connect any other sessions because
SSH will just keep on routing them into the control master.

~~~
michaelmior
I have had this problem, although fairly rarely. I have the following in my
~/.ssh/config:

    
    
        ControlPath /tmp/ssh_mux_%h_%p_%r
    

This sets the path of the control file used to share the connection. If it
ever hangs, I can just delete the file. But in practice I found this doesn't
happen often and I appreciate the speed boost I get from connection sharing.

~~~
shabble
one minor annoyance is that there's a max limit to the ControlPath string
(seemingly due to there being a max path length for Unix Sockets) which I've
occasionally hit when connecting to hosts with very long hostnames (AWS
default hostnames can sometimes hit it, IIRC).

Also note that the docs recommend against using publicly accessible dirs such
as /tmp/ for storing your mux sockets. I'm not sure of the exact threat (maybe
just info leakage about what hosts you're connected to, since the socket
permissions themselves are strict), but I use ~/.ssh/mux/ for mine.

~~~
michaelmior
Good point about the permission. I'm not doing this on a shared host anyway,
so no else has access to that directory, but good to keep in mind.

------
bryanlarsen
Another recommendation: start an SSH server on port 443 on a server somewhere.
Then if you're stuck somewhere on an untrusted network, one that blocks most
outgoing ports or one that throttles non-HTTP ports, you can use SSH for
tunneling and/or setting up a quick SOCKS proxy to get yourself encrypted,
unblocked, full speed internet access.

------
Morgawr
I just learned about remote file editing with vim and scp thanks to this
article, it's the only thing I didn't know about and... wow, it's amazing.
This will make my life much easier every time I have to remotely edit some
config files on my servers.

As for the rest of the article, really nice stuff. Nice tricks for ssh
newbies. I wish he also talked about setting up a nonce system with ssh or
move sshd to a non-default port to prevent attackers spamming port 22, or even
remove password authentication altogether.

~~~
Piskvorrr
Moving ssh port is, IMNSHO, a stopgap measure; you should have exhausted all
the other options (e.g. no passwords, no root login, denyhosts/fail2ban etc.)
before this even crosses your mind.

In other words, the inconvenience this brings is not adequate to the
infinitesimal increase in security.

~~~
moe
_In other words, the inconvenience this brings is not adequate to the
infinitesimal increase in security._

You are wrong. Please refrain from giving security advice.

Changing or filtering the SSH port prevents your host from being compromised
by automated netrange sweeps in the event of a pre-auth ssh vulnerability. For
this reason changing the SSH port is considered best practice.

~~~
JoeAltmaier
Since port numbers are a very tiny space, that would amount to an
infinitesimal increase in security, right? Essentially, 'hiding' the port is
'security through obscurity' which is a thoroughly discredited idea.

~~~
michaelmior
This is assuming that someone is specifically targeting your machine. In which
case yes, changing the port number probably won't do much. But if someone is
just hammering random servers on port 22, changing the port number is much
more likely to be effective.

------
hf
While we are busy dispensing wisdom: Do use

    
    
        PermitRootLogin without-password
    

instead of 'yes' in /etc/ssh/sshd_config if you absolutely must have ssh root
access.

~~~
Piskvorrr
If you must allow SSH root access, in 2014, you are doing something _horribly_
wrong, and this will come back to bite you.

~~~
Sae5waip
Did you ever stop and think about this or are you just repeating something you
read on "Hacker""news"?

Getting by /without/ direct SSH root access is often impractical (think about
scp), and without-password is a secure way to have it.

Also, the more people know about "without-password", the less people will set
PermitRootLogin to "yes".

~~~
jfindley
Requiring admins to ssh to a different, unique-to-them, user, and use sudo
from there for any operations requiring root is much better.

It's far easier to audit what's been done to the server, which is important
not just for compliance but also for figuring out why something's broken
suddenly.

It also means that you get to have your own shell history, your own shell
settings, your own vim settings, etc, etc.

In general, having proper deployment, log collection and config management
tools in place tends to mean you rarely need to scp files around at all - and
the cases when you do, you can work around this by scping them to some other
dir, and moving them locally with a sudo command.

~~~
shabble
...which is fine up until someone forgets to use visudo and buggers up the
sudoers file so nobody can get back in to fix it.

A user login followed by su to root is a valid alternative, but I wouldn't
have a problem with allowing key-only root access via sshd either.

You'd want the root key/password to be very tightly controlled for the reasons
you mention, but having it set is (IMO) a worthwhile backup plan for when
things go wrong.

------
luxpir
One problem I have with SSH is DPI. Deep Packet Inspection seems to be behind
the SSH block in place at a local library I work at. SSH out in any form just
isn't possible there, even via a browser-based console (such as that used by
Digital Ocean, for example). There doesn't seem to be a suitable solution to
get around it offered anywhere.

My own fix was to use 3G to do the SSH work via a tethered phone and to use
the wifi adapter to run the bulk of any other web traffic. It'd be great to
have a workaround for DPI, though, if anyone has any experience there.

~~~
Spooky23
I'd recommend complaining to the library trustees about it.

There's no reason they should be refusing your traffic, and they are probably
only causing a problem because some overzealous consultant cranked up the
setting too high.

In my city, the compliance requirement that must be met is to have a policy to
address "obscene, indecent, violent, or otherwise inappropriate for viewing in
the library environment". Blocking SSH access is not required meet that
compliance requirement.

In our case, our library actually doesn't filter, it's left to the discretion
of the librarians. And there is a time limit for access.

~~~
VLM
"Blocking SSH access is not required meet that compliance requirement."

Read up about SSH VPNs. Probably some kid set up a proxy accessed over SSH
port forwarding, to access some pr0n site, got caught, and next thing you
know, no SSH allowed anymore. If they were really smart they'd allow it but
rate limit it to 2400 bit/s, which is fairly fast for console work but not so
great for downloading animated pr0n gifs.

Whats weird is librarians typically are pretty hard core against censorship.
The same place thats willing to go to court to keep "to kill a mockingbird" or
"huckleberry finn" on the shelves, will simultaneously spare no expense to
block adults from accessing a breast cancer awareness site. A strange bunch,
librarians.

~~~
Spooky23
The library has an obligation to make a good faith effort to meet whatever
compliance requirements that they are faced with. That's it. It isn't a bank
or military installation.

If the original poster brings in an air card, and starts watching porn with
the volume cranked up, the library doesn't have a right or obligation to jam
the cellular network. They do whatever their policy calls for (usually ask the
guy to leave).

Librarians are very rarely the problem -- the trustees or other governing body
usually is. Make a fuss and in most cases the problems will go away. YMMV
depending on the community, of course.

~~~
luxpir
Cheers for your thoughts. I suspect the UK public library authority I would
have to appeal to would have zero motivation to help with SSH access,
unfortunately. I imagine it has been blocked for a specific reason, probably
some previous or expected abuse, as you've both mentioned.

The SSH over SSL solutions others have pointed out may do the trick for now.

------
grn
I can recommend Mastering SSH - it's a nice, short read.

[http://www.amazon.com/SSH-Mastery-OpenSSH-PuTTY-Tunnels-
eboo...](http://www.amazon.com/SSH-Mastery-OpenSSH-PuTTY-Tunnels-
ebook/dp/B006ZO9ULK/)

~~~
Nick_C
I can't. I bought with some high expectations, unfortunately I knew almost
everything in it from a couple of years of using ssh to my several VPSs. I was
quite disappointed at the level of detail it had -- StackExchange level, I
thought.

~~~
grn
You're right that it doesn't go into detail but it's short and provides high-
level overview of the most important features. It's much easier to learn the
basic of something from a book and then find the details in the manual than
working with the manual only.

But if someone expects to gain deep, expert level knowledge of how OpenSSH
works then he'll be disappointed. What expert-level books can you recomment?

~~~
Nick_C
Unfortunately, I can't recommend anything, but I'm not a wide reader on the
topic so my knowledge is limited.

Perhaps I was a bit hard on that book, my expectations were that it would be a
deep, expert type of book. If that's not what you are looking for, it is
perfectly fine. Actually, now that I think about it, the epub version is good
to keep on your mobile phone as a handy, easily-accessible reference for use
in the coffee shop, so I guess it does get a credit from me.

------
magnetikonline
Some good tips here - I like Controlmaster/Controlpath.

Note that on the tip of ~/.ssh/known_hosts providing ssh auto completion,
adding SSH server config to ~/.ssh/config will also enable auto completion.

~~~
shabble
It's great for tab-completion of remote paths for scp & friends.

It does have a few quirks though. One that I've noticed is (IIRC) that closing
a shared session isn't sufficient to pick up new groups membership when you
reconnect. You actually need to kill the master connection as well[0].

The syntax for shutting down a master connection is a bit clunky as well:

    
    
        ssh -O stop -S ~/.ssh/mux/socketname hostname
    

I've been meaning to make a little script or 2 that finds the current mux
sockets and tests them with -O check and give you a list of simple IDs you can
'ssh-mux-kill $id' or something. In fact, it'd probably be a nice use for
percol[1]

[0] There might be other ways of refreshing group memberships, but I don't
know of any.

[1] [https://github.com/mooz/percol](https://github.com/mooz/percol)

------
ambrop7
About the "Lightweight Proxy" (ssh -D), if you want it to be transparent to
the application (not require SOCKS support), you can use my tun2socks[1]
program. This is useful if you can't or don't want to set up an SSH tunnel
(which requires root permissions on the server). The linked page actually
explains exactly this use case. It even works on Windows ;)

[1]
[https://code.google.com/p/badvpn/wiki/tun2socks](https://code.google.com/p/badvpn/wiki/tun2socks)

~~~
marianov
Or use tsocks. Proxies everything that uses tcp through a socks proxy (ssh -D)
[http://manpages.ubuntu.com/manpages/hardy/man1/tsocks.1.html](http://manpages.ubuntu.com/manpages/hardy/man1/tsocks.1.html)

~~~
ambrop7
Not system-wide though, and possibly incompletely and with bugs. The entire
socket API is far from being simple to wrap like this, especially when you
consider that it includes all the various IO functions (read/write, send/recv,
recvmsg/sendmsg), nonblocking operation with select, poll, epoll, the p*
versions of these with special behavior with respect to signals, the
integration of these polling functions with non-wrapped fds, various socket
options, splice functions, thread safety, shutdown semantics...

It shouldn't be hard to find a program which runs fine with tun2socks but
breaks completely or subtly with tsocks.

------
Piskvorrr
Another useful (albeit ugly) hack is accessing a NATed host which doesn't even
have a port forwarded, via an intermediate SSH host _outside_ the target
network: [http://superuser.com/questions/277218/ssh-access-to-
office-h...](http://superuser.com/questions/277218/ssh-access-to-office-host-
behind-nat-router/277220#277220)

(disclaimer: tooting my own horn here, but it is a mighty useful trick)

------
mrlebowski
I have a setup similar to this:

    
    
      laptop - user (userid: me)
      F - firewall (userid: me)
      A - machine 1 in colo (userid: colo)
      B - machine 2 in colo (userid: colo, machine I want to access)
      C - machine 2 in colo (userid: colo)
      .
      .
      100s of machines.
    

Trust (ssh password less login) is setup between me@laptop and me@F, and
me@laptop and colo@A, and between all colo machine (A,B,C..). So colo@A can
ssh colo@B w/o password.

I am able to log into colo@A via F w/o password as I copied the ssh key there
manually. (path me@laptop -> colo@F -> colo@A)

QUESTION: Is it possible to ssh to other machines (B,C..) via A while assuming
full identity of colo@A? (Path would be me@laptop -> colo@F -> colo@A ->
colo@B/C/..) With my current config when I try to ssh to B it knows request is
originating from 'laptop' and still asks me for password.

~~~
Tyr42
I think this guy answered it
[https://news.ycombinator.com/item?id=7658742](https://news.ycombinator.com/item?id=7658742)

ProxyCommand ssh ...

------
beagle3
While the socks proxy does not require any root (local or remote), it is only
useful for programs that support it - which are not many.

However, apenwarr's sshuttle
[https://github.com/apenwarr/sshuttle](https://github.com/apenwarr/sshuttle)
is a briliant semi-proxy-semi-vpn solution that, in return for local root and
remote python (but not remote root), gives you transparent VPN-style
forwarding of TCP connections (and DNS requests if you want). It works
ridiculously well. Try it, if you haven't yet.

------
MichaelMoser123
Very interesting article;

I have a shell script that helps with setting up trusted keys: trusted keys
help if you need to run automated tests, that involve several machines, or
simply if you would like to skip typing in a password on each connection.

[http://mosermichael.github.io/cstuff/all/projects/2011/07/14...](http://mosermichael.github.io/cstuff/all/projects/2011/07/14/ssh-
friends.html)

------
vinceguidry
Is sshfs a serious replacement for nfs? I've got a Buffalo Nas at home that I
use Samba for, but Samba is too slow to watch hi-def videos over. NFS seems to
be a pain in the neck to get working on that particular device, and I hate
using it on a laptop. I guess I should probably just try it, but I can't see
SSHFS as being any faster than Samba.

~~~
turrini
Try:

# sshfs -o
direct_io,nonempty,allow_other,cache=no,compression=no,workaround=rename,workaround=nodelaysrv
user@remote:/place/ /mnt/somewhere

For even more performance:

 __* On server, start socat:

# socat TCP4-LISTEN:7001 EXEC:/usr/lib/sftp-server

 __* On client, do:

# sshfs -o
directport=7001,direct_io,nonempty,allow_other,cache=no,compression=no,workaround=rename,workaround=nodelaysrv
user@remote:/place/ /mnt/somewhere

~~~
voltagex_
Whoa, what do all those options do?

------
radoslawc
for me best trick with ssh so far is to use ssh as proxy command: ssh -o
ProxyCommand="ssh -W %h:%p user@ssh_jump_host.somedomain.net -p
some_non_22_port" user@some_host_inside.lan -D 1234

above creates dynamic tunel (for use as socks proxy) through jumphost to reach
http hosts available only to some_host_inside.lan machine

