Total Pageviews

Thursday 30 July 2015

SSH原理与运用


  • 一、什么是SSH?
    简单说,SSH是一种网络协议,用于计算机之间的加密登录。
    如果一个用户从本地计算机,使用SSH协议登录另一台远程计算机,我们就可以认为,这种登录是安全的,即使被中途截获,密码也不会泄露。
    最早的时候,互联网通信都是明文通信,一旦被截获,内容就暴露无疑。1995年,芬兰学者Tatu Ylonen设计了SSH协议,将登录信息全部加密,成为互联网安全的一个基本解决方案,迅速在全世界获得推广,目前已经成为Linux系统的标准配置。
    需要指出的是,SSH只是一种协议,存在多种实现,既有商业实现,也有开源实现。本文针对的实现是OpenSSH,它是自由软件,应用非常广泛。
    此外,本文只讨论SSH在Linux Shell中的用法。如果要在Windows系统中使用SSH,会用到另一种软件PuTTY,这需要另文介绍。
  • 二、最基本的用法
    SSH主要用于远程登录。假定你要以用户名user,登录远程主机host,只要一条简单命令就可以了。
    $ ssh user@host
    如果本地用户名与远程用户名一致,登录时可以省略用户名。
    $ ssh host
    SSH的默认端口是22,也就是说,你的登录请求会送进远程主机的22端口。使用p参数,可以修改这个端口。
    $ ssh -p 2222 user@host
    上面这条命令表示,ssh直接连接远程主机的2222端口。
  • 三、中间人攻击
    SSH之所以能够保证安全,原因在于它采用了公钥加密。
    整个过程是这样的:(1)远程主机收到用户的登录请求,把自己的公钥发给用户。(2)用户使用这个公钥,将登录密码加密后,发送回来。(3)远程主机用自己的私钥,解密登录密码,如果密码正确,就同意用户登录。
    这个过程本身是安全的,但是实施的时候存在一个风险:如果有人截获了登录请求,然后冒充远程主机,将伪造的公钥发给用户,那么用户很难辨别真伪。因为不像https协议,SSH协议的公钥是没有证书中心(CA)公证的,也就是说,都是自己签发的。
    可以设想,如果攻击者插在用户与远程主机之间(比如在公共的wifi区域),用伪造的公钥,获取用户的登录密码。再用这个密码登录远程主机,那么SSH的安全机制就荡然无存了。这种风险就是著名的"中间人攻击"(Man-in-the-middle attack)。
    SSH协议是如何应对的呢?
  • 四、口令登录
    如果你是第一次登录对方主机,系统会出现下面的提示:
    $ ssh user@host
    The authenticity of host 'host (12.18.429.21)' can't be established.
    RSA key fingerprint is 98:2e:d7:e0:de:9f:ac:67:28:c2:42:2d:37:16:58:4d.
    Are you sure you want to continue connecting (yes/no)?
    这段话的意思是,无法确认host主机的真实性,只知道它的公钥指纹,问你还想继续连接吗?
    所 谓"公钥指纹",是指公钥长度较长(这里采用RSA算法,长达1024位),很难比对,所以对其进行MD5计算,将它变成一个128位的指纹。上例中是 98:2e:d7:e0:de:9f:ac:67:28:c2:42:2d:37:16:58:4d,再进行比较,就容易多了。
    很自然的一个问题就是,用户怎么知道远程主机的公钥指纹应该是多少?回答是没有好办法,远程主机必须在自己的网站上贴出公钥指纹,以便用户自行核对。
    假定经过风险衡量以后,用户决定接受这个远程主机的公钥。
    Are you sure you want to continue connecting (yes/no)? yes
    系统会出现一句提示,表示host主机已经得到认可。
    Warning: Permanently added 'host,12.18.429.21' (RSA) to the list of known hosts.
    然后,会要求输入密码。
    Password: (enter password)
    如果密码正确,就可以登录了。
    当远程主机的公钥被接受以后,它就会被保存在文件$HOME/.ssh/known_hosts之中。下次再连接这台主机,系统就会认出它的公钥已经保存在本地了,从而跳过警告部分,直接提示输入密码。
    每个SSH用户都有自己的known_hosts文件,此外系统也有一个这样的文件,通常是/etc/ssh/ssh_known_hosts,保存一些对所有用户都可信赖的远程主机的公钥。
  • 五、公钥登录
    使用密码登录,每次都必须输入密码,非常麻烦。好在SSH还提供了公钥登录,可以省去输入密码的步骤。
    所谓"公钥登录",原理很简单,就是用户将自己的公钥储存在远程主机上。登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来。远程主机用事先储存的公钥进行解密,如果成功,就证明用户是可信的,直接允许登录shell,不再要求密码。
    这种方法要求用户必须提供自己的公钥。如果没有现成的,可以直接用ssh-keygen生成一个:
    $ ssh-keygen
    运行上面的命令以后,系统会出现一系列提示,可以一路回车。其中有一个问题是,要不要对私钥设置口令(passphrase),如果担心私钥的安全,这里可以设置一个。
    运行结束以后,在$HOME/.ssh/目录下,会新生成两个文件:id_rsa.pub和id_rsa。前者是你的公钥,后者是你的私钥。
    这时再输入下面的命令,将公钥传送到远程主机host上面:
    $ ssh-copy-id user@host
    好了,从此你再登录,就不需要输入密码了。
  • 六、authorized_keys文件
    远程主机将用户的公钥,保存在登录后的用户主目录的$HOME/.ssh/authorized_keys文件中。公钥就是一段字符串,只要把它追加在authorized_keys文件的末尾就行了。
    这里不使用上面的ssh-copy-id命令,改用下面的命令,解释公钥的保存过程:
    $ ssh user@host 'mkdir -p .ssh && cat >> .ssh/authorized_keys' < ~/.ssh/id_rsa.pub
    这 条命令由多个语句组成,依次分解开来看:(1)"$ ssh user@host",表示登录远程主机;(2)单引号中的mkdir .ssh && cat >> .ssh/authorized_keys,表示登录后在远程shell上执行的命令:(3)"$ mkdir -p .ssh"的作用是,如果用户主目录中的.ssh目录不存在,就创建一个;(4)'cat >> .ssh/authorized_keys' < ~/.ssh/id_rsa.pub的作用是,将本地的公钥文件~/.ssh/id_rsa.pub,重定向追加到远程文件 authorized_keys的末尾。
    写入authorized_keys文件后,公钥登录的设置就完成了。
  • 七、远程操作
    SSH不仅可以用于远程主机登录,还可以直接在远程主机上执行操作。
    上一节的操作,就是一个例子:
    $ ssh user@host 'mkdir -p .ssh && cat >> .ssh/authorized_keys' < ~/.ssh/id_rsa.pub
    单引号=bash中间的部分,表示在远程主机上执行的操作;后面的输入重定向,表示数据通过SSH传向远程主机。
    这就是说,SSH可以在用户和远程主机之间,建立命令和数据的传输通道,因此很多事情都可以通过SSH来完成。
    下面看几个例子。
    【例1】
    将$HOME/src/目录下面的所有文件,复制到远程主机的$HOME/src/目录。
    $ cd && tar czv src | ssh user@host 'tar xz'
    【例2】
    将远程主机$HOME/src/目录下面的所有文件,复制到用户的当前目录。
    $ ssh user@host 'tar cz src' | tar xzv
    【例3】
    查看远程主机是否运行进程httpd。
    $ ssh user@host 'ps ax | grep [h]ttpd'
  • 八、绑定本地端口
    既然SSH可以传送数据,那么我们可以让那些不加密的网络连接,全部改走SSH连接,从而提高安全性。
    假定我们要让8080端口的数据,都通过SSH传向远程主机,命令就这样写:
    $ ssh -D 8080 user@host
    SSH会建立一个socket,去监听本地的8080端口。一旦有数据传向那个端口,就自动把它转移到SSH连接上面,发往远程主机。可以想象,如果8080端口原来是一个不加密端口,现在将变成一个加密端口。
  • 九、本地端口转发
    有时,绑定本地端口还不够,还必须指定数据传送的目标主机,从而形成点对点的"端口转发"。为了区别后文的"远程端口转发",我们把这种情况称为"本地端口转发"(Local forwarding)。
    假定host1是本地主机,host2是远程主机。由于种种原因,这两台主机之间无法连通。但是,另外还有一台host3,可以同时连通前面两台主机。因此,很自然的想法就是,通过host3,将host1连上host2。
    我们在host1执行下面的命令:
    $ ssh -L 2121:host2:21 host3
    命 令中的L参数一共接受三个值,分别是"本地端口:目标主机:目标主机端口",它们之间用冒号分隔。这条命令的意思,就是指定SSH绑定本地端口2121, 然后指定host3将所有的数据,转发到目标主机host2的21端口(假定host2运行FTP,默认端口为21)。
    这样一来,我们只要连接host1的2121端口,就等于连上了host2的21端口。
    $ ftp localhost:2121
    "本地端口转发"使得host1和host3之间仿佛形成一个数据传输的秘密隧道,因此又被称为"SSH隧道"。
  • 十、远程端口转发
    既然"本地端口转发"是指绑定本地端口的转发,那么"远程端口转发"(remote forwarding)当然是指绑定远程端口的转发。
    还 是接着看上面那个例子,host1与host2之间无法连通,必须借助host3转发。但是,特殊情况出现了,host3是一台内网机器,它可以连接外网 的host1,但是反过来就不行,外网的host1连不上内网的host3。这时,"本地端口转发"就不能用了,怎么办?
    解决办法是,既然host3可以连host1,那么就从host3上建立与host1的SSH连接,然后在host1上使用这条连接就可以了。
    我们在host3执行下面的命令:
    $ ssh -R 2121:host2:21 host1
    R 参数也是接受三个值,分别是"远程主机端口:目标主机:目标主机端口"。这条命令的意思,就是让host1监听它自己的2121端口,然后将所有数据经由 host3,转发到host2的21端口。由于对于host3来说,host1是远程主机,所以这种情况就被称为"远程端口绑定"。
    绑定之后,我们在host1就可以连接host2了:
    $ ftp localhost:2121
    这里必须指出,"远程端口转发"的前提条件是,host1和host3两台主机都有sshD和ssh客户端。
  • 十一、SSH的其他参数
    SSH还有一些别的参数,也值得介绍。
    N参数,表示只连接远程主机,不打开远程shell;T参数,表示不为这个连接分配TTY。这个两个参数可以放在一起用,代表这个SSH连接只用来传数据,不执行远程操作。
    $ ssh -NT -D 8080 host
    f参数,表示SSH连接成功后,转入后台运行。这样一来,你就可以在不中断SSH连接的情况下,在本地shell中执行其他操作。
    $ ssh -f -D 8080 host
    要关闭这个后台连接,就只有用kill命令去杀掉进程。
  • 十二、参考文献
文章出处:http://www.ruanyifeng.com/blog/2011/12/ssh_remote_login.html
 http://www.ruanyifeng.com/blog/2011/12/ssh_port_forwarding.html
