<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule"
>
<channel>
	<title>G-Loaded Journal &#187; SSH</title>
	<atom:link href="http://www.g-loaded.eu/tag/ssh/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.g-loaded.eu</link>
	<description>An open-source software and technology related journal</description>
	<lastBuildDate>Mon, 05 Dec 2011 19:55:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
		<item>
		<title>Python SSH Server for UNIX Systems using Twisted.conch</title>
		<link>http://www.g-loaded.eu/2010/03/26/python-ssh-server-unix-twisted-conch/</link>
		<comments>http://www.g-loaded.eu/2010/03/26/python-ssh-server-unix-twisted-conch/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 20:27:00 +0000</pubDate>
		<dc:creator>George Notaras</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Administration]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Remote]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[SSH]]></category>
		<category><![CDATA[Twisted]]></category>
		<guid isPermaLink="false">http://www.g-loaded.eu/?p=1572</guid>
		<description><![CDATA[I can still recall the excitement of the first time I tried to access and administer a remote system using SSH. Accessing my shell at a remote machine securely, being able to do local and remote port forwarding in order to access remote services through encrypted tunnels, X forwarding, secure file transfers using scp or [...]]]></description>
			<content:encoded><![CDATA[<p>I can still recall the excitement of the first time I tried to access and administer a remote system using <strong>SSH</strong>. Accessing my shell at a remote machine securely, being able to do local and remote port forwarding in order to access remote services through encrypted tunnels, X forwarding, secure file transfers using <em>scp</em> or <em>sftp</em>, <a href="http://www.g-loaded.eu/2005/11/10/ssh-with-keys/">authentication using public key infrastructure</a> are just a few of the features that justify the excitement of the first time. The only <em>Secure Shell</em> server implementation I had used all that time was the <a href="http://www.openssh.com/">OpenSSH</a> server. Although this is an open-source project, the fact that it is written in C makes it extremely difficult for me to have fun with it by making any modifications in order to implement even simple things like command filtering. This is because I have never programmed in <strong>C</strong> and do not intend to learn how to do it in the foreseeable future. So what I&#8217;ve been looking for today was a server implementation of the <strong>SSH2 protocol</strong> written in <a href="http://python.org">Python</a>. Unfortunately, there is no such project ready for immediate use. I had to hack my own! After several hours of trial and error, having written dozens of sample scripts for testing, I finally created a minimal project, called <strong>RapidSSH</strong>, in order to demonstrate how to create a fully functional SSH server with just a few lines of Python code by using <em>Twisted.conch</em>, part of the <a href="http://twistedmatrix.com">Twisted Framework</a>. Read on&#8230;<br />
<span id="more-1572"></span><br />
At first, I tried to experiment with the <a href="http://twistedmatrix.com/documents/current/conch/examples/sshsimpleserver.py">sshsimpleserver.py</a> example script that exists on the Twisted homepage. But, soon I realized that this script is there just to give an idea about how to use <code>Twisted.conch</code> and also provide a sensible starting point for your own implementations. That script was not even close in having the functionality I had in mind. After spending some time examining the Twisted source code, I found a fantastic, but completely undocumented, module: <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/unix.py">twisted.conch.unix</a>. Having gained some experience by my experimentation with <code>sshsimpleserver.py</code> I managed to easily put the pieces together and come up with the SSH server implementation as shown below.</p>
<p>But first, let&#8217;s install some <strong>dependencies</strong>. I assume that you will try the code on a machine aimed for testing, so I won&#8217;t be using the system&#8217;s package manager but instead use <strong>easy_install</strong> to install the needed Python modules. Other commands like <em>pip</em> could be used as well. If you do not want to mess with your system-wide python installation, just use <strong>virtualenv</strong> and <strong>pip</strong>, but I won&#8217;t go into the details about how to use these tools in the current document.</p>
<p>Install the needed dependencies:</p>
<pre class="console">
easy_install pycrypto
easy_install pyasn1
easy_install pam
easy_install twisted
</pre>
<p>Make sure you have <strong>gcc</strong> installed, because it will be needed to complete the installation of Twisted and PyCrypto.</p>
<p>I have created a project for this code at <strong>Bitbucket</strong>, called <a href="http://bitbucket.org/gnotaras/rapidssh/">RapidSSH</a>. This will make it easier to share code and ideas about SSH server implementations in Python using Twisted.</p>
<p>Filename: <code>scripts/rapidsshd_unix.py</code></p>
<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># This file is part of rapidssh - http://bitbucket.org/gnotaras/rapidssh/</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># rapidssh - A set of Secure Shell (SSH) server implementations in Python</span>
<span style="color: #808080; font-style: italic;">#            using Twisted.conch, part of the Twisted Framework.</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># Copyright (c) 2010 George Notaras - http://www.g-loaded.eu</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># Permission is hereby granted, free of charge, to any person obtaining a copy</span>
<span style="color: #808080; font-style: italic;"># of this software and associated documentation files (the &quot;Software&quot;), to deal</span>
<span style="color: #808080; font-style: italic;"># in the Software without restriction, including without limitation the rights</span>
<span style="color: #808080; font-style: italic;"># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell</span>
<span style="color: #808080; font-style: italic;"># copies of the Software, and to permit persons to whom the Software is</span>
<span style="color: #808080; font-style: italic;"># furnished to do so, subject to the following conditions:</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># The above copyright notice and this permission notice shall be included in</span>
<span style="color: #808080; font-style: italic;"># all copies or substantial portions of the Software.</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR</span>
<span style="color: #808080; font-style: italic;"># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,</span>
<span style="color: #808080; font-style: italic;"># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE</span>
<span style="color: #808080; font-style: italic;"># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER</span>
<span style="color: #808080; font-style: italic;"># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,</span>
<span style="color: #808080; font-style: italic;"># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN</span>
<span style="color: #808080; font-style: italic;"># THE SOFTWARE.</span>
<span style="color: #808080; font-style: italic;">#</span>
<span style="color: #808080; font-style: italic;"># Initially based on the sshsimpleserver.py kindly published by:</span>
<span style="color: #808080; font-style: italic;"># Twisted Matrix Laboratories - http://twistedmatrix.com</span>
<span style="color: #808080; font-style: italic;">#</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">import</span> pam
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span>.<span style="color: black;">unix</span> <span style="color: #ff7700;font-weight:bold;">import</span> UnixSSHRealm
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">cred</span> <span style="color: #ff7700;font-weight:bold;">import</span> portal
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">cred</span>.<span style="color: black;">credentials</span> <span style="color: #ff7700;font-weight:bold;">import</span> IUsernamePassword
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">cred</span>.<span style="color: black;">checkers</span> <span style="color: #ff7700;font-weight:bold;">import</span> ICredentialsChecker
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">cred</span>.<span style="color: black;">error</span> <span style="color: #ff7700;font-weight:bold;">import</span> UnauthorizedLogin
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span>.<span style="color: black;">checkers</span> <span style="color: #ff7700;font-weight:bold;">import</span> SSHPublicKeyDatabase
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">conch</span>.<span style="color: black;">ssh</span> <span style="color: #ff7700;font-weight:bold;">import</span> factory, userauth, connection, keys, session
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">internet</span> <span style="color: #ff7700;font-weight:bold;">import</span> reactor, defer
<span style="color: #ff7700;font-weight:bold;">from</span> zope.<span style="color: black;">interface</span> <span style="color: #ff7700;font-weight:bold;">import</span> implements
<span style="color: #ff7700;font-weight:bold;">from</span> twisted.<span style="color: black;">python</span> <span style="color: #ff7700;font-weight:bold;">import</span> log
&nbsp;
<span style="color: #808080; font-style: italic;"># Logging</span>
<span style="color: #808080; font-style: italic;"># Currently logging to STDERR</span>
log.<span style="color: black;">startLogging</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">stderr</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Server-side public and private keys. These are the keys found in</span>
<span style="color: #808080; font-style: italic;"># sshsimpleserver.py. Make sure you generate your own using ssh-keygen!</span>
&nbsp;
publicKey = <span style="color: #483d8b;">'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBEvLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHRivcJSkbh/C+BR3utDS555mV'</span>
&nbsp;
privateKey = <span style="color: #483d8b;">&quot;&quot;&quot;-----BEGIN RSA PRIVATE KEY-----
MIIByAIBAAJhAK8ycfDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW
4sbUIZR/ZXzY1CMfuC5qyR+UDUbBaaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fw
vgUd7rQ0ueeZlQIBIwJgbh+1VZfr7WftK5lu7MHtqE1S1vPWZQYE3+VUn8yJADyb
Z4fsZaCrzW9lkIqXkE3GIY+ojdhZhkO1gbG0118sIgphwSWKRxK0mvh6ERxKqIt1
xJEJO74EykXZV4oNJ8sjAjEA3J9r2ZghVhGN6V8DnQrTk24Td0E8hU8AcP0FVP+8
PQm/g/aXf2QQkQT+omdHVEJrAjEAy0pL0EBH6EVS98evDCBtQw22OZT52qXlAwZ2
gyTriKFVoqjeEjt3SZKKqXHSApP/AjBLpF99zcJJZRq2abgYlf9lv1chkrWqDHUu
DZttmYJeEfiFBBavVYIF1dOlZT0G8jMCMBc7sOSZodFnAiryP+Qg9otSBjJ3bQML
pSTqy7c3a2AScC/YyOwkDaICHnnD3XyjMwIxALRzl0tQEKMXs6hH8ToUdlLROCrP
EhQ0wahUTCk1gKA4uPD6TMTChavbh4K63OvbKg==
-----END RSA PRIVATE KEY-----&quot;&quot;&quot;</span>
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> PamPasswordDatabase:
    <span style="color: #483d8b;">&quot;&quot;&quot;Authentication/authorization backend using the 'login' PAM service&quot;&quot;&quot;</span>
    credentialInterfaces = IUsernamePassword,
    implements<span style="color: black;">&#40;</span>ICredentialsChecker<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> requestAvatarId<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, credentials<span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">if</span> pam.<span style="color: black;">authenticate</span><span style="color: black;">&#40;</span>credentials.<span style="color: black;">username</span>, credentials.<span style="color: black;">password</span><span style="color: black;">&#41;</span>:
            <span style="color: #ff7700;font-weight:bold;">return</span> defer.<span style="color: black;">succeed</span><span style="color: black;">&#40;</span>credentials.<span style="color: black;">username</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> defer.<span style="color: black;">fail</span><span style="color: black;">&#40;</span>UnauthorizedLogin<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;invalid password&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> UnixSSHdFactory<span style="color: black;">&#40;</span>factory.<span style="color: black;">SSHFactory</span><span style="color: black;">&#41;</span>:
    publicKeys = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">'ssh-rsa'</span>: keys.<span style="color: black;">Key</span>.<span style="color: black;">fromString</span><span style="color: black;">&#40;</span>data=publicKey<span style="color: black;">&#41;</span>
    <span style="color: black;">&#125;</span>
    privateKeys = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">'ssh-rsa'</span>: keys.<span style="color: black;">Key</span>.<span style="color: black;">fromString</span><span style="color: black;">&#40;</span>data=privateKey<span style="color: black;">&#41;</span>
    <span style="color: black;">&#125;</span>
    services = <span style="color: black;">&#123;</span>
        <span style="color: #483d8b;">'ssh-userauth'</span>: userauth.<span style="color: black;">SSHUserAuthServer</span>,
        <span style="color: #483d8b;">'ssh-connection'</span>: connection.<span style="color: black;">SSHConnection</span>
    <span style="color: black;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Components have already been registered in twisted.conch.unix</span>
&nbsp;
portal = portal.<span style="color: black;">Portal</span><span style="color: black;">&#40;</span>UnixSSHRealm<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
portal.<span style="color: black;">registerChecker</span><span style="color: black;">&#40;</span>PamPasswordDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>   <span style="color: #808080; font-style: italic;"># Supports PAM</span>
portal.<span style="color: black;">registerChecker</span><span style="color: black;">&#40;</span>SSHPublicKeyDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>  <span style="color: #808080; font-style: italic;"># Supports PKI</span>
UnixSSHdFactory.<span style="color: black;">portal</span> = portal
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    reactor.<span style="color: black;">listenTCP</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">5022</span>, UnixSSHdFactory<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    reactor.<span style="color: black;">run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>
<p>Some notes:</p>
<ul>
<li>The server uses the very same public and private keys as found in the <code>sshsimpleserver.py</code> script. Make sure you generate new keys using <strong>ssh-keygen</strong> if you plan to run this on a public server (although this not recommended).</li>
<li>Twisted included a module for PAM authentication, <code>twisted.cred.pamauth</code>, but unfortunately I could not locate one of its dependencies to make it work. So, I used the excellent <a href="http://atlee.ca/software/pam/">python-pam</a> to create a custom PAM authenticator class.</li>
<li>I can guess what you might thought when you read about this code:<br />
<blockquote>Python is a cross-platform programming language. Twisted runs on Windows. So, is this a solution for running a SSH server on Win32?</p></blockquote>
<p> Well, at the moment it won&#8217;t run because internally it uses some Python modules that are available on UNIX platforms only. But, I intend to investigate the possibility of running this on <strong>Windows</strong> since I already need something like that.</li>
</ul>
<p>We can now enjoy our Python SSH server. Run as root:</p>
<pre class="console">
python scripts/rapidsshd_unix.py
</pre>
<p>From another machine, connect to the server using an <em>ssh client</em>:</p>
<pre class="console">
ssh -p 5022 rocky@arena
</pre>
<p>If you have deployed your public key in the <code>~/.ssh/authorized_keys</code> file on the remote machine (<em>arena</em>), you should be able to authenticate using the public key:</p>
<pre class="console">
ssh -p 5022 -i /path/to/private.key rocky@arena
</pre>
<p>You should get output like the following on the server:</p>
<pre class="console">
[root@arena ~]# python ssh.py
2010-03-26 21:30:05+0000 [-] Log opened.
2010-03-26 21:30:05+0000 [-] __main__.UnixSSHdFactory starting on 5022
2010-03-26 21:30:05+0000 [-] Starting factory <__main__.UnixSSHdFactory instance at 0xb7a0b0cc>
2010-03-26 21:30:13+0000 [__main__.UnixSSHdFactory] disabling diffie-hellman-group-exchange because we cannot find moduli file
2010-03-26 21:30:13+0000 [SSHServerTransport,0,192.168.0.172] kex alg, key alg: diffie-hellman-group1-sha1 ssh-rsa
2010-03-26 21:30:13+0000 [SSHServerTransport,0,192.168.0.172] outgoing: aes256-ctr hmac-sha1 none
2010-03-26 21:30:13+0000 [SSHServerTransport,0,192.168.0.172] incoming: aes256-ctr hmac-sha1 none
2010-03-26 21:30:14+0000 [SSHServerTransport,0,192.168.0.172] NEW KEYS
2010-03-26 21:30:14+0000 [SSHServerTransport,0,192.168.0.172] starting service ssh-userauth
2010-03-26 21:30:17+0000 [SSHService ssh-userauth on SSHServerTransport,0,192.168.0.172] rocky trying auth none
2010-03-26 21:30:17+0000 [SSHService ssh-userauth on SSHServerTransport,0,192.168.0.172] rocky trying auth publickey
2010-03-26 21:30:17+0000 [SSHService ssh-userauth on SSHServerTransport,0,192.168.0.172] rocky trying auth publickey
2010-03-26 21:30:17+0000 [SSHService ssh-userauth on SSHServerTransport,0,192.168.0.172] rocky authenticated with publickey
2010-03-26 21:30:17+0000 [SSHService ssh-userauth on SSHServerTransport,0,192.168.0.172] starting service ssh-connection
2010-03-26 21:30:17+0000 [SSHService ssh-connection on SSHServerTransport,0,192.168.0.172] got channel session request
2010-03-26 21:30:17+0000 [SSHChannel session (0) on SSHService ssh-connection on SSHServerTransport,0,192.168.0.172] channel open
2010-03-26 21:30:17+0000 [SSHChannel session (0) on SSHService ssh-connection on SSHServerTransport,0,192.168.0.172] pty request: xterm (24L, 80L, 0L, 0L)
2010-03-26 21:30:17+0000 [SSHChannel session (0) on SSHService ssh-connection on SSHServerTransport,0,192.168.0.172] getting shell
</pre>
<p>This first release of the <a href="http://bitbucket.org/gnotaras/rapidssh/">RapidSSH</a> project exists solely for demonstration purposes. Don&#8217;t get fooled by the small amount of code. Information about how to put the pieces together is scarce and it required a lot trial&#038;error and source code reading. The above implementation contains none of the customizations I had in mind. These will be done as soon as I find some time to do so. Until then it will be nice to hear about your experiences or implementations you have worked on.</p>
<div class="cc-block"><em><a href="http://www.g-loaded.eu/2010/03/26/python-ssh-server-unix-twisted-conch/">Python SSH Server for UNIX Systems using Twisted.conch</a></em>, unless otherwise expressly stated, is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License</a>. Terms and conditions beyond the scope of this license may be available at <a href="http://www.g-loaded.eu/about/disclaimer-and-license/">www.g-loaded.eu</a>.</div>
<h4>Related Articles</h4>
<ul><li><a href="http://www.g-loaded.eu/2006/09/23/use-python-to-get-the-web-page-data-in-epiphany/" rel="bookmark">Use Python to get the web page data in Epiphany</a></li>
<li><a href="http://www.g-loaded.eu/2006/05/17/epiphany-python-console-open-new-tab/" rel="bookmark">Epiphany Python Console &#8211; Open New Tab</a></li>
<li><a href="http://www.g-loaded.eu/2007/01/31/python-irc-bot/" rel="bookmark">Python IRC Bot</a></li>
<li><a href="http://www.g-loaded.eu/2006/04/07/python-crash-course/" rel="bookmark">Python Crash Course</a></li>
<li><a href="http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/" rel="bookmark">Set up the VNC Server in Fedora</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.g-loaded.eu/2010/03/26/python-ssh-server-unix-twisted-conch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Set up the VNC Server in Fedora</title>
		<link>http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/</link>
		<comments>http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/#comments</comments>
		<pubDate>Thu, 10 Nov 2005 13:28:16 +0000</pubDate>
		<dc:creator>George Notaras</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Administration]]></category>
		<category><![CDATA[Encryption]]></category>
		<category><![CDATA[HOWTO]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Remote]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Servers]]></category>
		<category><![CDATA[SSH]]></category>
		<category><![CDATA[VNC]]></category>
		<guid isPermaLink="false">http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/</guid>
		<description><![CDATA[This article describes in brief how to configure VNC server instances for one or multiple users on a remote machine, how to use VNC to start graphical applications on boot and finally how to enhance security by connecting to the server through encrypted SSH tunnels.]]></description>
			<content:encoded><![CDATA[<p>&quot;<em><strong>Virtual Network Computing (VNC)</strong> is a desktop protocol to remotely control another computer. It transmits the keyboard presses and mouse clicks from one computer to another relaying the screen updates back in the other direction, over a network.</em>&quot; -WikiPedia-</p>
<p>This article describes in brief how to configure <strong>VNC server</strong> instances for one or multiple users on a remote machine, how to use <strong>VNC</strong> to start graphical applications on boot and finally how to enhance <strong>security</strong> by connecting to the server through encrypted <strong>SSH</strong> tunnels.<br />
<span id="more-93"></span></p>
<h4>Prerequisites</h4>
<p>A <strong>user account</strong> should exist on the remote machine.<br />
The RPM packages <strong>vnc-server</strong> and <strong>vnc</strong> should be installed on the remote machine and your workstation respectively.</p>
<h4>Setting up the server</h4>
<p>I assume that we have setup a remote user account, named &quot;<strong>leopard</strong>&quot; and we want to start an X session through VNC for this user.</p>
<p>In Fedora Core or Red Hat based distros in general, all we have to do is define the VNC server instances in <strong>/etc/sysconfig/vncservers</strong>. These will be started by the vncserver initscript. This has to be done <strong>as root</strong>. Edit this file so that it contains the following:</p>
<pre class="codesnp">VNCSERVERS=&quot;3:leopard&quot;
VNCSERVERARGS[3]=&quot;-geometry 1024x768 -depth 16&quot;</pre>
<p>With these we define that a vnc server instance should be started as user leopard on <strong>display 3</strong> and we also set some options for this server such as <strong>resolution</strong> and <strong>color depth</strong>. Each VNC server instance <em>listens on port 5900 plus the display number</em> on which the server runs. In our case, leopard&#8217;s vnc server would listen on <strong>port 5903</strong>.</p>
<p>For multiple vnc instances <strong>/etc/sysconfig/vncservers</strong> would look like this:</p>
<pre class="codesnp">VNCSERVERS=&quot;1:tiger 2:albatros 3:leopard&quot;
VNCSERVERARGS[1]=&quot;-geometry 1024x768 -depth 16&quot;
VNCSERVERARGS[2]=&quot;-geometry 800x600 -depth 8&quot;
VNCSERVERARGS[3]=&quot;-geometry 1024x768 -depth 16&quot;</pre>
<p>These would listen on ports <strong>5901</strong>, <strong>5902</strong>, <strong>5903</strong> respectively.</p>
<h4>User Configuration</h4>
<p>There is one more thing that needs to be done on the remote machine. User leopard&#8217;s vnc password needs to be set. So, as user leopard give the command:</p>
<pre class="console"># vncpasswd</pre>
<p>We are prompted for a password. This is the password that we will use when we connect to leopard&#8217;s vnc server instance. This password is saved in <strong>/home/leopard/.vnc/passwd</strong>.</p>
<h4>Start the VNC server</h4>
<p>After the initial configuration is done we restart the vnc service. As root:</p>
<pre class="console"># service vncserver restart</pre>
<p>To make VNC server to start on boot:</p>
<pre class="console"># chkconfig vncserver on</pre>
<h4>More User Configuration</h4>
<p>After the VNC service is started, some new files are created in <strong>/home/leopard/.vnc/</strong> directory. These include leopard&#8217;s vnc server log file, pid file and an X startup script. As user leopard we edit the script in order to customize some settings. The default <strong>/home/leopard/.vnc/xstartup</strong> script contains some commands that are executed when the VNC server is started. These include:</p>
<pre class="codesnp">xsetroot -solid grey
vncconfig -iconic &#38;
xterm -geometry 80x24+10+10 -ls -title &quot;$VNCDESKTOP Desktop&quot; &#38;
twm &#38;</pre>
<p><strong>xsetroot</strong> in this case sets the background color.<br />
<strong>vncconfig</strong> is a supplementary program that can be used to control the vnc server. Apart from this, when run without arguments it acts as a helper application and its main purpose is to provide support for clipboard transfers between the client (vncviewer) and the vnc server.<br />
<strong>xterm</strong> starts an xterm terminal.<br />
<strong>twm</strong> starts the X server&#8217;s default window manager. We probably want to change that to a more user friendly window manager, eg fluxbox.</p>
<p>The VNC server, apart from letting us control a remote machine using a graphical interface, it <strong>serves as a way to start graphical applications on boot</strong>. For example, I want my favourite p2p program, amule, to start on boot. So, I add this to the <strong>/home/leopard/.vnc/xstartup</strong> script. This is how my xstartup file looks like:</p>
<pre class="codesnp">xsetroot -solid grey
vncconfig -iconic &#38;
xterm -geometry 80x24+10+10 -ls -title &quot;$VNCDESKTOP Desktop&quot; -e ./menu &#38;
amule &#38;
fluxbox &#38; </pre>
<p><strong>menu</strong> is a script of mine that is executed when xterm is started.<br />
Remember to put the &quot;<strong>&#38;</strong>&quot; symbol after each command, so that it goes to the background and the xstartup script continues on.</p>
<p>Restart the VNC service for the changes to take effect. As root:</p>
<pre class="console"># service vncserver restart</pre>
<h4>Connect to the VNC server</h4>
<p>In our example, leopard&#8217;s vnc server listens for connections on port <strong>5903</strong>. So, <span style="text-decoration:underline;">open this port</span> in the remote machine&#8217;s firewall.</p>
<p>We connect to the remote machine using a vnc viewer. Having installed the <strong>vnc</strong> package, connect to to the server with the following command:</p>
<pre class="console"># vncviewer 192.168.0.1:5903:3</pre>
<p>The general usage is :</p>
<pre class="codesnp">vncviewer [Server's IP]:[Port]:[Display]</pre>
<p>We are prompted for the password and eventually connect to the server. Closing the vncviewer&#8217;s window, does not affect the server or the programs we run on it. If we reconnect everything will be there.</p>
<p><em><span style="text-decoration:underline;">Special Note:</span></em> There is no need, actually it&#8217;s pointless and could give you some trouble, to logoff from your remote X session. If this happens, generally you need to restart the VNC service on the remote machine to get your remote desktop back. If you want to stop working on your remote desktop, just close the vncviewer&#8217;s window and you are done.</p>
<h4>Security</h4>
<p>The VNC protocol is not a secure communication protocol. The use of a vnc password provides security at the level of server access (it&#8217;s vulnerable to brute-force attacks though), but the whole VNC session is transmitted in the clear, without encryption. The easiest, but most effective, way to secure our connection to the VNC server is to connect through an encrypted <strong>SSH tunnel</strong>. This way the whole session will be encrypted.</p>
<p>The rest assume that you have the SSH server up and running on your remote machine (server.example.com) and you know what SSH tunnels are.</p>
<p>So, what we are going to do is to create an encrypted tunnel, and connect to our VNC server through it. We also want this tunnel to be <strong>automatically closed</strong> as soon as we shut down vncviewer. All this is done with the following command:</p>
<pre class="console"># ssh -f -L 25903:127.0.0.1:5903 leopard@server.example.com sleep 10; vncviewer 127.0.0.1:25903:3</pre>
<p>This is what it does:</p>
<ul>
<li><strong>-L 25903:127.0.0.1:5903</strong> forwards our local port 25903 to port 5903 on the remote machine. In other words, it creates the tunnel.</li>
<li><strong>-f</strong> forks the SSH session to the background, while <strong>sleep</strong> is being executed on the remote machine. This ssh option is needed because we want to execute the following command (vncviewer) in the same <em>local</em> machine&#8217;s terminal.</li>
<li><strong>vncviewer</strong> connects to the forwarded local port 25903 in order to connect to the VNC server through the encrypted tunnel.</li>
</ul>
<p>The <strong>sleep</strong> command is of major importance in the above line as it keeps the encrypted tunnel open for 10 seconds. If no application uses it during this period of time, then it&#8217;s closed. Contrariwise, if an application uses it during the 10 sec period, then the tunnel remains open until this application is shut down. This way the tunnel is <strong>automatically closed</strong> at the time we close vncviewer&#8217;s window, without leaving any SSH processes running on our workstation. This is pure convenience! More information can be found at the <a href="http://www.g-loaded.eu/2006/11/24/auto-closing-ssh-tunnels/">Auto-closing SSH Tunnels</a> article.</p>
<p>Using SSH tunnels to conect to your VNC server has two advantages:</p>
<ol>
<li>The whole session is encrypted.</li>
<li>Keeping port 5903 open on your remote machine <em>is no longer needed</em>, since all take place through the SSH tunnel. So, noone will know that you run a VNC server on the remote machine.</li>
</ol>
<h4>Further Reading</h4>
<p>I recommend that you read the man pages. Everything is in there:</p>
<pre>
# man vncserver
# man Xvnc
# man vncconfig
# man vncviewer
# man ssh
</pre>
<div class="cc-block"><em><a href="http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/">Set up the VNC Server in Fedora</a></em>, unless otherwise expressly stated, is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License</a>. Terms and conditions beyond the scope of this license may be available at <a href="http://www.g-loaded.eu/about/disclaimer-and-license/">www.g-loaded.eu</a>.</div>
<h4>Related Articles</h4>
<ul><li><a href="http://www.g-loaded.eu/2005/10/20/ssh-tunnels-headaches/" rel="bookmark">SSH Tunnels Headaches</a></li>
<li><a href="http://www.g-loaded.eu/2006/11/24/auto-closing-ssh-tunnels/" rel="bookmark">Auto-closing SSH tunnels</a></li>
<li><a href="http://www.g-loaded.eu/2005/11/10/ssh-with-keys/" rel="bookmark">Setup the SSH server to use keys for authentication</a></li>
<li><a href="http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples/" rel="bookmark">Netcat &#8211; a couple of useful examples</a></li>
<li><a href="http://www.g-loaded.eu/2010/03/26/python-ssh-server-unix-twisted-conch/" rel="bookmark">Python SSH Server for UNIX Systems using Twisted.conch</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Setup the SSH server to use keys for authentication</title>
		<link>http://www.g-loaded.eu/2005/11/10/ssh-with-keys/</link>
		<comments>http://www.g-loaded.eu/2005/11/10/ssh-with-keys/#comments</comments>
		<pubDate>Thu, 10 Nov 2005 13:13:12 +0000</pubDate>
		<dc:creator>George Notaras</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Administration]]></category>
		<category><![CDATA[Encryption]]></category>
		<category><![CDATA[HOWTO]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Public Keys]]></category>
		<category><![CDATA[Remote]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Servers]]></category>
		<category><![CDATA[SSH]]></category>
		<guid isPermaLink="false">http://www.g-loaded.eu/2005/11/10/ssh-with-keys/</guid>
		<description><![CDATA[In this article I describe how to configure the SSH server, so that users authenticate using keys, how to generate DSA keys using ssh-keygen, how to configure ssh-agent and finally how to use ssh-add to manage cached passphrases.]]></description>
			<content:encoded><![CDATA[<p>&quot;<em><strong>Secure Shell</strong> or <strong>SSH</strong> is both a computer program and an associated network protocol designed for logging into and executing commands on a networked computer.</em>&quot; -WikiPedia-</p>
<p>An SSH server can be set up in various ways, but in this document I&#8217;ll describe how it can be configured to:</p>
<ul>
<li>only support connections through the 2nd version of the SSH protocol (SSH-2)</li>
<li>use DSA keys for user authentication, without permitting authentication with passwords</li>
<li>allow only a specific group of users to connect</li>
</ul>
<p><span id="more-91"></span><br />
The SSH-2 protocol, apart from many other useful features, provides stronger security than SSH-1. It&#8217;s a bit more cpu hungry than the latter, but this should not be a problem. Using the above configuration, someone must be extremely lucky to manage to break into our system.</p>
<p>But, let me say a few words about how the authentication is done. The user creates a keypair, which consists of a private key, that can be protected with a passphrase, and a public key. The public key is transfered to the server and the private key is kept in our workstation. We assume that the user has accounts in both the server machine and his workstation. Everytime he tries to connect to the server, the keys are validated and the user is granted access.</p>
<h4>Prerequisites</h4>
<p>A <strong>user account</strong> in the SSH server machine.</p>
<p>You need to install the following packages to the SSH server machine:</p>
<ul>
<li>openssh</li>
<li>openssh-server</li>
</ul>
<p>The client machines should have the following:</p>
<ul>
<li>openssh</li>
<li>openssh-clients</li>
</ul>
<h4>First things first&#8230;</h4>
<p>I assume that our server machine (<strong><em>server.example.com</em></strong>) is a headless one and that the SSH server is up and running with the default configuration. This permits users, including root, to login with their username/password combination. I also assume that we have already set up a user account on the server with the username &quot;<strong><em>leopard</em></strong>&quot;. From a client machine (<strong><em>pc1.example.com</em></strong>) we connect like this:</p>
<pre class="console"># ssh leopard@server.example.com</pre>
<h5>Keypair generation</h5>
<p>The default key directory is &quot;<strong>~/.ssh</strong>&quot;. Create this directory <strong>in both</strong> the user leopard&#8217;s home on the server and in your current home directory on the client machine and chmod it so that only the users have access to it.</p>
<pre class="console"># mkdir ~/.ssh
# chmod 0700 ~/.ssh</pre>
<p>Now, we will create our keypair <span style="text-decoration:underline;">on our client machine</span>. The following command creates a standard 1024-bit DSA keypair:</p>
<pre class="console"># ssh-keygen -t dsa -f ~/.ssh/id_dsa</pre>
<p>You will be asked for a <strong>passphrase</strong> for the private key. You can type any phrase here or leave it blank. Keep in mind that if you do not set a passphrase for you private key and someone else gets access to it, then it will take him only a few seconds to connect to your user account on the server. Anyway, this is up to you. After the key generation is finished, the files <strong>id_dsa</strong> (private key) and <strong>id_dsa.pub</strong> (public key) are created in the <strong>~/.ssh/</strong> directory.</p>
<p>Now, we will copy the public key to the <em>/home/leopard/.ssh/</em> directory on the server saving it with the name <strong>authorized_keys</strong> and delete id_dsa.pub from our client machine, just because it&#8217;s not needed to be there.</p>
<pre class="console"># scp ~/.ssh/id_dsa.pub leopard@server.example.com:~/.ssh/authorized_keys
# rm -f ~/.ssh/id_dsa.pub</pre>
<p>Make sure that you chmod both keys so that only the respective users have access to them. Issue the following command on <strong>both</strong> the server and the client machine:</p>
<pre class="console"># chmod 0600 ~/.ssh/*</pre>
<h5>A limited group of SSH users</h5>
<p>As an extra security measure, we will create a new group <span style="text-decoration:underline;">on the server machine</span> and configure the SSH server to only allow this group&#8217;s members to authenticate. So, we create a group named &quot;<strong>sshusers</strong>&quot; and add user &quot;<strong>leopard</strong>&quot; to it. This has to be done as root:</p>
<pre class="console"># groupadd sshusers
# usermod -a -G sshusers leopard</pre>
<h4>The SSH Server configuration</h4>
<p>The SSH server&#8217;s configuration file is <strong>/etc/ssh/sshd_config</strong>. Most of the default options do not need to be modified. What we&#8217;ll do is to set it up so that only the members of the &quot;<strong>sshusers</strong>&quot; group can authenticate using keys instead of passwords. So, as root, fire up your favourite text editor and edit the server configuration file.<br />
<em>NOTE</em>: It&#8217;s a good habit to create backups before editing system files.<br />
The options that need to be modified are shown below:</p>
<pre class="codesnp">
Port 22
Protocol 2
AddressFamily inet
ListenAddress 192.168.0.1</pre>
<p>With these we configure the server to listen on port 22, accept connections only over the SSH-2 protocol, use the IPv4 address family and bind on the 192.168.0.1 IP address. Only the &quot;<strong>protocol</strong>&quot; option is really critical. You can set the others as you like or leave the defaults.</p>
<pre class="codesnp">HostKey /etc/ssh/ssh_host_dsa_key</pre>
<p>Uncomment or add this line. This is exactly the same as the default option, but needs to be uncommented in the server configuration file, so that the server shows its DSA key&#8217;s fingerprint when the client tries to authenticate the server during the connection process. If this is not set, then the server shows its RSA key&#8217;s fingerprint (the reason is unknown to me).</p>
<pre class="codesnp">
LoginGraceTime 2m
PermitRootLogin no
MaxAuthTries 1</pre>
<p>The <strong>LoginGraceTime</strong> option sets a time limit for the user authentication process. If this time passes and the user has not yet authenticated succesfully, then the server closes the connection. Leave this value to the default &quot;<span style="text-decoration:underline;">2m</span>&quot; until everything is set up properly, so that you have enough time to read any server messages. After that, you can lower it to a reasonable value. I have set it to &quot;<span style="text-decoration:underline;">20s</span>&quot;.<br />
Setting the &quot;<strong>PermitRootLogin</strong>&quot; option to &quot;<span style="text-decoration:underline;">no</span>&quot; the server does not allow root to login directly. You can still use &quot;<strong>su</strong>&quot; after you have succesfully logged in as a normal user.<br />
The &quot;<strong>MaxAuthTries</strong>&quot; option sets the maximum login attempts per connection. Since we use keys and key validation never fails, we set it to &quot;1&quot;.</p>
<pre class="codesnp">
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys</pre>
<p>These are the default options. I just add them here so that you make sure they are set up properly in your config.</p>
<pre class="codesnp">
RSAAuthentication no
PasswordAuthentication no
UsePAM no
KerberosAuthentication no
GSSAPIAuthentication no</pre>
<p>We do not want the server to let users authenticate using passwords or use SSH-1 based authentication methods. You should comment out any Kerberos or GSSAPI options too.</p>
<pre class="codesnp">AllowGroups sshusers</pre>
<p>Only users that belong to the &quot;<strong>sshusers</strong>&quot; group can authenticate. Any other user will be rejected without even being given the oportunity to authenticate.</p>
<pre class="codesnp">MaxStartups 2</pre>
<p>This option specifies the maximum number of concurrent unauthenticated connections to the SSH Server. It has nothing to do with the number of authenticated connections. The default value is &quot;10&quot;. We lower this value in order to limit the connections from third parties which do not have an account on our server machine.</p>
<pre class="codesnp">Banner /etc/ssh/banner</pre>
<p>Finaly, you can set a text file that will be displayed as a banner when someone connects to the server. Just remember that it is displayed before the authentication takes place, so do not be very descriptive. The banner is not really needed.</p>
<p>This is all we have to do. The rest of the configuration options should be left to their default values, unless you need something different. This is up to you.</p>
<h5>Restarting the server</h5>
<p>Now, that we have finished editing the config file, we need to restart the server, so that our changes take effect. Before that, I would recommend deleting any existing server keys. Don&#8217;t worry, they will be recreated as soon as the service is restarted. A quick way to delete all the keys is to:</p>
<pre class="console"># rm -f ssh_host*key*</pre>
<p>Then restart the server:</p>
<pre class="console"># service sshd restart</pre>
<p>Note that the key creation time may vary from machine to machine, so it may take a few minutes if the CPU is slow.</p>
<p>The server logging is done through syslog and authentication information is sent to <em>/var/log/secure</em>. This file should not be world-readable.</p>
<p>A last thing is to take a note of the server&#8217;s DSA public key fingerprint, so that we can compare it with the fingerprint the server sends to our client when we connect. This is important for connections to the server from locations other than our LAN in order to be sure that we actually connect to our server. On the server console type:</p>
<pre class="console"># ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub</pre>
<p>Take a note of the fingerprint.</p>
<h4>Connect to the server</h4>
<p>To connect to our SSH server from our client machine (pc1.example.com), we type:</p>
<pre class="console"># ssh leopard@server.example.com</pre>
<p>I suggest that the first time you connect you should add the <strong>-v</strong> option to the above command for verbose output.</p>
<p>Before the user authentication takes place, the ssh client will try to authenticate the SSH server. Since, there is no stored information about your server it will present you the server&#8217;s public DSA key fingerprint so you can compare it with the fingerprint you had previously taken a note of during the server configuration. If the fingerprints are identical, you can answer positively to the question. At this time the file <strong>~/.ssh/known_hosts</strong> is created on your client machine and it contains the trusted SSH server&#8217;s information. You will never be asked again if you trust this server. If the fingerprint comparison took you longer than the server&#8217;s <strong>LoginGraceTime</strong>, the user authentication does not take place. Just try to reconnect. This time you will eventually log in succesfully using key authentication.</p>
<h5>Hashing the known_hosts file</h5>
<p>Because the servers&#8217; hostnames and addresses are stored in plain text in the <strong>known_hosts</strong> file, hashing it is a good habit. This can be done using the ssh-keygen utility. Type:</p>
<pre class="console"># ssh-keygen -H -f ~/.ssh/known_hosts</pre>
<p>This process makes it unreadable, but the ssh programs can still read the contents. Make sure you permanently delete the <strong>known_hosts.old</strong> backup file.</p>
<h5>Change your private key&#8217;s passphrase</h5>
<p>If you ever need to change the private key&#8217;s passphrase you can use ssh-keygen:</p>
<pre class="console"># ssh-keygen -p -f ~/.ssh/id_dsa</pre>
<h4>The ssh-agent</h4>
<p>Although key authentication has many advantages over the authentication with passwords, it has one significant drawback: we have to type the passphrase every time we make a connection to the SSH server. One solution would be not to use a passphrase for our private key. But, this is unacceptable. If someone else gets access to our key and finds out to which servers we connect, things get really bad. A second solution is to use the <strong>ssh-agent</strong> (part of the openssh package) which caches our passphrase in the memory and then it&#8217;s automatically used when we make the connection to the SSH server. This way, we only need to type the passphrase once. This is by far more secure than not using a passphrase.</p>
<p>The ssh-agent is a small daemon that runs in the background. When it is run, it exports some environment variables (SSH_AUTH_SOCK, SSH_AGENT_PID) which can be used by programs like <strong>ssh-add</strong> in order to manage the agent&#8217;s cached info or by other programs like the <strong>ssh client</strong> in order to use this cached info for user authentication. These environment variables must be available to these programs, so the ssh-agent needs to be started in our login shell. There are many different ways to start the agent. Here I&#8217;ll describe a rather simple, but very efficient one.</p>
<h5>The ssh-agent&#8217;s configuration</h5>
<p>What we need is to start the agent when we login to our client machine&#8217;s shell and stop it when we log out. So, we add the following line to <strong>~/.bash_profile</strong>:</p>
<pre class="codesnp">eval `ssh-agent`</pre>
<p>Why do we use <strong>eval</strong>? When the ssh-agent is started, it just prints some commands to the stdout. These commands set and export the environment variables we talked about earlier. We use eval, so that these commands are actually executed, or better, evaluated by the shell, so the environment variables are made available to all applications that can use them.</p>
<p>We add the following line to <strong>~/.bash_logout</strong></p>
<pre class="codesnp">eval `ssh-agent -k`</pre>
<p>This &quot;unsets&quot; the environment variables and kills the agent every time we logout.</p>
<h5>Management of cached passphrases</h5>
<p>A small utility called <strong>ssh-add</strong> is used to manage the cached passphrases.</p>
<p>To add a key to the ssh-agent&#8217;s cache, we issue the command:</p>
<pre class="console"># ssh-add ~/.ssh/id_dsa</pre>
<p>We are prompted for the passphrase. After typing it succesfully, it gets cached. From now on, the cached passphrase will be automatically used for every connection we make to the SSH server. Convenient!<br />
If we store our key to the standard location <em>~/.ssh/</em> and name it with the standard filename <em>id_dsa</em>, then ssh-add can be run without arguments. Our key will be used.</p>
<p>To list the cached keys we type:</p>
<pre class="console"># ssh-add -l</pre>
<p>To remove a cached key:</p>
<pre class="console"># ssh-add -d ~/.ssh/id_dsa</pre>
<p>To empty the ssh-agent&#8217;s cache:</p>
<pre class="console"># ssh-add -D</pre>
<h4>Further Reading</h4>
<p>There are numerous articles around the web about SSH. Just use google. Keep in mind though that all the necessary info is in the man pages. You should not just read them, but rather study them:</p>
<ol>
<li><a href="http://www.openssh.org/manual.html">The official openssh manuals</a></li>
<li><a href="http://www.openssh.org/faq.html">The openssh FAQ</a></li>
</ol>
<p><small>This article appeared in the <a href="http://digg.com/">digg.com</a> homepage on November 16th, 2005. I thank all &#8220;diggers&#8221; by heart.</small></p>
<div class="cc-block"><em><a href="http://www.g-loaded.eu/2005/11/10/ssh-with-keys/">Setup the SSH server to use keys for authentication</a></em>, unless otherwise expressly stated, is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License</a>. Terms and conditions beyond the scope of this license may be available at <a href="http://www.g-loaded.eu/about/disclaimer-and-license/">www.g-loaded.eu</a>.</div>
<h4>Related Articles</h4>
<ul><li><a href="http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/" rel="bookmark">Set up the VNC Server in Fedora</a></li>
<li><a href="http://www.g-loaded.eu/2005/11/10/be-your-own-ca/" rel="bookmark">Be your own Certificate Authority (CA)</a></li>
<li><a href="http://www.g-loaded.eu/2006/11/24/auto-closing-ssh-tunnels/" rel="bookmark">Auto-closing SSH tunnels</a></li>
<li><a href="http://www.g-loaded.eu/2010/03/26/python-ssh-server-unix-twisted-conch/" rel="bookmark">Python SSH Server for UNIX Systems using Twisted.conch</a></li>
<li><a href="http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples/" rel="bookmark">Netcat &#8211; a couple of useful examples</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.g-loaded.eu/2005/11/10/ssh-with-keys/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>SSH Tunnels Headaches</title>
		<link>http://www.g-loaded.eu/2005/10/20/ssh-tunnels-headaches/</link>
		<comments>http://www.g-loaded.eu/2005/10/20/ssh-tunnels-headaches/#comments</comments>
		<pubDate>Thu, 20 Oct 2005 12:45:34 +0000</pubDate>
		<dc:creator>George Notaras</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Encryption]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Remote]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Shell]]></category>
		<category><![CDATA[SSH]]></category>
		<category><![CDATA[Tips]]></category>
		<guid isPermaLink="false">http://www.g-loaded.eu/?p=58</guid>
		<description><![CDATA[I&#8217;m writing a VNC mini howto and I got stuck with something. I wanted to do the following with a single command: create the SSH tunnel (local port forwarding) execute vncviewer on the local machine have the SSH tunnel to be automatically closed at the time vncviewer was closed After about one hour of trial [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m writing a VNC mini howto and I got stuck with something. I wanted to do the following with a single command:</p>
<ul>
<li>create the SSH tunnel (local port forwarding)</li>
<li>execute vncviewer on the local machine</li>
<li>have the SSH tunnel to be <strong>automatically</strong> closed at the time vncviewer was closed</li>
</ul>
<p><span id="more-58"></span><br />
After about one hour of trial and error and man page reading, I ended up with a very useful line of code:</p>
<pre class="console">ssh -f -L 25930:127.0.0.1:5904 -C me@remote sleep 10; vncviewer 127.0.0.1:25930:4</pre>
<p>What this does is:</p>
<ul>
<li>forwards local port 25930 to remote port 5904</li>
<li>forks the ssh session to the background executing a sleep command on the remote machine</li>
<li>executes vncviewer so that it connects to the vnc server through the tunnel</li>
</ul>
<p>What I badly needed was a way to auto-close the tunnel at the time vncviewer was closed. This seems to do it. The <strong>sleep</strong> command keeps the tunnel open for ten seconds. After this period of time it&#8217;s closed, unless vncviewer or some other application uses it. In this case, it is closed at the time this application stops using it. Pretty fu..ing cool!! I have wasted all my head&#8217;s juice until I managed to figure this out&#8230;</p>
<div class="cc-block"><em><a href="http://www.g-loaded.eu/2005/10/20/ssh-tunnels-headaches/">SSH Tunnels Headaches</a></em>, unless otherwise expressly stated, is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License</a>. Terms and conditions beyond the scope of this license may be available at <a href="http://www.g-loaded.eu/about/disclaimer-and-license/">www.g-loaded.eu</a>.</div>
<h4>Related Articles</h4>
<ul><li><a href="http://www.g-loaded.eu/2006/11/24/auto-closing-ssh-tunnels/" rel="bookmark">Auto-closing SSH tunnels</a></li>
<li><a href="http://www.g-loaded.eu/2005/11/10/configure-vnc-server-in-fedora/" rel="bookmark">Set up the VNC Server in Fedora</a></li>
<li><a href="http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples/" rel="bookmark">Netcat &#8211; a couple of useful examples</a></li>
<li><a href="http://www.g-loaded.eu/2005/11/10/ssh-with-keys/" rel="bookmark">Setup the SSH server to use keys for authentication</a></li>
<li><a href="http://www.g-loaded.eu/2006/04/08/linux-tips-pack-i/" rel="bookmark">Linux Tips &#8211; Pack I</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.g-loaded.eu/2005/10/20/ssh-tunnels-headaches/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/</creativeCommons:license>
	</item>
	</channel>
</rss>