------------------------------
SSH指南/SSH配置入门
注意:由于openssh是开源软件,各版间的配置方法和设置参数可能会不同,所以设置时要
  以最新版的手册为准,不要硬套书本的设置。
  
  
  第一章 SSH简介
  ssh(secure shell)是一种通用,功能强大的基于软件的网络安全解决方案,计算机每次向网络
  发送数据时,SSH都会自动对其进行加密。数据到达目的地时,SSH自动对加密数据进行
  解密。整个过程都是透明的。它使用了现代的安全加密算法,足以胜任大型公司的任务繁重
  的应用程序的要求。
  
  SSH协议内容涉及认证AUTHENTICATION,加密ENCRYPTION,和网络上传输数据的完整
  性INTEGRITY。
  
  SSH特性概述
  1、远程登录
  $ ssh -l root host.example.com
  2、安全文件传输
  $ scp myfile metoo@secondacount.com
  3、安全执行远程命令,能确保传输的数据安全。
  4、密钥和代理
  基于密钥的认证方法不用记住多个帐号密码。
  5、访问控制,能授权别人访问自已帐号。
  6、端口转发
  $ ssh -L 3002:localhost:119 xxx.xxx.com
  
  相关安全技术
  rsh命令族,rsh,rlogin and rcp。连接不加密,认证模型十分脆弱。
  PGP加密程序。它是基于文件的。
  Kerberos认证系统,用于网络可能被监视,而且计算机不是中心控制的环境。基于麻省理工
  学院的Athena项目。它SSH不是,SSH是轻量级的,容易部署。Kerberos使用前必须构建
  一些重要基础。
  IPSEC,Internet安全协议。
  SRP,安全远程密码协议,是Stanford大学开发的。是一种专用的认证协议。
  SSL,安全套接字。
  stunnel,是一种SSL工具,它为UNIX环境现有的基于TCP的服务(POP,IMAP等)增加
  SSL保护,而不用修改服务器源程序。
  
  第二章 SSH客户端的基本用法
  最常用功能,1、经由安全连接登录到远程计算机。2、通过安全连接在计算机间拷贝文件。
  
  当你第一次连接SSH服务器时,出现问答时要回答“yes”,把已知名主机的密钥的公共部
  分拷贝一份存在本地。之后你每次连接这台服务器,就用这个公钥来验证远程主机。最好是
  能在首次连接前就能获得这个公钥,否则第一次连接服务器时你可能已受到中间人攻击。
  
  使用密钥进行认证,SSH支持公钥认证,可以使用加密密钥,密钥比密码更安全。
  SSH证书使用一对密钥,一个私钥,一个公钥,私钥只保存你独有的一些秘密信息。SSH
  用其向服务器证明自已的身份。公钥是公开的,可以随便将其放入SSH服务器上自已的帐
  号中,在认证时,进行私钥和公钥协商,如果匹配,那么身份就得以证明,认证就成功。
  
  在使用公钥认证以前,首先要进行一些设置:
  1、需要一对密钥,还需要使用一个口令来保护自已的私钥。
  使用ssh-keygen程序生成一对密钥。如果不存在SSH目录,程序为自动创建本地SSH目录
  ~/.ssh,并将所生成的密钥分成两个文件存储,公有部份identity.pub,私有部分identity,或
  id_dsa_1024_a,id_dsa_1024_a.pub(ssh2)。
  2、需要在SSH服务器上安装自已的公钥。
  通过配置SSH目录中的一个文件实现,对于SSH1 AND OPENSSH来说该文件是
  ~/.ssh/authorized_keys。对SSH2来说是~/.ssh2/authorization。OPENSSH中的SSH-2连接自
  3.0版本起也一同使用authorized_keys文件。3.0版本前的使用authorized_keys2。把用户本
  地机器生成identity.pub文件内容加入其中。对SSH2来说,用户需编辑两个文件,一个客
  户端一个在服务器端,
  在客户端,要创建或编辑文件~/.ssh2/identification并在其中插入一行,说明自已的私钥文件
  名: IdKey id_dsa_1024_a.
  在服务器端,要创建或编辑文件~/.ssh2/authorization,该文件包含有公钥信息,每行一个,
  但和SSH1的authorized_keys文件不同(authorized_keys中包含有公钥的拷贝),authorization
  中只给出公钥文件名:Key id_dsa_1024_a.pub。最后,把这个文件从本地机器上拷贝到服务
  器~/.ssh2中。为安全起见,要确保ssh目录的安全,只有所有者才有权写入。如果远程用户
  的SSH配置文件的权限设置不当,服务器可能会拒绝进行认证。
  
  公钥认证比密码认证更安全,因为:
  1、 公钥认证需要两个加密部份(磁盘上的identify文件和用户头脑中的口令),入侵都必须
  2、 具备两种条件才行。密码认证只需要一个部份,那就是密码,它可能更容易被窃取。
  3、 在公钥认证中,口令和密钥都不用发给远程主机,只要把前面讨论的认证者发给远程主
  4、 机就可以了,因此,并没有秘密信息传出客户端。
  3、机器生成的密钥是不可能猜测出来的,而人生成的密码容易受到字典攻击。
  通过禁用密码认证并只允许使用密钥认证能极大提高主机的安全性。
  
  如果要修改密钥
  如果已经生成一个密钥对,并把公钥拷贝到多个SSH服务器上了,用户有一天决定修改自
  已的身份,因为再运行ssh-keygen。这样,就会覆盖identify and identify.pub文件,用户之
  前的公钥就没用了,必须把新公钥再次拷贝到各个服务器上。这是很头疼的,所以建议:
  1、 不能局限于仅仅使用一个密钥对,可随意生一此密钥对,将其保存在不同的文件中,并
  2、 将其用作不同的用途。
  3、 如果只是想修改口令,就不必重新生成一个密钥对,ssh-keygen有一个命令行选项可以
  4、 替换现有的密钥口令。ssh1 and openssh是-p,对于ssh2是-e。这样,因为私钥没变,所以
  5、 公钥依然不效,中需使用新口令对私钥进行解密就可以了。
  
  ssh代理
  它可以把私钥保存在内存中,为认证提供服务,不用重复输入密码。直到用户退出为止。代
  理程序是ssh-agent。可手工运行也可编辑~/.login 或~/.xsession来自动运行。
  $ ssh-agent $SHELL 其中SHELL是用户登录shell的环境变量。运行该命令后,打开另外
  一个shell,在这个shell中可以访问代理。
  接着用ssh-add命令装入私钥。这样,使用ssh and scp命令就不用再提醒输入口令了。口令
  装入内存中。如果用户正运行x window系统,并设置了DISPLAY环境变量,而标准输入
  不是终端,那么ssh-add就使用一个图形化X程序ssh-askpass来读取口令。要强制ssh-add
  使用X来读取口令,请在命令行中输入ssh-add < /dev/null。
  -l 参数显示内存中的密钥
  -d 参数从代理中删除密钥 $ ssh-add -d ~/.ssh/id_xxx.pub
  -D 是删除所有密钥
  -t 对加载的密钥设置超时时间,超时代理将自动卸载密钥。
  -L -U 对代理进行加锁和解锁,当你离开计算机而不想退出登录时有用。
  
  
  代理转发
  可能通过代理转发功能,可以用SCP把文件从远程SSH服务器上拷贝到第三方SSH主机上。
  条件是你在第三方SSH主机上必须有一个帐号。具体操作是这样的:
  1、 在本地主机上运行命令:# scp pat@shell.isp.com:print-me
  2、 psmith@other.host.net:other-print-me
  2、这个scp进程与本地代理进行联系,并让用户和shell.isp.com进行认证。
  3、自动在shell.isp.com上执行第二个scp,用来把文件拷贝到other.host.net主机上。
  3、 由于启用了代理转发(SSH1 AND SSH2默认是打开的,openssh默认是关闭的),因此
  4、 shell.isp.com上的SSH服务器就充当一个代理。
  5、第二个scp进程通过联系shell.isp.com上的代理试图让用户和other.host.net进行认证。
  5、 shell.isp.net上ssh服务器秘密与用户的本地代理进行通信,从而构建出一个认证者来提
  6、 供用户的证书并将其传回服务器。
  7、服务器为第二个scp进程验证用户的身份,other.host.net上的认证获得成功。
  8、开始拷贝文件。
  由于代理转发不会把私钥发送到远程主机上,而是把认证返回第一台机进行处理,因此密钥
  是安全的。
  
  不用密码或口令进行连接方式
  1、使用代理的公钥认证。
  2、可信主机认证。
  3、Kerberos认证。
  在后文中将会讨论这些方式的优缺点。
  
  sftp
  它是在SSH上的一个独立文件传输工具,操作与ftp类似,可以在一个会话中调用多个命令
  进行文件拷贝和处理,而scp每次调用时都要打开一个会话。sftp不区分ascii and binary传
  输模式,只使用二进制模式,因此,如果使用它在windows and unix之间拷贝ascii文件,
  那么就不能正确转换行结束符。
  
  第三章 SSH内幕
  SSH协议的主要特性和优点:
  1、 使用强加密技术来保证数据的私密性。端到端通信用随机密钥进行加密,随机密钥为会
  话进行安全协商,会话结束后被丢弃。支持的算法有ARCFOUR,Blowfish,DES,IDEA,3DES等。
  2、通信完整性,确保通信不会被修改。SSH-2基于MD5 AND SHA-1的加密hash算法。
  3、认证,即发送者和接收者的身份证明。客户机和服务器双向认证。
  4、授权,即对账号进行访问控制。
  5、使用转发或隧道技术对其它基于tcp/ip的会话进行加密。支持三种转发,tcp端口转发,
  X转发,代理转发。
  
  SSH可以防止的攻击
  1、网络窃听,SSH通信是加密的,即使截获会话内容,也不能将其解密。
  2、名字服务和IP伪装,SSH通过加密验证服务器主机身份可避免这类风险。
  3、连接劫持,SSH的完整性检测负责确定会话在传输过程是否被修改,如果被修改过,就
  关闭连接。
  4、 中间人攻击,SSH利用两种方法防止这种攻击,第一种是服务器主机认证。除非攻击者
  已经成功攻击了服务器主机,获得服务器的私有主机密钥。第二种是限制使用容易受到
  这种攻击的认证方法,密码认证容易受到中间人攻击,而公钥和基于主机的/RhostsRSA
  则对中间人攻击可以免疫。
  5、插入攻击,这种攻击可以客户和服务器之间发送的正文数据流之间插入任意数据。ssh1
  1.2.25后和openssh的所有版本都专门进行了设计,来检测并防止这种攻击。这种检测程序
  增大了插入攻击的难度,但是并不能完全防止。ssh2使用强加密完整性检测手段来防止这个
  问题。可以用3DES算法来防止这种攻击。
  
  SSH不能防止的攻击
  1、 密码崩溃,密码认证是一种脆弱的认证形式,尽量使用公钥认证方式。如果必须要密码
  认证,可考虑使用S/Key之类的一次性密码机制。
  2、 IP AND TCP攻击,由于SSH是在TCP之上进行操作的,因此容易受到针对TCP和IP
  缺陷而发起的攻击。SYN flood,TCP不同步和TCP劫持等。只能通过更低层的防护措施
  来保护。
  3、流量分析。
  4、隐秘通道。
  5、粗心大意。安全是一个过程,而不是一个产品,不要认为装上SSH就安全了。
  
  第四章 SSH的安装和编译时配置
  
  第五章 服务器范围的配置
  sshd可以在三个层次上进行配置,第一层次是上面的安装和编译时配置;第二层次是本章的
  服务器范围配置;第三层次是每账号配置(第八章),前者是服务器编译时就指定了包含哪
  些特定功能,不包含哪些功能,后者则是由终端用户来修改自已账号所使用的服务器的行为。
  
  以普通用户身份运行SSH服务器
  1、得到管理员许可。
  2、生成一个主机密钥。
  $ ssh-keygen -N '' -b 1024 -f ~/myserver/hostkey 生成hostkey and hostkey.pub两个文件
  3、选择端口号。 要选择大于或等1024的端口,因为只有超级用户才有权使用小于
  1024的端口 。
  4、创建服务器配置文件(可选) 可创建自已的配置文件,否则,服务就使用内建的特性或使
  用服务器范围的配置文件。
  启动服务器方式:$ sshd -h ~/myserver/hostkey -p 2345 -f ~/myserver/config
  由普通用户运行的服务器有一些缺点:
  1、由于不是由root的uid下运行,因此只能连接到用户自已的账号上。
  2、它需手工调用,不能自启动。
  3、 日志用户没权看到,因为服务器把它写到syslog日志系统中,但可用调试模式运行服务
  4、 器,这样信息就显示在终端机上。
  
  服务器配置文件
  SSH1 AND OPENSSH的配置文件通常是/etc/sshd_config,而SSH2的配置文件通常是
  /etc/ssh2/sshd2_config。
  
  以非缺省的配置文件来调用sshd,可以使用命令 -f 选项。$ sshd -f /usr/local/ssh/my_config。
  
  以*号作为标号的语名都会被sshd忽略。
  
  修改完配置后,修改不会马上影响到服务器,可重启服务器或发送SIGHUP信号。$ kill -HUP
  `cat /etc/sshd.pid`
  
  如果在命令行改动了配置,用SIGHUP信号重启服务器不能覆盖命令行的配置,它的优先
  级高。
  
  主机密钥,sshd主机密钥向SSH客户端唯一地标识SSH服务器。主机密钥保存在一对文件
  中,一个文件包含私钥,一个文件包含公钥。对于SSH1 AND OPENSSH,它是
  /etc/ssh_host_key。文件位置可用HostKey关键字修改 HostKey /usr/local/ssh/key。服务器的
  公钥保存在.pub文件中。
  OPENSSH服务器有一个SSH-2的主机密钥,缺省是在/etc/ssh_host_dsa_key。其位置可用
  HostDsaKey /usr/local/openssh/key2修改。
  
  对于SSH2,如果服务器是由超级用户运行,缺省私钥文件是/etc/ssh2/hostkey。如果是其它
  用户运行,则在~/.ssh2/hostkey。可用HostKeyFile /etc/local/ssh/key修改。公钥是hostkey.pub
  文件,可用publicHostKeyFile关键字修改。
  
  可以用命令行选项指定私钥文件:$ sshd -h /usr/local/ssh/key。
  
  随机数种子文件
  如果用户的系统中有一个随机位源,如/dev/urandom,那么OPENSSH就不能创建随机数种
  子文件。
  
  服务器配置文件
  通常是/etc/sshd_config /etc/ssh2/ssh2_config,可以用-f 选项重新指定其配置文件。可用于一
  台机器运行多个sshd的情况。
  
  每账号认证文件。~/.ssh/authorized_keys 。
  
  
  文件权限
  由于配置文件的权限设置错误,会降低系统的安全性,所以可以设置StrictModes YES/NO
  关键字,对sshd的重要文件和目录的权限进行检查,如果检查失败,服务器就拒绝对该用
  户的SSH连接。
  
  在多宿主主机上,使用ListenAddress xxx.xxx.xxx.xxx来限制SSH只监听一个网络接口。
  
  空闲连接时间,IdleTimeout xx 如果是0代表什么都不做,保持连接。否则,超时就断开连
  接,可以用s,m,h,d,w表示。
  
  KeepAlive YES/NO 可以断开失效的连接,比如客户端崩溃。
  
  失败的登录
  LogingGraceTime 60 限定用户必须在60秒内成功进行认证。 0值表禁用。命令行选项用
  -g
  
  PasswordGuesses 5 如果连接请求使用密码认证,那么sshd2就只允许客户端尝试五次。
  (SSH2)
  
  限制并发连接
  MaxConnections 32 最大32个连接(SSH2)
  
  逆向IP映射
  SSH2服务器可以根据客户端地址进行逆向DNS查询,以确保客户端的地址就是这个地址。
  如果检查失败,连接拒绝。
  RequireReverseMapping yes (ssh2)
  
  转发
  AllowTcp-Forwarding yes
  X11Forwarding yes
  
  服务器密钥生成
  该密钥用来对客户端/服务器之间的通信进行保护。是临时的,永远不会保存在磁盘上。服
  务器在启动时生成这个密钥。并以固定的周期重新生成。缺省长度是768位,最小为512,
  可以ServerKeyBits 2048 指定长度。用KeyRegenerationInterval 1200指定周期。 命令行选
  项:-k
  
  加密算法
  Ciphers any 允许所有支持算法。其它算法包括
  3des-cbc,blowfish-cbc,twofish-cbc,arcfour,none
  
  mac算法
  MAC关键字可以让用户选择sshd2进行完整性检测所使用的算法,称为消息认证代码。用
  于sshd2的有hmac-sha1,hmac-md5,hmac-md5-96。
  
  在OPENSSH中,用户可以用Protocol关键字选择支持SSH-1 AND SSH-2,1 代表SSH-1,2 代
  表SSH-2, 1,2 代表都支持。
  
  允许用户登录:认证和访问控制
  1、认证负责对发起连接请求的用户的身份进行验证。
  密码认证
  PasswordAuthentication yes AllowedAuthentications password (ssh2)
  公钥认证
  RSAAuthentication yes (ssh1,openssh/1)
  AllowedAuthentications publickey (ssh2)
  DEAAuthentication yes (openssh/2)
  Rhosts认证,可信主机认证通过检查远程主机名和相关用户名来实现对客户端的身份认证。
  RhostsAuthentication yes (ssh1,openssh)
  IgnoreRhosts yes (ssh1,ssh2,openssh)不使用系统的hosts.equiv and ~/.rhosts,使用SSH专用
  的/etc/shosts.equiv and ~/.shosts
  强可信主机认证。
  RhostsRSAAuthentication yes ssh1,openssh
  AllowedAuthentications hostbased ssh2
  提取已知名主机的公钥
  UserKnownHosts no ssh2
  IgnoreUserKnownHosts yes openssh
  PGP认证
  Kerberos认证
  S/key认证
  SecurID认证
  PAM认证
  
  2、访问控制负责允许或禁止来自特定用户、机器在或INTERNET域的SSH连接到服务器
  上。
  通常,只要设置正确,任何账号都可以接收SSH连接,这种访问权限可以使用服务器关键
  字AllowUsers and DenyUsers覆盖。
  AllowUsers smith
  如果配置文件中单独出现一个AllowUsers,后面没有任何内容,就表示禁止所有没提到的用
  户连接,如果没有AllowUsers这个关键字,则所有用户都可连接。DenyUsers表示禁止连接。
  可用通配符,
  
  可以用组访问控制AllowGroups DenyGroups
  
  主机名访问控制
  AllowHosts hostname
  DenyHosts hostname
  
  超级用户的访问控制
  sshd对超级用户专门使用一种特殊的访问机制,PermiRootLogin来允许或禁止使用SSH来
  访问root账号。
  
  显示用户的欢迎信息
  PrintMotd yes/no default is yes
  
  显示邮件信息
  CheckMail yes/no default is yes
  
  空密码
  PermitEmptyPasswords yes/no 如果使用密码认证,并且有个账号没有设定密码,那么服务
  器就可以拒绝访问这个账号
  
  如果系统中存在/etc/nologin,那么sshd就只允许root用户登录,其它都不能登录。因此,touch
  /etc/nologin是把访问权只授给系统管理员的一种快速方法。这样并不需要重新配置ssh。也
  不需要重启ssh。
  
  子系统
  定义和调用远程命令的一个抽象层,用户可以通过在客户端命令行中给出命令来调用远程命
  令,如:ssh server.examply.com /bin/tar c /home 这个命令调用tar,远程把/home拷贝到磁带上。
  子系统是服务器机器上预定义的一组远程命令,这样就可以方便地执行。在服务器配置文档
  中定义:subsystem backups /bin/tar c /home,要在服务器上运行该命令,可以使用 -s 选项。
  ssh -s backups server.example.com。缺省情况下,sshd_config中定义了一个子系统,subsystem
  sftp 。不要删除这个子系统,这是scp2和sftp必须的。
  
  日志
  Fascisl Logging mode 把调试信息打印到系统日志文件中,可以使用FascistLogging关键字
  启用。
  调试模式 可以使用-d命令选项启用
  安静模式 只能输出严重错误,而不能输出 普通日志,可以使用QuietMode关键字或-q
  命令行启用。
  openssh中的日志配置关键字是SyslogFacility and LogLevel。SyslogFacility设置syslog的
  facility(KERN,DAEMON,USER,AUTH,MAIL等),LogLevel记录日志提供的详细程度,该
  值从低到高顺序是:QUIET,FATAL,ERROR,INFO,VERBOSE,DEBUG,使用DEBUG会侵犯用
  户的隐私权,这个级别只能用于诊断,而不能用于普通操作。
  
  
  第六章 密钥管理与代理
  一个身份标识由两部份组成,分别称为私钥(Private Key)和公钥(Public Key),合称一个
  密钥对。
  
  SSH1,SSH2 AND OPENSSH身份标识文件的格式各不相同。
  SSH1缺省设置中,私钥存储在文件identity中,公钥存储在文件identity.pub中。这个密钥
  对存放在~/.ssh目录下,在使用前,把公钥拷贝到服务器上的一个认证文件里,如SSH1 AND
  OPENSSH中的~/.ssh/authorized_keys,此后,当客户请求连接到你的服务器上的帐号时,就
  会用一个私钥作为证明身份的标识,服务器则在authorized_keys文件中寻找与之匹配的公
  钥。
  
  SSH2密钥对文件的命名通常是根据该密钥使用的加密算法的性质来起的,例如一个用DSA
  加密的1024位密钥生成时其缺省文件名是id_dsa_1024_a and id_dsa_1024_a.pub。用户必须
  把私钥放在identification文件中,缺省是~/.ssh2/目录,一个私钥在这个文件中占一行,在公
  钥认证中,每一行的开头都有一个关键字IdKey,后跟一个私钥文件名。如:
  IdKey id_dsa_1024_a
  IdKey my-other-ssh2-key
  在服务器端的认证文件~/.ssh2/authorization中,SSH2不包含公钥的实际拷贝,只是把公钥
  文件列出来,前面用关键字kEY标识。如:
  Key id_dsa_1024_a.pub
  Key something-else.pub
  这样维护起来更容易,更方便。
  
  OPENSSH对SSH-1连接使用的标识和授权文件与SSH1完全相同,对于SSH-2连接,缺省
  的密钥则存储在~/.ssh/id_dsa(private key)和~/.ssh/id_dsa.pub(public key)中,服务器上的授权
  文件是~/.ssh/authorized_keys。
  
  创建身份标识用ssh-keygen命令。
  
  OPENSSH的ssh-keygen可以支持SSH1中相应程序的所有功能和选项,它还新增了为SSH-2
  连接生成DSA密钥的能力。
  $ ssh-keygen -t dsa -b 1024
  -e -x 选项可把OPENSSH格式的密钥存储格式转换成SSH2格式 (直接回车,按提示输入转
  换文件名)
  -i -X 选项把SSH2格式的密钥转换成OPENSSH格式。这样可用SSH2客户端连接
  OPENSSH服务器。(直接回车,按提示输入转换文件名)
  -y 如果不小心删掉了OPENSSH的公钥,可用-y恢复。
  -l 可计算出公钥的指纹,指纹是鉴别位置不同的两个密钥是否相同的常用的一种密码学技
  术。这项技术用于不可能逐位对比两个密钥的情况。OPENSSH AND SSH2都能计算指纹。
  它是根据密钥计算出来一个长度较短的值,它是原理与校验和类似,用于验证一串信息(在
  我们的例子中是密钥)的不可替换性。
  
  启动代理
  1、单shell方式,使用当前登录的shell. $ eval `ssh-agent`
  2、子shell方式,派生出一个子shell,并继承父shell的某些环境变量。 $ ssh-agent $SHELL
  不要想当然运行 $ ssh-agent,这样客户端是无法有代理联系的。删除代理用kill命令就可以
  了。
  
  SSH-1 与 SSH-2代理的兼容性
  SSH-1的代理不能处理SSH-2的代理,SSH-2的代理却可以处理SSH-1的代理请求。
  
  第七章 客户端的高级用法
  $ ssh -a -p 220 -c blowfish -l sally -i myself server.example.com 可通过配置文件简化命令
  输入
  
  Host myserver
  ForwardAgent no
  Port 220
  Cipher blowfish
  User sally
  IdentifyFile myself
  HostName server.example.com
  配置了该文件后,就可以在客户端简单地输入
  $ ssh myserver
  
  全局文件和本地文件
  全局文件通常是由管理员创建的,用来维护整台计算机上的客户行为。该文件通常位于
  /etc/ssh_config or /etc/ssh2/ssh2_config。每个客户也可以在自已账号中创建本地客户配置文
  件,通常是~/.ssh/config or ~/.ssh2/ssh2_config。本地配置文件优先级高于全局配置文件。命
  令行选项的优先级又高于本地配置文件。
  
  scp有关命令参数
  -r 递归拷贝目录
  -p 保持文件权限和时间戳
  -u 拷贝完成后删除源文件
  -d 防止覆盖文件
  -n 描述操作
  -q 不显示统计信息
  
  
  第八章 每账号服务器配置
  这种配置可以让SSH服务器区分每个服务器上的各个用户。利用服务器目标账号的认证文
  件(authorized_keys)配置。局限有两点,它不能覆盖编译时配置和服务器范围配置所采用
  的安全措施,第二,如果使用公钥认证,每账号配置是十分灵活的,如果采用可信主机和密
  码认证,提供的选择范围就很小。
  
  基于公钥的配置
  1、认证文件的完全格式 依次包含三项内容,一些选项,公钥和注释。多个选项用逗号分
  开。
  2、用于限制客户端可以在服务器上调用的程序的强制命令。如客户端请求执行/bin/ls命令,
  而服务器端强制命令却运行/bin/who命令,它十分有用,可用于加强安全性,了为授权提供
  方便。如要让你的助手每次连接上来都运行email命令程序pine,则可以这样:
  command= "/usr/local/bin/pine" ...key...。最多可给每个密钥关联一个强制命令,要关联多个命
  令可把这些命令放入远程主机的一个脚本中,并将该脚本作为强制命令运行。如果强制命令
  有shell出口,那会存在安全问题,等于没有强制,客户可以运行任何程序。以下规则可以
  用来判断一个程序是否适合用作强制命令。
  a、 避免使用具有shell出口的程序(如:文件编辑器vi,Emacs; 分页程序 more,less;调用分
  b、 页的man,新闻阅读程序rn,邮件阅读程序pine以及调试程序adb,非交互的程序find,xargs
  c、 等)。
  b、避免使用编译器,解释器或其它可以让用户生成并运行任意执行代码的程序。
  c、可创建或删除文件的程序,如cp,mv,rm,scp,ftp等。
  d、避免使用setuid or setgid的程序,特别是setuid 是root的程序。
  d、 如果使用脚本作为强制命令,就要遵循编写安全脚本的传统规则,在一个脚本之内,要
  限制使用相对路径作为搜索路径,应该使用绝对路径来调用所有的程序;不要盲目地把
  用户提供的字符串作为命令来执行;不要让脚本执行任何setuid的工作。不要调用具有
  shell出口的程序。
  e、考虑使用受限shell。
  f. 为一个单独的、专用的SSH密钥(不要用你登录的那个密钥)关联一个强制命令。这样
  不会影响你的登录能力就可以方便地禁用该密钥。
  g、禁用不必要的SSH特性。如no-port-forwarding,no-agent-forwarding,no-pty(禁用tty分配)。
  几个常用的强制命令介绍:
  使用定制消息拒绝连接:command="/bin/echo Sorry,buddy,but you've terminated!" ...key... 千万
  不要用more and less之类的分页程序
  显示命令菜单:利用脚本
  检查客户端的原始程序:command="/bin/echo you tried to invoke
  $SSH_ORIGINAL_COMMAND" ...key... $SSH_ORIGINAL_COMMAND环境变量保存着
  客户连接时运行的原始命令。
  限制客户端的原始命令,创建一个脚本,该脚本根据$SSH_ORIGINAL_COMMAND内容选
  择不同的操作。
  把客户端的原始命令记录在日志中:也是根据$SSH_ORIGINAL_COMMAND变量来做的一
  个脚本。脚本内容如一:
  #!/bin/sh
  if [ -n "$SSH_ORIGINAL_COMMAND" ]
  then
  echo "`/bin/date`: $SSH_ORIGINAL_COMMAND" >> $HOME/ssh-command-log
  exec $SSH_ORIGINAL_COMMAND
  fi
  
  3、限制来自特定主机的连接。由from选项完成。from="client.example.com" ...key...。强制
  连接必须来自client.example.com。否则断开。from="!client.example.com" ...key...表示拒绝该
  地址的连接。支持通配符。SSH2不支持该功能。但可以通过$SSH2_CLIENT变量提取客户
  ip,编写强制命令脚本达到同样效果。
  4、为远程程序设置环境变量。environment="EDITOR=emacs" ...key...,为每个连接修改默认的
  环境变量。
  5、设置空闲超时时间,这样如果客户端用户不再发送数据就强制将其断开。idle-timeout=5m,
  该选项会覆盖服务器范围配置。
  6、对到达的SSH连接禁用某些特性,例如端口转发和tty分配。禁用tty分配会使客户端没
  有交互会话的能力。$SSH_TTY变量可显示tty情况。
  
  用户的rc文件
  ssh服务器会在每个连接到达时调用shell脚本/etc/sshrc,用户可把一些登录后想运行的脚本
  写到这个文件中。用户可以在自已的目录下定义类似的脚本,如果有自定义的~/.ssh/rc则
  /etc/sshrc则不会执行。
  
  第九章 端口转发与X转发
  使用SSH对其它应用程序在别的TCP端口上建立的TCP/IP传输进行加密和解密,这一过
  程称为端口转发,其绝大多数操作都是透明的,功能非常强大。TELNET,SMTP,NNTP,IMAP
  和一些基于TCP的不安全协议都可变得安全,只要将其连接通过SSH转发即可。端口转发
  有时又叫做隧道传输。
  例子:一个运行IMAP的服务器S,在家里的主机H上运行一个email程序,现在想用ssh
  保护IMAP连接。
  $ ssh -L2001:localhost:143 S
  -L 表明是本地转发,,上面这命令可完成登录到S的功能,现在的这个SSH会话同时将H
  的2001端口转发到S的143端口,在退出会话之前一直有效。并告知email程序使用被转
  发的端口,通常邮件程序连接服务器的143端口,即套接字 (S,143)。现在要令其连接
  本地主机H自已的2001端口,也就是套接字(localhost,2001)。创建本地转发时可以不用-L
  选项,而在客户端配置文件中用LocalForward关键字。
  LocalForward 2001 localhost:143 ssh1 openssh
  LocalForward "2001:localhost:143" ssh2
  
  -g 选项和GatewayPorts yes/no关键字可以配置除本地主机外的机器是否能使用本地的端口
  转发功能。出于安全问题,该禁止这个功能。
  
  远程转发端口与本地转发几乎完全相同,只是方向相反。此时服务器在本地,转发连接由远
  程主机发起。假设你已登录进服务器S。则
  $ ssh -R2001:localhost:143 H
  -R代表远程转发。命令执行后,一条从远程主机H的2001端口到服务器S的143端口的安
  全隧道就建立起来了。H上的任何程序都可以通过连接(localhost,2001)来使用此安全隧道。
  而在客户端配置文件中用RemoteForward关键字.
  RemoteForward 2001 S:143 ssh openssh
  RemoteForward "2001:S:143" ssh2
  
  $ ssh -o ClearAllForwardings=yes server.example.com 阻止第二条命令建立隧道
  
  本地转发与远程转发
  在本地转发中,应用程序客户端与监听端同SSH客户端在一起,应用程序服务器与连接端
  同SSH服务器在一起。
  在远程转发中,应用程序客户端与监听端同SSH服务器在一起,应用程序服务器与连接端
  同SSH客户端在一起。
  
  无远程登录的端口转发,连接时带-f参数。一次性转发用-fo,ssh1与openssh不支持这个功
  能,但可用以下语句实现:
  $ ssh -f -L2001:localhost:143 server sleep 10
  
  终止
  如果一个SSH会话现在还在活动当中,终止会出错。在SSH2中,如果退出有活动转发连
  接的会话,该会话会依然打开,但会转到后台运行。直到转发连接终止。ssh1 and openssh
  与此相反,如果要断开还在活动的会话,会出现警告,仍然在前台运行。
  
  TIME_WAIT问题。在某些情况下,TCP连接断连时,其一端的套接字在很短一段时间内变
  得不可用,所以在断连过程结束前不能把该端口用于TCP转发。
  
  
  
  
  
  
  第十章 推荐配置
  服务器范围配置
  1、禁用其它访问方式。
  关掉r-命令,方法如下:删除/etc/hosts.equiv文件,或改为只读空文件。禁用rshd,rlogind and
  rexecd,通过修改inetd.conf文件。
  2、/etc/sshd_config配置
  HostKey /etc/ssh_host_key
  PidFile /etc/sshd.pid
  RandomSeed /etc/ssh_random_seed
  
  StrictModes yes 要求用户保护其与SSH有关的文件及目录
  Umask 0077 保证所有SSHD1创建是文件和目录都只能由其所有者(SSHD 运行的
  UID)读取
  
  port 22
  ListenAddress 0.0.0.0
  IdleTimeout 15m 15分钟空闲超时
  KeepAlive yes 客户机死机时连接将会终止,而不会长期挂起。
  
  LoginGraceTime 30 登录时成功认证的时限为30秒。
  
  ServerKeyBits 768 服务器密钥长度
  KeyRegenerationInterval 3600 服务器密钥一小时重新生成一次
  
  PasswordAuthentication no 禁用密码认证
  RhostsAuthentication no 禁用可信主机认证
  RhostsRSAAuthentication no 禁用增强可信主机认证
  RSAAuthentication yes 启用公钥认证
  
  IgnoreRhosts yes 完全禁止SSHD使用.rhosts文件
  IgnoreRootRhosts yes
  
  UseLogin no 禁用UseLogin,防止万一使用了其它登录程序
  
  AllowHosts xxx 根据需要设置
  SilentDeny yes 任何被DenyHosts拒绝的连接都不会向用户返回消息,不必告诉攻击
  者发生了什么,可以增加了排错的难度。
  
  PermitRootLogin nopwd 允许超级用户通过SSH连接,但不能用密码认证
  
  FascistLogging no 禁用FascistLogging日志方式,因为它会在日志中记录用户特定信息,对
  攻击者有用。
  QuietMode no 禁用QuietMode日志方式,使用日志更详细,敏感度更低
  
  AllowTcpForwarding yes 允许tcp端口转发和X转发,保护其它的tcp连接
  X11Forwarding yes
  
  3、/etc/ssh2/sshd2_config配置
  HostKeyFile /etc/ssh2/hostkey
  PublicHostKeyFile /etc/ssh2/hostkey.pub
  RandmoSeedFile /etc/ssh2/random_seed
  
  UserConfigDirectory
  IdentityFile
  AuthorizstionFile
  
  StrictModes yes
  
  port 22
  listenAddress 0.0.0.0
  KeepAlive yes
  RequireReverseMapping no
  
  LoginGraceTime 30
  
  由于sshd2没有设置服务器密钥的位数的关键字,用户得在启动时使用 -b 选项 $ sshd2 -b
  1024 ....
  
  AllowedAuthentications publickey
  RequiredAuthentications publickey
  
  IgnoreRhosts yes
  UserKnownHosts no 禁用该项可防止用户给未知主机提供信任权限。
  
  PermitRootLogin nopwd
  
  
  Ciphers any 不能选none
  
  
  QuietMode no
  VerboseMode yes
  
  Ssh1Compatibility no 禁用SSH-1兼容模式
  #Ssh1Path /usr/local/ssh1/sshd1 出于实用原因,也可以启用此模式,之前要指明ssh1服
  务器可执行文件位置
  
  4、每账号配置
  对于SSH1 AND OPENSSH,~/.ssh/authorized_keys中的每一个密钥都必须用适当的选项进
  行限制,from选项限制只能从特定的主机访问特定的密钥。例如,假设文件中包含你家那
  台pc(myhome.isp.net)的公钥,而其它机器根本不可能用那个密钥来认证,我们就可以明确
  限定这一关系:from = "myhome.isp.net" ...key...。还要对适当的密钥设置空闲超时时间:from
  = "myhome.isp.net" ,idle-timeout=5m ...key...。
  最后,考虑每一个密钥是否需要对到达的连接使用端口转发,代理转发以及分配tty等,如
  果不需要,就可以分别用no-port-forwarding,no-agent-forwarding and no-pty禁用这些特性。
  
  5、密钥管理
  至少创建1024位长的用户密钥,并用好的口令对密钥进行保护。
  
  6、客户端配置
  离开正在运行的ssh客户端时,一定要用密码保护。
  在客户端配置文件中启用某些安全功能,并将其设置为最强
  Host *
  FallBackToRsh no 禁止使用不安全的r-命令(ssh2)没有这个问题。
  UseRsh no
  GatewayPorts no 禁止远程客户端连接本地的转发端口
  StrictHostKeyChecking ask 在主机密钥发生变化时提醒你。请求你的处理意见。
  配置“/etc/ssh/ssh_config”文件 
  “/etc/ssh/ssh_config”文件是OpenSSH系统范围的配置文件,允许你通过设置不同的选项
  来改变客户端程序的运行方式。这个文件的每一行包含“关键词-值”的匹配,其中“关键
  词”是忽略大小写的。下面列出来的是最重要的关键词,用man命令查看帮助页(ssh (1))
  可以得到详细的列表。 
  
  编辑“ssh_config”文件(vi /etc/ssh/ssh_config),添加或改变下面的参数: 
  
  # Site-wide defaults for various options 
  Host * 
  ForwardAgent no 
  ForwardX11 no 
  RhostsAuthentication no 
  RhostsRSAAuthentication no 
  RSAAuthentication yes 
  PasswordAuthentication yes 
  FallBackToRsh no 
  UseRsh no 
  BatchMode no 
  CheckHostIP yes 
  StrictHostKeyChecking no 
  IdentityFile ~/.ssh/identity 
  Port 22 
  Cipher blowfish 
  EscapeChar ~ 
  
  下面逐行说明上面的选项设置: 
  
  Host * 
  选项“Host”只对能够匹配后面字串的计算机有效。“*”表示所有的计算机。 
  
  ForwardAgent no 
  “ForwardAgent”设置连接是否经过验证代理(如果存在)转发给远程计算机。 
  
  ForwardX11 no 
  “ForwardX11”设置X11连接是否被自动重定向到安全的通道和显示集(DISPLAY set)。 
  
  RhostsAuthentication no 
  “RhostsAuthentication”设置是否使用基于rhosts的安全验证。 
  
  RhostsRSAAuthentication no 
  “RhostsRSAAuthentication”设置是否使用用RSA算法的基于rhosts的安全验证。 
  
  RSAAuthentication yes 
  “RSAAuthentication”设置是否使用RSA算法进行安全验证。 
  
  PasswordAuthentication yes 
  “PasswordAuthentication”设置是否使用口令验证。 
  
  FallBackToRsh no 
  “FallBackToRsh”设置如果用ssh连接出现错误是否自动使用rsh。 
  
  UseRsh no 
  “UseRsh”设置是否在这台计算机上使用“rlogin/rsh”。 
  
  BatchMode no 
  “BatchMode”如果设为“yes”,passphrase/password(交互式输入口令)的提示将被禁止。
  当不能交互式输入口令的时候,这个选项对脚本文件和批处理任务十分有用。 
  
  CheckHostIP yes 
  
  “CheckHostIP”设置ssh是否查看连接到服务器的主机的IP地址以防止DNS欺骗。建议设
  置为“yes”。 
  
  StrictHostKeyChecking no 
  “StrictHostKeyChecking”如果设置成“yes”,ssh就不会自动把计算机的密匙加入
  “$HOME/.ssh/known_hosts”文件,并且一旦计算机的密匙发生了变化,就拒绝连接。 
  
  IdentityFile ~/.ssh/identity 
  “IdentityFile”设置从哪个文件读取用户的RSA安全验证标识。 
  
  Port 22 
  “Port”设置连接到远程主机的端口。 
  
  Cipher blowfish 
  “Cipher”设置加密用的密码。 
  
  EscapeChar ~ 
  “EscapeChar”设置escape字符。 
  
  配置“/etc/ssh/sshd_config”文件 
  “/etc/ssh/sshd_config”是OpenSSH的配置文件,允许设置选项改变这个daemon的运行。
  这个文件的每一行包含“关键词-值”的匹配,其中“关键词”是忽略大小写的。下面列出
  来的是最重要的关键词,用man命令查看帮助页(sshd (8))可以得到详细的列表。 
  
  编辑“sshd_config”文件(vi /etc/ssh/sshd_config),加入或改变下面的参数: 
  
  # This is ssh server systemwide configuration file. 
  Port 22 
  ListenAddress 192.168.1.1 
  HostKey /etc/ssh/ssh_host_key 
  ServerKeyBits 1024 
  LoginGraceTime 600 
  KeyRegenerationInterval 3600 
  PermitRootLogin no 
  IgnoreRhosts yes 
  IgnoreUserKnownHosts yes 
  StrictModes yes 
  X11Forwarding no 
  PrintMotd yes 
  SyslogFacility AUTH 
  LogLevel INFO 
  RhostsAuthentication no 
  RhostsRSAAuthentication no 
  RSAAuthentication yes 
  PasswordAuthentication yes 
  PermitEmptyPasswords no 
  AllowUsers admin 
  
  下面逐行说明上面的选项设置: 
  
  Port 22 
  “Port”设置sshd监听的端口号。 
  
  ListenAddress 192.168.1.1 
  “ListenAddress”设置sshd服务器绑定的IP地址。 
  
  HostKey /etc/ssh/ssh_host_key 
  
  “HostKey”设置包含计算机私人密匙的文件。 
  
  ServerKeyBits 1024 
  “ServerKeyBits”定义服务器密匙的位数。 
  
  LoginGraceTime 600 
  “LoginGraceTime”设置如果用户不能成功登录,在切断连接之前服务器需要等待的时间(以
  秒为单位)。 
  
  KeyRegenerationInterval 3600 
  “KeyRegenerationInterval”设置在多少秒之后自动重新生成服务器的密匙(如果使用密匙)。
  重新生成密匙是为了防止用盗用的密匙解密被截获的信息。 
  
  PermitRootLogin no 
  “PermitRootLogin”设置root能不能用ssh登录。这个选项一定不要设成“yes”。 
  
  IgnoreRhosts yes 
  “IgnoreRhosts”设置验证的时候是否使用“rhosts”和“shosts”文件。 
  
  IgnoreUserKnownHosts yes 
  “IgnoreUserKnownHosts”设置ssh daemon是否在进行RhostsRSAAuthentication安全验证
  的时候忽略用户的“$HOME/.ssh/known_hosts” 
  
  StrictModes yes 
  “StrictModes”设置ssh在接收登录请求之前是否检查用户家目录和rhosts文件的权限和所
  有权。这通常是必要的,因为新手经常会把自己的目录和文件设成任何人都有写权限。 
  
  X11Forwarding no 
  “X11Forwarding”设置是否允许X11转发。 
  
  PrintMotd yes 
  “PrintMotd”设置sshd是否在用户登录的时候显示“/etc/motd”中的信息。 
  
  SyslogFacility AUTH 
  “SyslogFacility”设置在记录来自sshd的消息的时候,是否给出“facility code”。 
  
  LogLevel INFO 
  “LogLevel”设置记录sshd日志消息的层次。INFO是一个好的选择。查看sshd的man帮
  助页,已获取更多的信息。 
  
  RhostsAuthentication no 
  “RhostsAuthentication”设置只用rhosts或“/etc/hosts.equiv”进行安全验证是否已经足够了。 
  
  RhostsRSAAuthentication no 
  “RhostsRSA”设置是否允许用rhosts或“/etc/hosts.equiv”加上RSA进行安全验证。 
  
  RSAAuthentication yes 
  “RSAAuthentication”设置是否允许只有RSA安全验证。 
  
  PasswordAuthentication yes 
  “PasswordAuthentication”设置是否允许口令验证。 
  
  PermitEmptyPasswords no 
  “PermitEmptyPasswords”设置是否允许用口令为空的帐号登录。 
  
  AllowUsers admin 
  “AllowUsers”的后面可以跟着任意的数量的用户名的匹配串(patterns)或user@host这样
  的匹配串,这些字符串用空格隔开。主机名可以是DNS名或IP地址.
-------------------------------------------------------------------------------
SSH 安全性和配置入门
什么是 SSH?基本描述
Secure Shell (SSH) 的目的在于在通过网络远程访问另一个主机时提供最大的保护。它通过提供更好的身份验证工具和 Secure Copy (SCP)、Secure File Transfer Protocol (SFTP)、X 会话转发和端口转发等功能来加密网络交换,从而增加其他非安全协议的安全性。有各种类型的加密可用,从 512 位加密到高达 32768 位加密,包括密码,比如 Blowfish、Triple DES、CAST-128、Advanced Encryption Scheme (AES) 和 ARCFOUR。更高位的加密配置以使用更高的网络带宽为代价。图 1 和 图 2 展示如何使用一个像 Wireshark 这样的网络嗅探程序轻松让任何人随意查看 telnet 会话。

图 1. Telnet 协议会话未加密。 
展示 telnet 协议会话未加密的图解

常用缩略词

  • API:应用程序编程接口
  • FTP:文件传输协议
  • IETF:互联网工程任务组
  • POSIX:UNIX 可移植操作系统接口
  • RFC:请求注解
  • VPN:虚拟专用网络
在使用 telnet 这样的不安全 “明文” 协议时,网络上的任何人都可以窃取您的密码和其他敏感信息。图 1 展示用户fsmythe 通过一个 telnet 连接登录到一个远程主机。他输入其用户名 fsmythe 和密码 r@m$20!0,同一网络上的任何其他用户都可以看到,将其看作是倒霉、没有戒心的 telnet 用户。

图 2. SSH 协议会话加密。 
展示 SSH 协议会话加密的图解
图 2 提供了对典型 SSH 会话的概览,并展示了加密的协议如何不被同一网段的任何其他用户看到。现在每个主流 Linux® 和 UNIX® 版本都附带有默认安装的 SSH 包 — 通常是开源 OpenSSH 包—,因此有点需要下载和从源码进行编译。如果您不在一个 Linux 或 UNIX 平台上,有大量开源和基于 SSH 的免费软件工具可用,它们大受追捧并广为应用,比如 WinSCPPuttyFileZillaTTSSH 和 Cygwin(安装在 Windows® 操作系统之上的 POSIX 软件)。这些工具在 Windows 平台上提供一个 UNIX 或 Linux 式的 shell 接口。
不管您的操作系统是什么,SSH 都为老生常谈的日常计算操作提供许多实际效益。它不仅可靠、安全和灵活,而且易于安装、使用和配置 — 而且独具特色。

SSH 架构
IETF RFC 4251 到 4256 将 SSH 定义为 “经由一个不安全网络进行远程登录和其他安全网络服务的安全 shell 协议”。shell 由三个主要元素组成(参见 图 3):
  • 传输层协议:该协议提供服务器身份验证、隐私和具有完美转发隐私的完整性。该层可以提供可选压缩且通过一个 TCP/IP 连接运行,但是也可用于任何其他可靠的数据流之上。
  • 用户认证协议:该协议从服务器到客户端进行身份验证,且通过传输层运行。
  • 连接协议:该协议多路传输加密隧道到多个逻辑通道,通过用户认证协议运行。

图 3. SSH 协议逻辑层
SSH 协议逻辑层
传输层负责密钥交换和服务器身份验证。它设置加密、完整性验证和(可选)压缩并向上层公开一个用于发送和接收纯文本数据包的 API。用户认证层提供客户端身份验证以及多种验证方法。常见的身份验证方法包括密码、公钥、键盘交互、GSSAPI、SecureID 和 PAM。
连接层定义通道、全局请求和借以提供 SSH 服务的通道请求。单个 SSH 连接可以并行承载多个通道,每个都可双方向传输数据。通道请求转送信息,比如服务器端流程的退出代码。SSH 客户端发起一个转发服务器端端口的请求。
这种开发式架构设计提供广泛的灵活性。传输层可媲美传输层安全(Transport Layer Security,TLS),而且您可以运用定制的身份验证方法来扩展用户认证层。通过连接层,您可以多道传输二级会话到单个 SSH 连接(参见 图 4)。

图 4. 7 层 OSI 模型内的 SSH 
7 层 OSI 模型内的 SSH

针对 UNIX 和 Linux 系统的 SSH 的一般用途
您通常使用 SSH 来允许用户登录到一个远程主机并执行命令。然而,SSH 还支持隧道和 X11 连接。它甚至可以使用 SFTP 或 SCP 传输文件。SSH 适用于大部分常见平台内的多个应用程序,这些平台包括 Linux、UNIX、Windows 和 Apple® OS X,虽然有些应用程序可能需要仅在特定 SSH 客户端或服务器上提供或与之兼容的功能。
下面是一些常见的 SSH 语法例子:
  • 远程主机 shell 访问(取代 telnet 和 rlogin 明文,不安全协议):
    # ssh fsmythe@example.com
    [fsmythe@example.com] ~
    
  • 在远程主机(代替 rsh)执行单一命令:
    # ssh root@example.com reboot 
    root@example.com's password: ******
    
  • 通过 SCP 命令将文件从本地服务器复制到远程主机。
    root@edb-01.example.com's password: ******
    file1.txt      100%    0     0.0KB/s   00:00
    file2.txt      100%    0     0.0KB/s   00:00
    
  • 结合 SFTP,作为 FTP 文件传输的一个安全替代品:
    sftp fsmythe@example.com 
    Connecting to example.com...
    fsmythe@example.com's password: *******
    sftp>
    
  • 结合 rsync 有效安全地备份、复制和镜像文件到一个本地或远程主机:
    # rsync -avul --rsh=ssh /opt/edbdata/ root@example.com:/root/backup/
    root@example.com's password: ******
    building file list ... done
    ./
    file1.txt
    file2.txt
    file3.txt
    file4.txt
    dir1/file5.txt
    dir2/file6.txt
    
    sent 982813 bytes  received 2116 bytes  1374860.38 bytes/sec
    total size is 982138  speedup is 1.00
    
  • 端口转发或端口隧道化(不要与 VPN 混淆):
    ssh -L 8000:mailserver:110 example.com    fsmythe@example.com's password: ********
    
  • 从一个远程主机转发 X 会话(可能通过多个中间主机):
    Edit /etc/ssh/sshd_config and change 2 keywords : 
    AllowTcpForwarding yes
    X11Forwarding yes
    # service sshd restart 
    $ export DISPLAY 
    $ ssh -X fsmythe@example.com 
    
  • X11 转发配置与带 SSH X11 隧道的一个 X Windows 客户端的结合,支持实现通过 SSH 安全地在同一 Windows 主机上运行的一个 UNIX 或 Linux GUI 子系统,该 Windows 主机是到 Linux 或 UNIX 远程主机的 SSH 会话的来源:
    ssh -ND 8000 fsmythe@example.com
    Browser Settings, goto 'Manual Proxy Configuration' set "SOCKS Host" to example.com,
    the 'Port to 8000' , Enable SOCKS v5, and lastly set 'No Proxy for' field
    to 'localhost, 127.0.0.1'
    
  • 使用 sshfs 将一个目录作为本地计算机上的文件系统安全地挂载到一个远程服务器:
    # yum install sshfs fuse-utils (Install sshfs and fuse-utils)
    $sshfs example.com:/remote_dir /mnt/local_dir
    
  • 通过一个或多个机制对服务器进行自动化的远程主机监控和管理:
    (Report number of apache processes running on the remote server example.com):
    $ ssh example.com ps -ef | grep httpd | wc -l
    root@example.com's password: ***** 
    

SSH 安全性和配置最佳实践
对于一些之前列举的代码示例,许多系统管理员担心 SSH 使用情况和功能的一些安全性实现。尽管已经口头和书面说明了常见的各种 SSH 安全性和远程主机安全性方法,下面有一系列流程和配置可用于加强有关远程主机访问的 SSH 安全性:
  • 将 root 账户仅限制为控制台访问:
    # vi /etc/ssh/sshd_config
    PermitRootLogin no 
    
  • 为私有密钥使用一个强大的口令和密码保护来创建公私密钥对(绝不要生成一个无密码的密钥对或一个无密码口令无密钥的登录):
    (Use a higher bit rate for the encryption for more security)
    ssh-keygen -t rsa -b 4096
    
  • 配置 TCP 包装程序,以便仅允许选定的远程主机并拒绝不合意的主机:
    # vi /etc/hosts.deny
    ALL: 192.168.200.09  # IP Address of badguy
    
  • 在工作站或笔记本电脑上,关闭 SSH 服务禁用 SSH 服务器,然后删除 ssh 服务器包:
    # chkconfig sshd off 
    # yum erase openssh-server
    
  • 通过控制用户访问限制 SSH 访问:
    # vi /etc/ssh/sshd_config 
    AllowUsers fsmythe bnice swilson
    DenyUsers jhacker joebadguy jripper 
    
  • 仅使用 SSH Protocol 2:
    # vi /etc/ssh/sshd_config
    Protocol 2
    
  • 不要支持闲置会话,并配置 Idle Log Out Timeout 间隔:
    # vi /etc/ssh/sshd_config
    ClientAliveInterval 600  # (Set to 600 seconds = 10 minutes)
    ClientAliveCountMax 0
    
  • 禁用基于主机的身份验证:
    # vi /etc/ssh/sshd_config
    HostbasedAuthentication no
    
  • 禁用用户的 .rhosts 文件:
    # vi /etc/ssh/sshd_config
    IgnoreRhosts yes 
    
  • 配置防火墙以接受仅来自已知网段的 SSH 连接:
    Update /etc/sysconfig/iptables (Redhat specific file) to accept connection only 
    from 192.168.100.0/24 and 209.64.100.5/27, enter:
    
    -A RH-FW-1-INPUT -s 192.168.100.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
    -A RH-FW-1-INPUT -s 209.64.100.5/27 -m state --state NEW -p tcp --dport 22 -j ACCEPT
    
  • 限制 SSH 将侦听和绑定到的可用接口:
    # vi /etc/ssh/sshd_config
    ListenAddress 192.168.100.17
    ListenAddress 209.64.100.15
    
  • 设置用户策略,实施强大的密码来防御强力攻击、社会工程企图(social engineering attempts)和字典攻击:
    # < /dev/urandom tr -dc A-Za-z0-9_ | head -c8
    oP0FNAUt[
    
  • 使用 Chroot SSHD 将 SFTP 用户局限于其自己的主目录:
    # vi /etc/ssh/sshd_config 
    ChrootDirectory /data01/home/%u
    X11Forwarding no
    AllowTcpForwarding no
    
  • 禁用空密码:
    # vi /etc/ssh/sshd_config
    PermitEmptyPasswords no
    
  • 在指定时间内对传入端口 2022 连接的数量限速:
    Redhat iptables example (Update /etc/sysconfig/iptables): 
    
    -A INPUT  -i eth0 -p tcp --dport 2022 -m state --state NEW -m limit --limit 3/min
    --limit-burst 3 -j ACCEPT
    
    -A INPUT  -i eth0 -p tcp --dport 2022 -m state --state ESTABLISHED -j ACCEPT
    -A OUTPUT -o eth0 -p tcp --sport 2022 -m state --state ESTABLISHED -j ACCEPT
    
  • 配置 iptables,以便在 30 秒内仅允许在端口 2022 上有三个连接尝试:
    Redhat iptables example (Update /etc/sysconfig/iptables): 
    -I INPUT -p tcp --dport 2022 -i eth0 -m state --state NEW -m recent --set
    
    -I INPUT -p tcp --dport 2022 -i eth0 -m state --state NEW -m recent --update 
    --seconds 30 --hitcount 3 -j DR
    
  • 使用一个日志分析器,比如 logcheckloggrepsplunk 或 logwatch 来更好地理解日志并创建日志报告。另外,在 SSH 应用程序自身内增加日志记录的详细度:
    Installation of the logwatch package on Redhat Linux 
    # yum install logwatch 
    
  • 通过配置增加 SSH 日志记录的详细度:
    # vi /etc/ssh/sshd_config
    LogLevel DEBUG
    
  • 在补丁上总是将 SSH 程序包和需要的库保持为最新:
    # yum update openssh-server openssh openssh-clients -y 
    
  • 隐藏 OpenSSH 版本,要求 SSH 源代码并进行重新编译。然后进行以下更新:
    # vi /etc/ssh/sshd_config
    VerifyReverseMapping yes # Turn on  reverse name checking
    UsePrivilegeSeparation yes # Turn on privilege separation
    StrictModes yes   # Prevent the use of insecure home directory    
        # and key file permissions
    AllowTcpForwarding no  # Turn off , if at all possible 
    X11Forwarding no  # Turn off , if at all possible
    PasswordAuthentication no # Specifies whether password authentication is 
        # allowed.  The default is yes. Users must have 
        # another authentication method available .
    
  • 从系统上删除 rlogin 和 rsh 二进制程序,并将它们替代为 SSH 的一个 symlink
    # find /usr -name rsh
    /usr/bin/rsh
    # rm -f /usr/bin/rsh
    # ln -s /usr/bin/ssh /usr/bin/rsh
    
SSH 支持可启用或禁用的多种不同的身份验证方法和技术。在 /etc/ssh/sshd_config 文件中,您可以进行这些配置更改,方法就是输入为身份验证方法列出的关键字,然后紧接 yes 或 no。下面是一些常见的配置更改:
# RSAAuthentication yes  
# PubkeyAuthentication yes  
# RhostsRSAAuthentication no
# HostbasedAuthentication no
# RhostsRSAAuthentication and HostbasedAuthentication
PasswordAuthentication yes
ChallengeResponseAuthentication no
# KerberosAuthentication no
GSSAPIAuthentication yes

sshd_config 文件内的 AllowedAuthentications 和 RequiredAuthentications 决定哪些身份验证方法和配置仅用于 SSH Protocol 2,且它们支持密码和公钥身份验证的语法如下:
# vi /etc/ssh/sshd_config
AllowedAuthentications publickey, password
RequiredAuthentications publickey, password


SSH 的私钥和公钥对
为了帮助验证身份,SSH 有一个密钥管理功能和相关的代理。当配置为公钥身份验证时,您的密钥证明您在远程 SSH 主机上的身份。一个基于 SSH 的身份包括两个部分:一个公钥和一个私钥。私有 SSH 密钥是用于出站 SSH 连接的用户身份,且应当保密。当用户发起一个 SSH 或 SCP 会话到远程主机或服务器时,他或她被认为是 SSH 客户端。通过一个数学算法,一个私钥如同您的电子身份证;公钥如同您向其出示身份证的锁或门机制。您的私钥说,“这真的是 Fred Smythe”;公钥说,“是的,您确实是真正的 Fred Smythe;您已通过身份验证:请进入。”
您的公钥代表您允许通过您的大门或锁进入的人。公钥需要保密;它们不能用于泄漏一个系统或对系统进行未经授权的访问。在一个 Linux 或 UNIX 系统上,这些私有和公共密钥对存储在 ASCII 文本系统中;在 Windows 系统上,一些程序将密钥对存储为文本文件,一些存储在 Windows 注册表中。
通过一个 SSH Protocol 2 配置可创建使用多个私有密钥的多重鉴定。让我们看看如何在一个典型的 Linux 主机上生成、设置和配置一个 SSH 私有和公共密钥对(参见 图 5)。

图 5. 在 SSH 定义的架构模型中定义的 SSH 公私密钥对事务图 
SSH 公私密钥对事务
配置公私 SSH 密钥对的步骤
步骤 1 中所示的示例(参见 清单 1)为用户 fsmythe 使用 ssh-keygen 使用程序,通过 dsa 的 type 创建 SSH 公私密钥对。

清单 1. 生成 SSH 密钥对
    
[fsmythe@example.com ~]$ /usr/bin/ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/fsmythe/.ssh/id_dsa):
Enter passphrase (empty for no passphrase): ******    (Enter 'mypassword')
Enter same passphrase again: ****** (Enter 'mypassword')
Your identification has been saved in /home/fsmythe/.ssh/id_dsa.
Your public key has been saved in /home/fsmythe/.ssh/id_dsa.pub.
The key fingerprint is:
33:af:35:cd:58:9c:11:91:0f:4a:0c:3a:d8:1f:0e:e6 fsmythe@example.com
[fsmythe@example.com ~]$

步骤 2 中所示的示例(清单 2) 展示如何将密钥对的私有密钥从源主机复制到目标主机的 authorized_keys 文件,该文件位于目标主机上预期用户帐户的主目录下的 .ssh 子目录内。

清单 2. 将私有密钥从源主机复制到目标主机上的 authorized_keys 文件 
    
[fsmythe@example.com ~]$ scp -p /home/fsmythe/.ssh/id_dsa.pub 
fsmythe@thor01.com:/home/fsmythe/.ssh/authorized_keys
fsmythe@ thor01.com's password:
id_dsa.pub       100%   624    0.6KB/s     00:00

步骤 3 中所示的示例(参见 清单 3)发出第一次远程 SSH 调用(ls -d /tmp)到目标服务器,从而缓存您的服务器的 .ssh/known_hosts 文件内的密钥。您可以输入与在创建 SSH 公私密钥对时同样的口令,且在远程目标服务器上运行的命令的输出可在您本地的源服务器上看到。

清单 3. 通过在目标远程主机上运行远程命令来验证 SSH 访问 
    
[fsmythe@example.com ~]$ ssh root@thor01.com ls -d /tmp
The authenticity of host 'thor01.com (10.12.53.118)' can't be established.
RSA key fingerprint is 84:4f:e5:99:0b:7d:54:d0:1b:3e:2b:96:02:34:41:25.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'thor01.com,10.12.53.118' (RSA) to the list of known hosts.
Enter passphrase for key '/root/.ssh/id_dsa': ******  (Enter 'mypassword') 
/tmp
file1.txt
file2.txt
dir3_5432

注意:对于上述示例,您不必输入用户 fsmythe 的密码。不过您可以输入您在第一步中设置的口令。如果您选择在访问远程目标时不输入口令,那么在提示输入口令时输入步骤 1 中的 enter 来创建一个空口令。现在,您不必输入任何内容来作为用户 fsmythe 访问 thor01.com 远程目标机器。
配置和使用 ssh-agent
对于拒绝创建无密码 SSH 公私密钥对的真正的偏执狂来说,有一个 ssh-agent 实用程序。简言之,您使用 ssh-agent实用程序来暂时在无口令集的公私密钥对配置上授予无密码的 SSH 访问,但仅针对当前 shell 会话。在运用 ssh-agent 实用程序之前,像往常一样输入口令:
[root@example01.com ~]# ssh root@example02.com
Enter passphrase for key '/root/.ssh/id_dsa':****** (User must type password)
Last login: Sat May  8 06:37:26 2010 from 10.12.53.118

接下来,查询 ssh-agent 以在标准输出中生成 Bourne shell 命令:
[root@example01.com ~]# ssh-agent -s
SSH_AUTH_SOCK=/tmp/ssh-vxZIxF1845/agent.1845; export SSH_AUTH_SOCK;
SSH_AGENT_PID=1849; export SSH_AGENT_PID;
echo Agent pid 1849;

在步骤 3 中,在当前 shell 会话中设置前述的环境变量:
[root@example01 ~]# SSH_AUTH_SOCK=/tmp/ssh-vxZIxF1845/agent.1845;export SSH_AUTH_SOCK
SSH_AGENT_PID=1849; export SSH_AGENT_PID;echo Agent pid 1849
Agent pid 1849

然后,确认 ssh-agent 在运行:
[root@example01.com ~]# ps -fp $SSH_AGENT_PID
UID        PID  PPID  C STIME TTY          TIME CMD
root      1849     1  0 06:14 ?        00:00:00 ssh-agent -s

现在,在运行的 ssh-agent 内列出当前加载的身份:
[root@example01.com ~]# ssh-add -l
The agent has no identities.

在步骤 6 中,添加所需的 SSH 身份(使用该 SSH 密钥的正确口令对其进行预先验证):
[root@example01.com ~]# ssh-add
Enter passphrase for /root/.ssh/id_dsa:
Identity added: /root/.ssh/id_dsa (/root/.ssh/id_dsa) ****** (Entered 'mypassword')

现在,您可以确认将这些身份加载到运行的 ssh-agent 中:
[root@example01.com ~]# ssh-add -l
1024 33:af:35:cd:58:9c:11:91:0f:4a:0c:3a:d8:1f:0e:e6 /root/.ssh/id_dsa (DSA)

最后,使用 SSH 命令语法测试 ssh-agent。注意,现在有一个口令提示:
# Assuming target remote host has correct authorized key for private key from example01
[root@example01.com ~]# ssh -A root@example02.com 
Last login: Sat May  8 06:36:27 2010 from 10.12.53.118
[root@example02 ~]#

# Assuming target remote host has correct authorized key for private key from example03
[root@example01.com ~]# ssh -A root@example03.com  
Last login: Sat May  8 07:04:05 2010 from 10.12.53.119
[root@example03 ~]#

在使用 ssh-add 命令输入口令时,您实际上是在解密私有密钥然后通过代理将其放到内存中,用于将来使用该口令的 SSH 连接。注意,您可以输入多个私有密钥并使用 ssh-add 命令预先验证它们。
清单 4 中所示的 SSH 工具 ssh-keyscan 允许您从多个远程 SSH 主机收集公共 SSH 主机密钥。该工具有助于构建 /etc/ssh_known_hosts 文件且异常快速有效。它主要适用于用于自动化用途的 shell 脚本。

清单 4. 使用 ssh-keyscan 的示例
    
[root@example01 ~]# /usr/bin/ssh-keyscan -t rsa,dsa example02.com
# example02.comSSH-2.0-OpenSSH_4.3
example02.comssh-dss AAAAB3NzaC1kc3MAAACBALd5/TGn7jCL1DWWzYMw96jw3QOZGBXJgP4m9LACViyM0QHs
ewHGo841JdInfE825mVe0nB/UT15iylLOsI/jFCac+ljQRlO+h2q7WOwGveOUN7TxyKlejM+G1pg5DndGt05iYn+2
dDfn5CmEsI+K0F2vk/+mpoSOk9HKq9VgwNzAAAAFQDPeLAth62TRUcN/nTYoqENBmW3SwAAAIEAryoKa+VaG5LQNj
wBujAuA7hGl+DIWVb1aZ8xAHkcyL5XgrOWEKNnK9mDmEN66oMLfTMO3w8/OvbJUmcXcU3jnL3zguz2E2OIv6t6vAa
F6niL7A/VhxGGxy4CJZnceufStrzZ3UKXRzjwlm0Bwu/LruVF2m3XLvR5XVwUgyWvw+AAAACAaK12k3uC/OOokBgi
eu/SuD5wCSBsf9rqG9ZFa32ujZwRZmA/AwPrZd6q3ASxmjtMp6zGQSzxPczUvLH9D9WIJo713bw8wCPo/7pqiQNRs
OZXqlQyaXyrDout6CI683b1/rxsZKPrJpFNehrZwjWrwpYhK7VaTuzxvWtrDyDxWec=
# example03.comSSH-2.0-OpenSSH_4.3
example03.comssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq5So5VBeH4gPX1A1VEeQkGsb/miiWsWnNTW8ZWYj
2IvU7rKpk/dBIp64WecYYYgDqTK5u0Q+yTijF8wEEI9rRyoh9p5QraM8qy9NxcHzyGqU4vSzfVrblIQrDI8iv7iwz
7PxQAY76NmweaUyGEDfIErty4gCn/ksy85IgffATa9nt36a4iUhiDNifnE8dm1ZrKkvz3lIg0w+Cu0T9MY77AqLWj
Moo0WoQArIvYa0soS3VhzgD/Biwu/sh3eHJtFUxTVxnATdkWkHKUI1wxma3j7jF0saTRKEQSvG6492W+U1FhEjFGN
r7KeZXH99uFpuUWFA7xO7uaG/MLWSjPJMxw==
# example04.comSSH-2.0-OpenSSH_4.3
example04.comssh-dss AAAAB3NzaC1kc3MAAACBALd5/TGn7jCL1DWWzYMw96jw3QOZGBXJgP4m9LACViyM0QHs
ewHGo841JdInfE825mVe0nB/UT15iylLOsI/jFCac+ljQRlO+h2q7WOwGveOUN7TxyKlejM+G1pg5DndGt05iYn+2
dDfn5CmEsI+K0F2vk/+mpoSOk9HKq9VgwNzAAAAFQDPeLAth62TRUcN/nTYoqENBmW3SwAAAIEAryoKa+VaG5LQNj
wBujAuA7hGl+DIWVb1aZ8xAHkcyL5XgrOWEKNnK9mDmEN66oMLfTMO3w8/OvbJUmcXcU3jnL3zguz2E2OIv6t6vAa
F6niL7A/VhxGGxy4CJZnceufStrzZ3UKXRzjwlm0Bwu/LruVF2m3XLvR5XVwUgyWvw+AAAACAaK12k3uC/OOokBgi
eu/SuD5wCSBsf9rqG9ZFa32ujZwRZmA/AwPrZd6q3ASxmjtMp6zGQSzxPczUvLH9D9WIJo713bw8wCPo/7pqiQNRs
OZXqlQyaXyrDout6CI683b1/rxsZKPrJpFNehrZwjWrwpYhK7VaTuzxvWtrDyDxWec=
# example05.comSSH-2.0-OpenSSH_4.3
example05.comssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq5So5VBeH4gPX1A1VEeQkGsb/miiWsWnNTW8ZWYj
2IvU7rKpk/dBIp64WecYYYgDqTK5u0Q+yTijF8wEEI9rRyoh9p5QraM8qy9NxcHzyGqU4vSzfVrblIQrDI8iv7iwz
7PxQAY76NmweaUyGEDfIErty4gCn/ksy85IgffATa9nt36a4iUhiDNifnE8dm1ZrKkvz3lIg0w+Cu0T9MY77AqLWj
Moo0WoQArIvYa0soS3VhzgD/Biwu/sh3eHJtFUxTVxnATdkWkHKUI1wxma3j7jF0saTRKEQSvG6492W+U1FhEjFGN
r7KeZXH99uFpuUWFA7xO7uaG/MLWSjPJMxw==


使用 UNIX 应用程序或脚本配置 SSH
配置供远程 shell 脚本使用的 SSH 访问以及用于维护、远程备份和存档系统的远程工具非常有用,但一旦涉及到服务器安全性,它一直都是一个有极大争议的主题。用户可能希望运行的很多 shell 脚本,比如:
$ ssh fsmythe@example.com /usr/local/bin/dangerous_script.pl 

不能处理提示其进行身份验证的一个必需的 SSH 口令,但除非提前配置一个无密码的公私 SSH 密钥对、一个 ssh-agent 配置或一个可信的主机网络机制 — 不提示输入 SSH 密钥的配置 —,否则这不太可能。这是因为 SSH 期待来自与该 shell 会话相关的当前终端的口令。通过使用一个预期脚本或 Perl(参见 CPAN Module Net::SSH::Perl)脚本(或您的 shell 脚本可以选择性地调用上述脚本类型中的一种)用户可以解决该问题:
#!/usr/local/bin/expect
spawn sftp $argv
expect "password:"
send "mysshpassowrd\r"

向一般用户授予一个无密码的 SSH 机制来访问远程主机在一些系统管理员的眼里已相当不可想象。然而,拥护无密码 SSH 机制访问远程主机的其他安全措施,比如远程主机上的用户仅提供一个受限的 korn shell (rksh) 帐户或受限的 shell (rssh) 而非一个完全的 bash 或 Bourne shell 帐户。一个授权密钥也可以将用户限制为列表中命令的一个子集,因此实际上,用户仅可以使用运程运行所需的确切命令,没有可能发生进一步访问或会损坏系统的 一个意外命令运行。清单 5 中提供的 SSH 限制示例提供这样一个限制类型。

清单 5. 限制远程主机上 authorized_keys 文件的配置示例 
    
[fsmythe@example02 .ssh]$ more authorized_keys
command="/usr/local/bin/secureScript.sh",no-port-forwarding,no-X11-forwarding,no-agent-fo
rwarding,no-pty ssh-dss AAAAB3NzaC1kc3MAAACBAOFsC6C7cJUGOZG4Ur9W0J6mxTTk5+MYTu5XfRESPLVwQ
A7HlUxhsXsxgmb1L1RgvR/g0JZnipDS+fGOrN2/IerSpgyzegTVxYLPrOovvuyCn5TA0+rmyrkV27so6yRDkdqTJc
YzWNJOyDndnTrDc/LNmqLFKoGMQ33aur6RNv4VAAAAFQD4leC5Fc1VJqjvXCNsvazBhi84vQAAAIAWbshT80cTESg
dX/srxX4KVNAzY1uhBz5V0UYR4FGP+aoe6laxRj+gQvFIvAKIrpikvBjgyW6cdT8+k0t8HGIQp20MzSBdY9sH8xdj
05AG97Nb/L8xzkceB78qfXhV6txaM1CzssUtiOtaAygrywNPBDEN9MbEbwpVVVyd6iqZNgAAAIAmV0SUZoUr8dHdC
tagRye4bGOQjoztpb4C0RbXQw+w7Jpzr6cZISdZsK4DTBjODvv2+/OWPm7NEzzWyLzHPBNul8hAHOUCOpp+mYWbXX
F78BTk2Ess0SZu8dwpOtasTNEp+xPcsOvQx2Kdr17gTp+28SfpREuLudOr6R3KeTb+hw== fsmythe@example01

主机 example01 上的用户 fsmythe 仅允许执行本例中的命令 ="/usr/local/bin/secureScript.sh

使用 SSH 创建一个可信的主机环境
最后,我要提一下作为一种替代方案来设置公私 SSH 密钥对的可信主机环境。对于自动化或在有必要进行这些类型的调用的一个脚本环境中,虽然可信主机环境仍然承担一些安全风险,但它优于公私密钥对场景。一个 可信主机环境或可信主机身份验证主要依赖于列出获准访问的用户和主机组合的预配置文件。有两种可信主机身份验证。较老(比如针对 OpenSSH 和 SSH1)和较弱的使用明文协议命令(rshrcp 和 rlogin);检查两个文件;并在 sshd_config 文件中设置一个关键字:
/etc/hosts.equiv
~/.rhosts 

SSH Protocol 2 不支持该方法。相反,对于更安全的可信主机网络,在 /etc/ssh/sshd_config 文件(接受主机名或 IP 地址)中进行如下更改,并配置 shosts.equiv 和/或 .shosts 文件:
/etc/shosts.equiv
~/.shosts 

要在 /etc/ssh/sshd_config 文件中为 SSH Protocol 2 启用一个可信主机环境,使用:
PermitEmptyPasswords yes
AllowSHosts remoteclient.com
DenySHosts 

例如,如果您在服务器 example.com 上且按如下方式配置了您的 /etc/shosts.equiv 文件:
+remoteclient.com fsmythe
+secureserver.net sallyh
+192.168.100.12 fsmythe
-hackers.org james 

您将允许用户 fsmythe 从远程源 remoteclient.com,192.168.100.12,和 secureserver.net 进行可信主机身份验证,允许用户从 secureserver.net 进行访问,拒绝来自远程源 hackers.org 的用户 james 的访问。
可信主机身份验证和公私 SSH 密钥对身份验证方法是类似的,在很大程度上实现相同的结果。表 1 提供对两种身份验证方法的并排比较。

表 1. 公私 SSH 密钥对与可信主机环境之比较 
SSH 方面可信主机公私密钥对
根据 IP 地址进行身份验证
根据主机名进行身份验证
使用其他公钥功能
根据远程用户名进行身份验证
允许主机名和 IP 地址中有通配符
口令是登录访问所必需的
IP 地址或主机名变更消息有时
服务器和客户端需要的配置
对自动化任务或脚本化需求有用
对那些目前嘲笑在网络上使用无密码远程 SSH 访问来支持可信主机身份验证这一想法的那些管理员,在使用脚本实现远程 SSH 功能时考虑公私密钥对的缺点:
  • 如果一个服务器主机名或 IP 地址改变,公私密钥对配置会由于缓存的已知主机而破坏。需要在 .ssh/known_hosts 文件中删除旧条目,且 SSH 远程主机名和/或 IP 地址被再次缓存。这会破坏依赖于公私密钥对的脚本。
  • 公私密钥对身份验证同时需要客户端和服务器配置。如果一个 SSH 公钥改变或重新生成密钥对,所有远程主机将在其 authorized_keys 文件中需要新的公共密钥。
  • 如果 .ssh/ 文件夹的权限或私有或公共密钥文件本省改变,它会阻止无 SSH 密码的访问发生。要禁用严格的文件和目录权限检查,在 /etc/ssh/sshd_config 文件内将关键字 StrictModes 设置为 no
  • 一旦生成密钥对,没有集中方式来撤销密钥,或确切地知道该密钥已向谁分发。

结束语
SSH 是一个强大而安全的网络实用程序,全球有无数用户使用它来完成各种任务。作为 telnet 和 r* 系列命令等明文协议的一个安全替代方案,拥有可免费分发的 SSH 客户端和服务器的多个产品,SSH 是很难被击败的。在许多网络中被广泛用于脚本化技术内的大量远程监控、系统维护、远程系统审计、报告和自动化,SSH 似乎已被普遍接受并将继续不断演化。


下载
描述名字大小下载方法
Putty Windows SSH 客户端安装程序putty-0.60-installer.exe1.7MBHTTP
FileZilla Windows SSH 安装程序FileZilla_3.3.2.1_win32-setup.exe4.0MBHTTP
Tera Term Windows SSH 安装程序teraterm-4.65.exe7.5MBHTTP
WinSCP 安装包winscp427setup.exe2.9MBHTTP
Cygwin Universal DownloaderSoftonicDownloader11694.exe251KBHTTP
关于下载方法的信息

参考资料
学习
  • Secure Shell。Wikipedia 提供了对 SSH 的精彩介绍和讨论。
  • OpenSSH:OpenSSH 是 Internet 技术用户依赖的一个连通性工具版本。可免费获取。
  • RFC 4251:阅读 SSH 协议架构。
  • The OpenSSH Protocol under the Hood(Girish Venkatachalam,Linux Journal,2007 年 4 月):在 OpenSSH 上获取 “基本事实细节”。
  • Server clinic: Connect securely with ssh(Cameron Laird,developerWorks,2003 年 7 月):了解使用 SSH 保护服务器的更多信息。
  • SSH and ssh-agent:了解更多并从 Symantec 下载工具。
  • SSH public keys:更多了解使用公共密钥的风险。
  • SSH tutorial for Linux:Suso.com 提供在 Linux 环境中开始使用 SSH 的一本好教程。
  • Five SSH tricks:探究您必须知道的 5 个 SSH 技巧。
  • Top 20 OpenSSH Server Best Security Practices:探究这些服务器最佳安全实践。
  • AIX and UNIX 专区:developerWorks 的“AIX and UNIX 专区”提供了大量与 AIX 系统管理的所有方面相关的信息,您可以利用它们来扩展自己的 UNIX 技能。
  • AIX and UNIX 新手入门:访问“AIX and UNIX 新手入门”页面可了解更多关于 AIX 和 UNIX 的内容。
  • AIX and UNIX 专题汇总:AIX and UNIX 专区已经为您推出了很多的技术专题,为您总结了很多热门的知识点。我们在后面还会继续推出很多相关的热门专题给您,为了方便您的访问,我们在这里为您把本专区的所有专题进行汇总,让您更方便的找到您需要的内容。
  • AIX and UNIX 下载中心:在这里你可以下载到可以运行在 AIX 或者是 UNIX 系统上的 IBM 服务器软件以及工具,让您可以提前免费试用他们的强大功能。
  • IBM Systems Magazine for AIX 中文版: 本杂志的内容更加关注于趋势和企业级架构应用方面的内容,同时对于新兴的技术、产品、应用方式等也有很深入的探讨。IBM Systems Magazine 的内容都是由十分资深的业内人士撰写的,包括 IBM 的合作伙伴、IBM 的主机工程师以及高级管理人员。所以,从这些内容中,您可以了解到更高层次的应用理念,让您在选择和应用 IBM 系统时有一个更好的认识。
  • 技术书店:阅读关于这些和其他技术主题的图书。
讨论
关于作者
Roger Hill 在过去 23 年中一直担任大型复杂混合环境中的一名 UNIX®/Linux® 系统工程师和程序员/开发员。在过去 7 年中他主要专注于各种 UNIX、Linux 和 Windows® 平台之间的互通和为这些系统建立无缝、安全的自动化功能。Roger 拥有计算机信息系统副学士学位、计算机科学学士学位、Linux 管理校长证书,且有 9 个专业技术认证。
原文链接: http://www.ibm.com/developerwork...
from http://www.chineselinuxuniversity.net/articles/44368.shtml
----------------------------------------------------------------------------------------------------------------------------------------


This document covers the SSH client on the Linux Operating System and other OSes that use OpenSSH. If you useWindows, please read the document SSH Tutorial for Windows If you use Mac OS X or other Unix based system, you should already have OpenSSH installed and can use this document as a reference.
This article is one of the top tutorials covering SSH on the Internet. It was originally written back in 1999 and was completely revised in 2006 to include new and more accurate information. As of October, 2008, it has been read by over 473,600 people and consistently appears at the top of Google's search results for SSH Tutorial and Linux SSH.

Contents

[hide]

What Is SSH?

There are a couple of ways that you can access a shell (command line) remotely on most Linux/Unix systems. One of the older ways is to use the telnet program, which is available on most network capable operating systems. Accessing a shell account through the telnet method though poses a danger in that everything that you send or receive over that telnet session is visible in plain text on your local network, and the local network of the machine you are connecting to. So anyone who can "sniff" the connection in-between can see your username, password, email that you read, and commands that you run. For these reasons you need a more sophisticated program than telnet to connect to a remote host.
An unencrypted telnet session
SSH, which is an acronym for Secure SHell, was designed and created to provide the best security when accessing another computer remotely. Not only does it encrypt the session, it also provides better authentication facilities, as well as features like secure file transfer, X session forwarding, port forwarding and more so that you can increase the security of other protocols. It can use different forms of encryption ranging anywhere from 512 bit on up to as high as 32768 bits and includes ciphers like AES (Advanced Encryption Scheme), Triple DES, Blowfish, CAST128 or Arcfour. Of course, the higher the bits, the longer it will take to generate and use keys as well as the longer it will take to pass data over the connection. 
An encrypted ssh session
These two diagrams on the left show how a telnet session can be viewed by anyone on the network by using a sniffing program like Ethereal (now called Wireshark) or tcpdump. It is really rather trivial to do this and so anyone on the network can steal your passwords and other information. The first diagram shows user jsmith logging in to a remote server through a telnet connection. He types his username jsmith and password C0lts06!, which are viewable by anyone who is using the same networks that he is using.
The second diagram shows how the data in an encrypted connection like SSH is encrypted on the network and so cannot be read by anyone who doesn't have the session-negotiated keys, which is just a fancy way of saying the data is scrambled. The server still can read the information, but only after negotiating the encrypted session with the client. 
When I say scrambled, I don't mean like the old cable pay channels where you can still kinda see things and hear the sound, I mean really scrambled. Usually encryption means that the data has been changed to such a degree that unless you have the key, its really hard to crack the code with a computer. It will take on the order of years for commonly available computer hardware to crack the encrypted data. The premise being that by the time you could crack it, the data is worthless.

Getting Started

This tutorial isn't going to cover how to install SSH, but will cover how to use it for a variety of tasks. Consult your Linux distribution's document for information on how to setup OpenSSH.
Chances are that if you are using a version of Linux that was released after 2002, that you already have OpenSSH installed. The version of SSH that you will want to use on Linux is called OpenSSH. As of this writing (October 2009), the latest version available is 5.3, but you may encounter versions from 3.6 on up. If you are using anything lower than version 3.9, I'd strongly advise you to upgrade it.
OpenSSH can be obtained from http://www.openssh.org/
To really make ssh useful, you need a shell account on a remote machine, such as on a suso.org account.
The first thing we'll do is simply connect to a remote machine. This is accomplished by running 'ssh hostname' on your local machine. The hostname that you supply as an argument is the hostname of the remote machine that you want to connect to. By default ssh will assume that you want to authenticate as the same user you use on your local machine. To override this and use a different user, simply use remoteusername@hostname as the argument. Such as in this example:
ssh username@username.suso.org

The first time around it will ask you if you wish to add the remote host to a list of known_hosts, go ahead and say yes.
The authenticity of host 'arvo.suso.org (216.9.132.134)' can't be established. RSA key fingerprint is 53:b4:ad:c8:51:17:99:4b:c9:08:ac:c1:b6:05:71:9b. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'arvo.suso.org' (RSA) to the list of known hosts.

It is important to pay attention to this question however because this is one of SSH's major features. Host validation. To put it simply, ssh will check to make sure that you are connecting to the host that you think you are connecting to. That way if someone tries to trick you into logging into their machine instead so that they can sniff your SSH session, you will have some warning, like this:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: POSSIBLE DNS SPOOFING DETECTED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ The RSA host key for arvo.suso.org has changed, and the key for the according IP address 216.9.137.122 is unchanged. This could either mean that DNS SPOOFING is happening or the IP address for the host and its host key have changed at the same time. Offending key for IP in /home/suso/.ssh/known_hosts:10 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed. The fingerprint for the RSA key sent by the remote host is 96:92:62:15:90:ec:40:12:47:08:00:b8:f8:4b:df:5b. Please contact your system administrator. Add correct host key in /home/suso/.ssh/known_hosts to get rid of this message. Offending key in /home/suso/.ssh/known_hosts:53 RSA host key for arvo.suso.org has changed and you have requested strict checking. Host key verification failed.
If you ever get a warning like this, you should stop and determine if there is a reason for the remote server's host key to change (such as if SSH was upgraded or the server itself was upgraded). If there is no good reason for the host key to change, then you should not try to connect to that machine until you have contacted its administrator about the situation. If this is your own machine that you are trying to connect to, you should do some computer forensics to determine if the machine was hacked (yes, Linux can be hacked). Or maybe your home computer's IP address has changed such as if you have a dynamic IP address for DSL. One time I received this message when trying to connect to my home machine's DSL line. I thought it was odd since I hadn't upgraded SSH or anything on my home machine and so I choose not to try to override the cached key. It was a good thing that I didn't try because I found out that my dynamic IP address had changed and that out of chance, another Linux machine running OpenSSH took my old IP.
After saying yes, it will prompt you for your password on the remote system. If the username that you specified exists and you type in the remote password for it correctly then the system should let you in. If it doesn't, try again and if it still fails, you might check with the administrator that you have an account on that machine and that your username and password is correct.

Generating a key

Now that you have spent all that time reading and are now connected, go ahead and logout. ;-) Once you're back to your local computer's command prompt enter the command 'ssh-keygen -t dsa'.
ssh-keygen -t dsa
It should begin spitting out the following:
Generating public/private dsa key pair. Enter file in which to save the key (/home/localuser/.ssh/id_dsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/localuser/.ssh/id_dsa. Your public key has been saved in /home/localuser/.ssh/id_dsa.pub. The key fingerprint is: 93:58:20:56:72:d7:bd:14:86:9f:42:aa:82:3d:f8:e5 localuser@mybox.home.com
It will prompt you for the location of the keyfile. Unless you have already created a keyfile in the default location, you can accept the default by pressing 'enter'.
Next it will ask you for a passphrase and ask you to confirm it. The idea behind what you should use for a passphrase is different from that of a password. Ideally, you should choose something unique and unguessable, just like your password, but it should probably be something much longer, like a whole sentence. Here are some examples of passphrases I've used in the past:
The right thing changes from state to state
the purpose of life is to give it purpose
They're not going to guess this passphrase!
The RIAA can just suck my big ass
It is never a good day at Teletron
Some passphrases that I've used have had as many as 60 characters along with punctuation and numbers. This makes the passphrase harder to guess. To give you an idea of how much more secure a passphrase is than a password. Consider this. Even if you narrowed down the number of words someone could use in a passphrase to 2000 potential words, if that person used 5 words in a sentence from that 2000 word set, it would mean there are 32,000,000,000,000,000 different combinations. Compare this with 6,095,689,385,410,816, which is the total possible combinations in an 8 character password using upper and lower case characters, numbers and punctuation (about 94 potential characters). So an 8 character password has 5.25 times less combinations than a 5 word passphrase. In actuality, most people choose words from a set of 10,000 or more words, bringing the complexity of a 5 word passphrase to 16,405 or more times greater than that of a 8 character password. So on average, the difficulty of cracking a passphrase is much greater than any password that could be used. Interestingly, the potential number of combinations of 8 word passphrase of someone with an adult vocabulary (8000 words or more) is almost equal to the number of 8 character password combinations multiplied by itself or about 16,777,216,000,000,000,000,000,000,000,000 combinations.
Don't use any famous quotes or phrases for your passphrase, they may be easily guessed by another person or by a brute force cracking program.
The reason why you would generate a keyfile is so that you can increase the security of your SSH session by not using your system password. When you generate a key, you are actually generating two key files. One private key and one public key, which is different from the private key. The private key should always stay on your local computer and you should take care not to lose it or let it fall into the wrong hands. Your public key can be put on the machines you want to connect to in a file called .ssh/authorized_keys. The public key is safe to be viewed by anybody and mathematically cannot be used to derive the private key. Its just like if I gave you a number 38,147,918,357 and asked you to find the numbers and operations I used to generate that number. There are nearly infinite possibilities.
Whenever you connect via ssh to a host that has your public key loaded in the authorized_keys file, it will use a challenge response type of authentication which uses your private key and public key to determine if you should be granted access to that computer It will ask you for your key passphrase though. But this is your local ssh process that is asking for your passphrase, not the ssh server on the remote side. It is asking to authenticate you according to data in your private key. Using key based authentication instead of system password authentication may not seem like much of a gain at first, but there are other benefits that will be explained later, such as logging in automatically from X windows.

Installing your public key manually

If you do not have the ssh-copy-id program available, then you must use this manual method for installing your ssh key on the remote host. Even if you do have the ssh-copy-id program, its good to do the manual installation at least once so that you have a good understanding of what is going on, because this is where a lot of people end up having problems.
Go ahead and copy your public key which is in ~/.ssh/id_dsa.pub to the remote machine.
scp ~/.ssh/id_dsa.pub username@arvo.suso.org:.ssh/authorized_keys
It will ask you for your system password on the remote machine and after authenticating it will transfer the file. You may have to create the .ssh directory in your home directory on the remote machine first. By the way, scp is a file transfer program that uses ssh. We'll talk more about it later.
Now when ssh to the remote machine, it should ask you for your key passphrase instead of your password. If it doesn't, it could be that the permissions and mode of the authorized_keys file and .ssh directory on the remote server need to be set more restrictively. You can do that with these commands on the remote server:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
You can also put the public key in the remote authorized_keys file by simply copying it into your paste buffer, logging into the remote machine and pasting it directly into the file from an editor like vi, emacs or nano. I would recommend using the 'cat' program to view the contents of the public key file though because using less will end up breaking the single line into multiple lines.
cat ~/.ssh/id_dsa.pub

Installing your public key automatically

A newer way that you can quite easily install your public ssh key on a remote host is with the ssh-copy-id program like this:
ssh-copy-id yourusername@your.website.com
It will prompt you for your password on the remote host and take care of the rest. That was easy. So why didn't I just tell you how to use this program in the first place? Well, in my experience, many of the problems people have with ssh revolve around trying to get their ssh public key installed correctly. Its a good thing that they've made a program to do the dirty work for you, but in the interest of building your skills, you should at least do the manual install once so that you know what is involved.

Using the ssh-agent program

The true usefulness of using key based authentication comes in the use of the ssh-agent program. Usually, the ssh-agent program is a program that starts up before starting X windows and in turn starts X windows for you. All X windows programs inherit a connection back to the ssh-agent, including your terminal windows like Gnome Terminal, Konsole, xfce4-terminal, aterm, xterm and so on. What this means is that after you've started up X windows through ssh-agent, you can use the ssh-add program to add your passphrase one time to the agent and the agent will in turn pass this authentication information automatically every time you need to use your passphrase. So the next time you run:
ssh username@arvo.suso.org
you will be logged in automatically without having to enter a passphrase or password. Most recent distributions will automatically start ssh-agent when you login to X windows through a session manager like gdm (graphical login). I found that as of this writing the following distributions started ssh-agent by default.
  • Debian
  • Fedora
  • Gentoo
  • SuSE
  • Ubuntu
Most distributions prior to about 2002 did not start it.
Don't worry if you don't see your distro listed in here. You can check if it is already running by running this command.
ps auxw
If there is an ssh-agent process listed there, then you can just start using it, otherwise, you should consult your distribution's documentation on OpenSSH and running the ssh-agent.
Once you've verified that ssh-agent is running, you can add your ssh key to it by running the ssh-add command:
ssh-add
If the program finds the DSA key that you created above, it will prompt you for the passphrase. Once you have done so it should tell you that it has added your identity to the ssh-agent:
Identity added: /home/username/.ssh/id_dsa (/home/username/.ssh/id_dsa)
Now you can try logging into that remote machine again and this time you will notice that it just logs you right in without prompting you for any password or passphrase.
To make adding your passphrase easier, you can add the ssh-add program to your desktop session startup programs and it will bring up a prompt in X windows to ask for your passphrase every time you login to your desktop. You should also have the gtk2-askpass program installed. Or x11-askpass. They are the real programs that actually prompt you for your password. ssh-add just runs them if its not being run in a terminal. Below is a screenshot of the Gnome Sessions Configuration dialog with ssh-add added to the startup programs.
Gnome Session with ssh-add program set to run and prompt for your key's passphrase


X11 Session Forwarding

One lesser known feature of X windows is its network transparency. It was designed to be able to transmit window and bitmap information over a network connection. So essentially you can login to a remote desktop machine and run some X windows program like Gnumeric, Gimp or even Firefox and the program will run on the remote computer, but will display its graphical output on your local computer.
To try this out, you will need an account on a remote computer that has X windows installed with some X windows applications. suso.org servers do not have any such programs so you will need to either login to one of your other workstations or another server that does have them. The key to making it work is using the -X option, which means "forward the X connection through the SSH connection". This is a form of tunneling.
ssh -X username@desktopmachine.domain.com
If this doesn't work, you may have to setup the SSH daemon on the remote computer to allow X11Forwarding, check that the following lines are set in /etc/ssh/sshd_config on that computer:
X11Forwarding yes X11DisplayOffset 10 X11UseLocalhost yes
For some newer programs and newer versions of X windows, you may need to use the -Y option instead for trusted X11 forwarding. Try using this option if your X11 windows program fails to start running with a message like this one that was for Gimp:
The program 'gimp-2.2' received an X Window System error. This probably reflects a bug in the program. The error was 'BadWindow (invalid Window parameter)'. (Details: serial 154 error_code 3 request_code 38 minor_code 0) (Note to programmers: normally, X errors are reported asynchronously; that is, you will receive the error a while after causing it. To debug your program, run it with the --sync command line option to change this behavior. You can then get a meaningful backtrace from your debugger if you break on the gdk_x_error() function.)

TCP Port Forwarding

Like X11 session forwarding, SSH can also forward other TCP application level ports both forward and backwards across the SSH session that you establish.
For example, you can setup a port forward for your connection from your home machine to arvo.suso.org so that it will take connections to localhost port 3306 and forward them to the remote side mysql.suso.org port 3306. Port 3306 is the port that the MySQL server listens on, so this would allow you to bypass the normal host checks that the MySQL server would make and allow you to run GUI MySQL programs on your local computer while using the database on your suso account. Here is the command to accomplish this:
ssh -L 3306:mysql.suso.org:3306 username@arvo.suso.org
The -L (which means Local port) takes one argument of
<local-port>:<connect-to-host>:<connect-to-port>
so you specify what host and port the connection will go to on the other side of the SSH connection. When you make a connection to the <local-port> port, it sends the data through the SSH connection and then connects to <connect-to-host>:<connect-to-port> on the other side. From the point of view of <connect-to-host>, its as if the connection came from the SSH server that you login to. In the case above, arvo.suso.org.
This is much like a VPN connection allows you to act like you are making connections from the remote network that you VPN into.
Take a moment to think of other useful connections you can make with this type of network tunnel.
Another useful one is for when you are away from home and can't send mail through your home ISP's mail server because it only allows local connections to block spam. You can create an SSH tunnel to an SSH server that is local to your ISP and then have your GUI mail client like Thunderbird make a connection to localhost port 8025 to send the mail. Here is the command to create the tunnel:
ssh -L 8025:smtp.homeisp.net:25 username@shell.homeisp.net
One thing to note is that non-root users do not normally have the ability to listen on network ports lower than 1024, so listening on port 25 would not work, thus we use 8025. It really doesn't matter, you can use any port as long as your email client can connect to it.
You can also reverse the direction and create a reverse port forward. This can be useful if you want to connect to a machine remotely to allow connections back in. For instance, I use this sometimes so that I can create a reverse port 22 (SSH) tunnel so that I can reconnect through SSH to a machine that is behind a firewall once I have gone away from that network.
ssh -R 8022:localhost:22 username@my.home.ip.address
This will connect to my home machine and start listening on port 8022 there. Once I get home, I can then connect back to the machine I created the connection from using the following command:
ssh -p 8022 username@localhost
Remember to use the right username for the machine that you started the tunnel from. It can get confusing. You also have to keep in mind that since you are connecting to the host called localhost, but its really a port going to a different SSH server, you may wind up with a different host key for localhost the next time you connect to localhost. In that case you would need to edit your .ssh/known_hosts file to remove the localhost line. You really should know more about SSH before doing this blindly.
As a final exercise, you can keep your reverse port forward open all the time by starting the connection with this loop:
while true ; do ssh -R 8022:localhost:22 suso@my.home.ip.address ; sleep 60 ; done
This way, if you happen to reboot your home machine, the reverse tunnel will try to reconnect after 60 seconds. Provided you've setup keys and your ssh-agent on the remote machine. ;-)

SOCKS5 proxying

So thats great and all, but eventually you are going to want to know how you can do tunneling without having to specify the address that you want to forward to.
This is accomplished through the -D SOCKS5 option.
ssh -D 9999 username@remotehost.net
Any application that supports the SOCKS5 protocol (and most of the big network programs do) can forward its network connection over SSH and dynamically forward to any hostname that you specify. So for a web browser, any URL that you type in the URL field, would be sent through the SSH tunnel. Firefox, Xchat, Gaim and many others all support using SOCKS5. The setting is usually under preferences in the connection settings.
Remember, in the words of Benjamin "Uncle Ben" Parker, with great power comes great responsibility. Just because you can get around firewalls and use other hosts for sending network traffic, doesn't mean that some system administrator isn't going to notice you.

Running Commands Over SSH

Sometimes you don't really want to run a shell like Bash on the host you are connecting to. Maybe you just want to run a command and exit. This is very simply accomplished by putting the command you wish to run at the end of your ssh connection command.
ssh username@remotehost.net ls -l /
This will probably generate output similar to the following.
total 220 drwxr-xr-x 2 root root 4096 Nov 9 04:08 bin drwxr-xr-x 3 root root 4096 Nov 11 09:29 boot drwxr-xr-x 23 root root 122880 Nov 14 02:36 dev drwxr-xr-x 68 root root 12288 Jan 10 04:03 etc drwxr-xr-x 189 root root 4096 Jan 9 00:40 home drwxr-xr-x 2 root root 4096 Mar 12 2004 initrd drwxr-xr-x 9 root root 4096 Nov 9 04:07 lib drwx------ 2 root root 16384 Sep 26 2004 lost+found drwxr-xr-x 2 root root 4096 Apr 14 2004 misc drwxr-xr-x 6 root root 4096 Nov 12 02:11 mnt drwxr-xr-x 3 root root 4096 Oct 15 22:17 opt dr-xr-xr-x 307 root root 0 Nov 14 02:36 proc drwx------ 44 root root 8192 Jan 9 16:23 root drwxr-xr-x 2 root root 8192 Nov 9 04:08 sbin drwxr-xr-x 2 root root 4096 Mar 12 2004 selinux drwxr-xr-x 9 root root 0 Nov 14 02:36 sys drwxrwxrwt 20 root root 4096 Jan 10 06:46 tmp drwxr-xr-x 17 root root 4096 Dec 7 2004 usr drwxr-xr-x 26 root root 4096 Jan 10 2005 var
Then you can process the output however you want using the normal shell conventions.
You can also do something called forced-command where you force any login attempt to run a specific command regardless of what is specified on the command line by the client.
To do this, you put this variable and the command you want to force in the authorized_keys file on the remote host:
command="/usr/bin/backup" ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAvna.....
Put the variable before the start of the line for the key. There are other variables you can use here like from="" to allow only from a specific host. These variables can be put together separated by commas.



(This space is intentionally left blank)



Using SCP

SCP is basically a program that uses the SSH protocol to send files between hosts over and encrypted connection. You can transfer files from your local computer to a remote host or vice versa or even from a remote host to another remote host.
Here is a basic command that copies a file called report.doc from the local computer to a file by the same name on the remote computer.
scp report.doc username@remote.host.net:
Note how the lack of a destination filename just preserves the original name of the file. This is also the case if the remote destination includes the path to a directory on the remote host.
To copy the file back from the server, you just reverse the from and to.
scp username@remote.host.net:report.doc report.doc
If you want to specify a new name for the file on the remote computer, simply give the name after the colon on the to side.
scp report.doc username@remote.host.net:monday.doc
Or if you want to copy it to a directory relative to the home directory for the remote user specified.
scp report.doc username@remote.host.net:reports/monday.doc
You can also use fullpaths which are preceded with a /.
To copy a whole directory recursively to a remote location, use the -r option. The following command copies a directory named mail to the home directory of the user on the remote computer.
scp -r mail username@remote.host.net:
Sometimes you will want to preserve the timestamps of the files and directories and if possible, the users, groups and permissions. To do this, use the -p option.
scp -rp mail username@remote.host.net:

Keeping Your SSH Session Alive

Sometimes you may have trouble keeping your SSH session up and idle. For whatever reason, the connection just dies after X minutes of inactivity. Usually this happens because there is a firewall between you and the internet that is configured to only keep stateful connections in its memory for 15 or so minutes.
Fortunately, in recent versions of OpenSSH, there is a fix for this problem. Simply put the following:
Host * Protocol 2 TCPKeepAlive yes ServerAliveInterval 60
in the file
~/.ssh/config
The file above can be used for any client side SSH configuration. See the ssh_config man page for more details. The 'TCPKeepAlive yes' directive tells the ssh client that it should send a little bit of data over the connection periodically to let the server know that it is still there. 'ServerAliveInterval 60' sets this time period for these messages to 60 seconds. This tricks many firewalls that would otherwise drop the connection, to keep your connection going.

Ending your SSH session

All good things come to an end. And there are many common ways to end your SSH session.
exit
logout
(Ctrl-d)
The last one is actually the user pressing the 'Ctrl' key and the letter 'd' at the same time. These all are ways of terminating the SSH session from the server side. They usually exit the shell which in turn logs you off the machine.
What you may not know, is that there is another way to close an SSH session. This is useful if you lose connectivity with the machine and you have no way of ending your shell session. For example, this happens momentarily if you stay logged into a machine while it is shutdown. SSH has its own command line escape sequences. These can be used to end connections, create new port forwards or list current ones and a few other functions. To end a connection even when you don't have a command prompt, type return twice (for good measure) and then the sequence '~.'. That's a tilde followed by a period.
(RETURN) (RETURN) ~.
This will terminate the SSH connection from the client end instead of the server end.
Happy SSH'ing!

External References

Here are some links where you can find more information about SSH

from http://support.suso.com/supki/SSH_Tutorial_for_Linux
--------------------------------------------------------------------

SSH Port Forwarding

by 

SSH (Secure SHell) is well known to Linux administrators as the de facto method for connecting to other systems. SSH long ago supplanted other connection methods because it strongly encrypts the connection between the hosts, ensuring that passwords and any transmitted data are safe from prying eyes. On Fedora® and Red Hat® Enterprise Linux® systems, and many other Linux distributions, the OpenSSH suite provides the programs for this purpose. An administrator typically runs SSH to login to another system, often to run a shell on the remote host and issue commands. SSH, however, has many extra tricks up its sleeve beyond simply securing a connection.

Table of Contents

Introduction
Local Port Forwarding
Secure Proxying
Service Administration
Remote Port Forwarding
A Remote Desktop Assistance Trick
Conclusion

Introduction

If you are relatively new to using SSH, this article will show you some useful tools for securing communications other than simply logging in to a remote host. If you have a login on another system, you can use SSH to securely route other traffic in an almost endless variety of other situations. One of these capabilities is called port forwarding.

IP Networking for Newbies

In Internet Protocol (IP) networking, any connection between two hosts is made from a port number at one host’s IP address to a port number at the other host’s address. Ports range from 0-65535, and some numbers are usually claimed by particular services. For instance, port 80 is typically used by a web (HTTP) server, and port 22 is typically used by a SSH server. You can see a list of well-known port numbers in the /etc/services file. Port numbers under 1024 are usually not available for users other than the administrator.
SSH port forwarding, essentially, is the art of causing a port from one host to appear on another, using a connection through SSH. Port forwarding can accomplish several goals at once, but one of the most compelling reasons to use the technique is that traffic to the forwarded port is encrypted.

Local Port Forwarding

When you forward a port locally, you make a port from the SSH server (the host to which you are connecting) available on your local machine (the host on which you’re running the ssh command). A port on the remote machine which would otherwise be unavailable to you for reasons of firewalling or other controls can be used just as if it was your local machine’s port. This port is presumably then available to other programs on your local host, outside the SSH session. That may seem a little confusing, but the following examples will hopefully give you a clearer understanding of how this technique works.

Secure Proxying

Imagine a situation where you need to conceal your web browsing traffic. Certainly many nefarious reasons for doing this come to mind immediately, but how about a legitimate one? Perhaps you are an on-site consultant and you don’t want your employer to know you’re Googling for an answer to a particularly difficult problem. Or maybe you’re visiting your company’s time registers from off-site.
If you have a remote host, say in your home office, that uses a squid web proxy, and is reachable by SSH, you can easily use local port forwarding to augment SSH with a secure proxy channel. Assume your remote host in the home office is known on the Internet as fedora1.mydomain.com. Let’s assume your web proxy at your home office, the host called proxy, uses port 1080; it need only be available to machines inside that network. Let’s further assume that you’re sitting inside the headquarters of IT sector giant example.com, at a host called codemonkey1.example.com.
To set up port forwarding in this case, issue this command:

ssh -L 1080:proxy:1080 username@fedora1.mydomain.com
At this point, you can set your web browser to use the proxy, using the host codemonkey1.example.com (or localhost) and port 1080. Your web browser connects to your local machine’s port 1080, but the connection is forwarded over the SSH session to fedora1 in your home office, which connects to proxy to make HTTP requests. Anyone at example.com watching traffic will see only SSH traffic between codemonkey1 and fedora1.mydomain.com.

Observe Site Security Policies

Obviously, connections like this, as well as any network traffic, should be governed by Example.com’s IT security policies. Having secure, encrypted web browsing is nice, but having a job is good, too!

Service Administration

Let’s try another example. Say that you have a web-based administration tool that runs on your codemonkey1 host in Example.com, using port 8888, but you wisely block access to this port for any hosts other than itself (as localhost). Unfortunately, you’ve been working at an off-site example.com location for a few hours, when an urgent page comes in from your boss that requires immediate access to your web administration tool.
Fortunately, you can access SSH on that box, so no worries: local port forwarding to the rescue again! Issue the following command:

ssh -L 8888:localhost:8888 username@codemonkey1
Note that the hostname localhost in the command above indicates the way that codemonkey1 refers to itself. If you now open up a web browser and point it at port 8888 on the system you’re using at the off-site, you’ll see your web-based administration tool, just as if you were back at the console in your own office.
Confusingly, you might type this in the web browser’s location bar as http://localhost:8888, but in this case, the term localhost is simply a way of telling the web browser to connect to the system on which it’s running. To recap, your host’s HTTP request connects to itself at port 8888, which is forwarded over the SSH session to codemonkey1, which then connects to itself at port 8888.

Remote Port Forwarding

When you forward a port remotely, you make a port on the client system available on the remote system. Like local forwarding, this technique allows you to work around security measures that might otherwise prevent an IP connection. However, since the port becomes available on the server side, a new vista of possibilities opens for networking, like the following example.

A Remote Desktop Assistance Trick

You may already know about vino, the slightly tweaked VNC server that allows one user to remotely view or assist with another user’s desktop. The vinoserver normally listens on port 5900 for a connection to the default X server. If you run multiple X servers (concurrent graphical logins), add the X display number to 5900 to find out the port number used, or simply use netstat -ltp and list the ports. A helpful friend or administrator can run the VNC client (vncviewer) to connect to the other desktop. But what if the server in question, and the user needing help, can’t be reached through normal means?
Imagine a friend of yours needs remote help, but is behind a router not under his control that prevents you from using SSH to login to his system. Your system fedora1.mydomain.com, however, is not similarly disadvantaged.
First, set up an account for your friend on fedora1, using a username and password you agree on over a relatively secure channel. (Your friend is free to change the password at first login using the passwd command or the appropriate graphical utility.) Then relay this command to your friend over IRC, instant messaging, email, or some other method:
ssh -R 5900:localhost:5900 friend@fedora1.mydomain.com
In the command above, the first port number 5900 represents the port that will be opened on the remote host (fedora1.mydomain.com. The hostname localhost is the hostname your friend’s system calls itself. (Recall that if your friend has systems with ports he can reach, such as on a local or remote network, he can forward their ports remotely too!) The second port number 5900 is the port number on your friend’s system where his vino server is running.
Important: If your system has a process using port 5900, such as your own vino server, your friend will have to choose port 5901 for the first port number above.
You can now assist your friend by running the command vncviewer localhost. If your friend had to forward to port 5901 instead, use localhost:1 instead; for port 5902, use localhost:2; and so forth. Thus you can have several remote connections open at once to help a number of people at a time.

Conclusion

The flexibility of port forwarding goes far beyond the bounds of this article. Hopefully, though, these examples will spark your interest if you are starting to explore port forwarding.
-----------------------------------------------------------------------
setting up an email session over ssh


My ISP provides an email account I still use, even though web-based mail has various advantages. I just prefer the Mail.app interface over the gmail interface. The account uses pop and smtp, as is typical. At home I this works reliably and well. Here’s the problem: if I leave my house and try to use this account from say, work, I can still download mail, but my ISP’s smtp server will not accept outgoing mail from outside its domain.
Here is how I solved the problem.
Besides my Mac, I have an Ubuntu box at home. One of its main purposes is to run an ssh server exposed to the outside world (port 22 on the Ubuntu box is the only port my router exposes). Among the many useful tricks ssh can perform is to provide a SOCKS proxy. It turns out to be a simple matter to use this proxy to solve my email problem.
To use my email account from the road, I simply bring up a console and enter the command:
ssh -D 2345 drc@myubuntubox
Once that session is established, I fire up a mail client configured to connect to the internet via a SOCKS proxy listening on port 2345 (there is nothing special about the port, it is just easy to remember). I use Thunderbird for this purpose, so not to have to hassle with changing Mail.app’s configuration back and forth.
--------------------------------------------------------------------------------------------------------

Multihop SSH with Putty/WinSCP

Introduction

It’s not always possible to ssh to a host directly. Many networks require high-value systems to be accessed via an intermediate bastion/proxy host that receives extra attention in terms of security controls and log monitoring. The added security provided by this connection bouncing comes with a cost in convenience, though. It requires multiple logins to access the protected systems and substantially complicates scp/stfp file transfers.
Fortunately, there are a number of ways to automate connection bouncing and make it as convenient as direct connection. There are already a number of web-sites detailing the approaches to this issue, and I won’t repeat their contents, to get a broad overview of the topic read the following:

Terminology

SSH Connection “Chaining”

Connection “chaining” refers to any approach that involves sshing to an intermediate host, and then sshing from the intermediate host to the next host (for example: ssh 1 'ssh 2 "ssh 3"'). This solution is attractive for setups with many hops because it’s easy to extend, for example sshto makes this very easy. The primary disadvantage is that end-to-end encryption is lost. The connection is decrypted by every host in the chain, and an attacker with sufficient privilege on an intermediate system can sniff the connection without compromising either of the endpoints. I consider this to be a significant failing, and have a strong preference for “stacked” connections wherever they are logistically feasible.

SSH Connection “Stacking”

Connection “stacking” refers to any solution that involves tunneling ssh connections inside each other. “Nesting” strikes me as a better term, but stacking seems to be more widely agreed upon. It is typically implemented with proxy-commands or with ssh port-forwarding. It can be more difficult to manage for connections with many hops, and it forces one of the endpoints to bear the encryption load of all the connections (in chained setups, the load is spread evenly among all the hosts in the chain). It does maintain end-to-end encryption, preventing connection/credential sniffing by intermediate hosts.

My Setup

The key properties for my setup are:
  • End-to-end encryption is maintained using stacked connections
  • Only a single intermediate host is involved, the proxy features I utilize do not trivially scale to longer connection paths
  • Putty is used for shell connections, and WinSCP is used for scp/sftp connections
  • No special software is required beyond a default Putty installation, WinSCP, and an SSH server with port forwarding enabled. Specifically, netcat is not required on the intermediate host as is common with ProxyCommand setups.

WinSCP Config

The WinSCP Config is quite simple and utilizes its “tunnel” feature. Open WinSCP and configure a saved session for the final destination host as follows:
  1. On the Session page, fill in the hostname and user name for the final destination host. Leave the password blank.
  2. Check the “Advanced options” box in the login dialog.
  3. Select the Connection –> Tunnel page.
  4. Check the “Connect through SSH tunnel” box.
  5. Fill in the Host name and user name of the intermediate host. Leave the password blank.
  6. Save the session using the button in the lower right-hand corner of the window.
When you log in using the new profile, you will be prompted for two passwords. The first is for your account on the intermediate host, and the second is for your account on the final-destination host. After login, the bounce is entirely transparent and WinSCP works as if you had connected directly to the final-destination host. The connection process can be made even more transparent and secure by using public key authentication with Pageant instead of passwords.

Putty Config

The Putty setup is slightly more complicated and requires that public key authentication be used on the intermediate host. It utilizes Putty’s “local proxy” feature, which allows you to specify an arbitrary command on the local machine to act as a proxy. Instead of creating a TCP connection, PuTTY will communicate using the proxy program’s standard input and output streams. Our local proxy will be plink, which is a command-line ssh connection program included in the Putty default installation. Plink’s -nc option provides functionality similar to the ProxyCommand/netcat approach, but does so using the ssh server’s native port-forwarding interface and does not require that netcat be installed on the intermediate system. To set things up, configure a saved session for the final destination host:
  1. Configure public key authentication for the intermediate host and make sure it works.
  2. Start putty and on the “Session” page of the “Putty Configuration Dialog” that appears, fill in the host name and user name for the final destination host.
  3. Switch to the Connection –> Proxy page, select “Local” as the proxy type enter the following as the local proxy command: plink.exe intermediate.proxy.host -l username -agent -nc %host:%port\n
  4. Save the session.
If all is working properly, when you log in using the new profile plink will handle the login to the intermediate system silently. Putty isn’t smart enough to prompt if the proxy command requires user input, so you’ll get a connection error if public key authentication on the intermediate host isn’t working. If you use password authentication on the final destination host you’ll be prompted for your password, or if you use pubkey authentication there as well you’ll land at a prompt with no fuss at all.
If you have trouble, make sure plink is executing properly. You may need to enter the full pathname, usually c:\program files\putty\plink.exe. You can also try executing the plink command from a prompt, remembering to substitute the %host and %port values of your final destination host. If it’s working properly, you’ll be logged into the intermediate system with your pageant-cached private key, and instead of a prompt you’ll be presented with the SSH banner for your final destination system.

from http://mikelococo.com/2008/01/multihop-ssh/