Indelible InkFresh Ink (iOS)2024-02-06T16:01:44+00:00https://www.indelible.org/ink/Jon PariseCopyright 1999-2024 by Jon Parise. All rights reserved.Enforcing Trusted SSL Certificates on iOS and OS X2012-10-24T00:00:00+00:00https://www.indelible.org/ink/trusted-ssl-certificatesJon Parise<p>One of the nice things about iOS and OS X networking is that it generally just
works. In particular, connecting to an SSL-protected host is a transparent
operation for high-level code based on <code class="language-plaintext highlighter-rouge">NSURLConnection</code>. As long as the
authenticity of the remote host’s public certificate can be verified, the
connection is considered trustworthy.</p>
<p>This broad definition of trust allows connections to arbitrary hosts without
requiring prior knowledge of those hosts’ certficates. This convenience is
generally desirable, but there are times when we want to restrict our trust to
a specific set of known certificates, not just any certificate signed by a
well-known authority or registered with the <a href="http://en.wikipedia.org/wiki/Keychain_(Mac_OS)">Keychain</a>.</p>
<p>For example, many iOS applications interact with a backend server component.
These connections can be “sniffed” by introducing <a href="http://www.charlesproxy.com/documentation/proxying/ssl-proxying/">proxy software</a>
between the iOS device and the rest of the network. While this can be a
wonderful development aid, it highlights the often misunderstood insecurity of
these otherwise “private” communication channels. This scenario is known as a
<a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">man-in-the-middle attack</a>. (It is also how the Siri protocol was
originally cracked.)</p>
<p>Fortunately, Apple includes all of the tools needed for an application to
evaluate the trusthworthiness of individual network connection attempts:</p>
<ul>
<li><a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLProtectionSpace_Class/Reference/Reference.html">NSURLProtectionSpace Class Reference</a></li>
<li><a href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html">NSURLAuthenticationChallenge Class Reference</a></li>
<li><a href="https://developer.apple.com/library/ios/#documentation/security/conceptual/CertKeyTrustProgGuide/01introduction/introduction.html">Certificate, Key, and Trust Services Programming Guide</a></li>
</ul>
<h2 id="trusted-certificates">Trusted Certificates</h2>
<p>To begin, the client application needs its own copy of the trusted server’s
public certificate. This should be in <a href="http://en.wikipedia.org/wiki/Distinguished_Encoding_Rules#DER_encoding">DER format</a> (which is just a
binary version of the more familiar <a href="http://en.wikipedia.org/wiki/Privacy_Enhanced_Mail">PEM format</a>). To convert a
certificate from PEM to DER format:</p>
<figure class="highlight"><pre><code class="language-console" data-lang="console"><span class="gp">$</span><span class="w"> </span>openssl x509 <span class="nt">-inform</span> PEM <span class="nt">-outform</span> DER <span class="nt">-in</span> cert.pem <span class="nt">-out</span> cert.der</code></pre></figure>
<p>Then add the certificate to the application’s resource bundle (or otherwise
encode it in the application binary). This is safe because it’s only the
public portion of the certificate; the private key remains private.</p>
<p>Note that bundling the server’s public certificate with the application does
introduce an ongoing maintenance concern. It will need to be updated whenever
the server’s certificate changes (such as after a renewal). But this is the
simplest approach for the illustrative purposes of this article.</p>
<h2 id="evaluating-server-trust">Evaluating Server Trust</h2>
<p>The application now needs a way to determine whether or not the remote host’s
certificate matches the bundled certificate. This is done by establishing a
chain of trust “anchored” on the local certificate. The server’s credentials
are accessed via the <code class="language-plaintext highlighter-rouge">NSURLProtectionSpace</code> interface.</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="n">BOOL</span><span class="p">)</span><span class="nf">shouldTrustProtectionSpace</span><span class="p">:(</span><span class="n">NSURLProtectionSpace</span> <span class="o">*</span><span class="p">)</span><span class="nv">protectionSpace</span> <span class="p">{</span>
<span class="c1">// Load up the bundled certificate.</span>
<span class="n">NSString</span> <span class="o">*</span><span class="n">certPath</span> <span class="o">=</span> <span class="p">[[</span><span class="n">NSBundle</span> <span class="nf">mainBundle</span><span class="p">]</span> <span class="nf">pathForResource</span><span class="p">:</span><span class="s">@"cert"</span> <span class="nf">ofType</span><span class="p">:</span><span class="s">@"der"</span><span class="p">];</span>
<span class="n">NSData</span> <span class="o">*</span><span class="n">certData</span> <span class="o">=</span> <span class="p">[[</span><span class="n">NSData</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithContentsOfFile</span><span class="p">:</span><span class="n">certPath</span><span class="p">];</span>
<span class="n">CFDataRef</span> <span class="n">certDataRef</span> <span class="o">=</span> <span class="p">(</span><span class="n">__bridge_retained</span> <span class="n">CFDataRef</span><span class="p">)</span><span class="n">certData</span><span class="p">;</span>
<span class="n">SecCertificateRef</span> <span class="n">cert</span> <span class="o">=</span> <span class="n">SecCertificateCreateWithData</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="n">certDataRef</span><span class="p">);</span>
<span class="c1">// Establish a chain of trust anchored on our bundled certificate.</span>
<span class="n">CFArrayRef</span> <span class="n">certArrayRef</span> <span class="o">=</span> <span class="n">CFArrayCreate</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="o">&</span><span class="n">cert</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
<span class="n">SecTrustRef</span> <span class="n">serverTrust</span> <span class="o">=</span> <span class="n">protectionSpace</span><span class="p">.</span><span class="n">serverTrust</span><span class="p">;</span>
<span class="n">SecTrustSetAnchorCertificates</span><span class="p">(</span><span class="n">serverTrust</span><span class="p">,</span> <span class="n">certArrayRef</span><span class="p">);</span>
<span class="c1">// Verify that trust.</span>
<span class="n">SecTrustResultType</span> <span class="n">trustResult</span><span class="p">;</span>
<span class="n">SecTrustEvaluate</span><span class="p">(</span><span class="n">serverTrust</span><span class="p">,</span> <span class="o">&</span><span class="n">trustResult</span><span class="p">);</span>
<span class="c1">// Clean up.</span>
<span class="n">CFRelease</span><span class="p">(</span><span class="n">certArrayRef</span><span class="p">);</span>
<span class="n">CFRelease</span><span class="p">(</span><span class="n">cert</span><span class="p">);</span>
<span class="n">CFRelease</span><span class="p">(</span><span class="n">certDataRef</span><span class="p">);</span>
<span class="c1">// Did our custom trust chain evaluate successfully?</span>
<span class="k">return</span> <span class="n">trustResult</span> <span class="o">==</span> <span class="n">kSecTrustResultUnspecified</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>
<h2 id="nsurlconnection">NSURLConnection</h2>
<p>Integrating the above code with an <code class="language-plaintext highlighter-rouge">NSURLConnection</code>-based system is easy.
First, the connection delegate needs to advertise its ability to authenticate
“server trust” protection spaces.</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="n">BOOL</span><span class="p">)</span><span class="nf">connection</span><span class="p">:(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="p">)</span><span class="nv">connection</span> <span class="nf">canAuthenticateAgainstProtectionSpace</span><span class="p">:(</span><span class="n">NSURLProtectionSpace</span> <span class="o">*</span><span class="p">)</span><span class="nv">protectionSpace</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">[</span><span class="n">protectionSpace</span><span class="p">.</span><span class="n">authenticationMethod</span> <span class="nf">isEqualToString</span><span class="p">:</span><span class="n">NSURLAuthenticationMethodServerTrust</span><span class="p">];</span>
<span class="p">}</span></code></pre></figure>
<p>Then, the connection delegate needs to handle the authentication challenge:</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">connection</span><span class="p">:(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="p">)</span><span class="nv">connection</span> <span class="nf">didReceiveAuthenticationChallenge</span><span class="p">:(</span><span class="n">NSURLAuthenticationChallenge</span> <span class="o">*</span><span class="p">)</span><span class="nv">challenge</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">([</span><span class="n">self</span> <span class="nf">shouldTrustProtectionSpace</span><span class="p">:</span><span class="n">challenge</span><span class="p">.</span><span class="n">protectionSpace</span><span class="p">])</span> <span class="p">{</span>
<span class="p">[</span><span class="n">challenge</span><span class="p">.</span><span class="n">sender</span> <span class="nf">useCredential</span><span class="p">:[</span><span class="n">NSURLCredential</span> <span class="nf">credentialForTrust</span><span class="p">:</span><span class="n">challenge</span><span class="p">.</span><span class="n">protectionSpace</span><span class="p">.</span><span class="n">serverTrust</span><span class="p">]</span> <span class="nf">forAuthenticationChallenge</span><span class="p">:</span><span class="n">challenge</span><span class="p">];</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="p">[</span><span class="n">challenge</span><span class="p">.</span><span class="n">sender</span> <span class="nf">performDefaultHandlingForAuthenticationChallenge</span><span class="p">:</span><span class="n">challenge</span><span class="p">];</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>Trust failures will result in a connection failure:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>The certificate for this server is invalid. You might be connecting
to a server that is pretending to be "api.example.com" which could
put your confidential information at risk.
</code></pre></div></div>
<h2 id="afnetworking">AFNetworking</h2>
<p><a href="http://afnetworking.com/">AFNetworking</a> implements the <code class="language-plaintext highlighter-rouge">NSURLConnectionDelegate</code> methods internally.
Fortunately, it also exposes a block-based interface for supplying custom
implementations of the necessary callbacks. These are applied directly to
<code class="language-plaintext highlighter-rouge">AFHTTPRequestOperation</code> objects, so a convenient place to set them is in a
custom <code class="language-plaintext highlighter-rouge">HTTPRequestOperation:success:failure:</code> implementation.</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="n">AFHTTPRequestOperation</span> <span class="o">*</span><span class="p">)</span><span class="nf">HTTPRequestOperationWithRequest</span><span class="p">:(</span><span class="n">NSURLRequest</span> <span class="o">*</span><span class="p">)</span><span class="nv">urlRequest</span>
<span class="nf">success</span><span class="p">:(</span><span class="kt">void</span> <span class="p">(</span><span class="o">^</span><span class="p">)(</span><span class="n">AFHTTPRequestOperation</span> <span class="o">*</span><span class="p">,</span> <span class="n">id</span><span class="p">))</span><span class="nv">success</span>
<span class="nf">failure</span><span class="p">:(</span><span class="kt">void</span> <span class="p">(</span><span class="o">^</span><span class="p">)(</span><span class="n">AFHTTPRequestOperation</span> <span class="o">*</span><span class="p">,</span> <span class="n">NSError</span> <span class="o">*</span><span class="p">))</span><span class="nv">failure</span> <span class="p">{</span>
<span class="n">AFHTTPRequestOperation</span> <span class="o">*</span><span class="n">operation</span> <span class="o">=</span> <span class="p">[</span><span class="n">super</span> <span class="nf">HTTPRequestOperationWithRequest</span><span class="p">:</span><span class="n">urlRequest</span> <span class="nf">success</span><span class="p">:</span><span class="n">success</span> <span class="n">failure</span><span class="o">:</span><span class="n">failure</span><span class="p">];</span>
<span class="c1">// Indicate that we want to validate "server trust" protection spaces.</span>
<span class="p">[</span><span class="n">operation</span> <span class="nf">setAuthenticationAgainstProtectionSpaceBlock</span><span class="p">:</span><span class="o">^</span><span class="n">BOOL</span><span class="p">(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">,</span> <span class="n">NSURLProtectionSpace</span> <span class="o">*</span><span class="n">protectionSpace</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="p">[</span><span class="n">protectionSpace</span><span class="p">.</span><span class="n">authenticationMethod</span> <span class="nf">isEqualToString</span><span class="p">:</span><span class="n">NSURLAuthenticationMethodServerTrust</span><span class="p">];</span>
<span class="p">}];</span>
<span class="c1">// Handle the authentication challenge.</span>
<span class="p">[</span><span class="n">operation</span> <span class="nf">setAuthenticationChallengeBlock</span><span class="p">:</span><span class="o">^</span><span class="p">(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">,</span> <span class="n">NSURLAuthenticationChallenge</span> <span class="o">*</span><span class="n">challenge</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">([</span><span class="n">self</span> <span class="nf">shouldTrustProtectionSpace</span><span class="p">:</span><span class="n">challenge</span><span class="p">.</span><span class="n">protectionSpace</span><span class="p">])</span> <span class="p">{</span>
<span class="p">[</span><span class="n">challenge</span><span class="p">.</span><span class="n">sender</span> <span class="nf">useCredential</span><span class="p">:[</span><span class="n">NSURLCredential</span> <span class="nf">credentialForTrust</span><span class="p">:</span><span class="n">challenge</span><span class="p">.</span><span class="n">protectionSpace</span><span class="p">.</span><span class="n">serverTrust</span><span class="p">]</span>
<span class="nl">forAuthenticationChallenge:</span><span class="n">challenge</span><span class="p">];</span>
<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="p">[</span><span class="n">challenge</span><span class="p">.</span><span class="n">sender</span> <span class="nf">performDefaultHandlingForAuthenticationChallenge</span><span class="p">:</span><span class="n">challenge</span><span class="p">];</span>
<span class="p">}</span>
<span class="p">}];</span>
<span class="k">return</span> <span class="n">operation</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>
Manually Loading nib Files2011-06-15T00:00:00+00:00https://www.indelible.org/ink/nib-loadingJon Parise<p><a href="http://en.wikipedia.org/wiki/Interface_Builder">Interface Builder</a> is the standard Mac OS and iOS user interface design
tool. Layouts are saved as “nib” (NeXT Interface Builder) files. Recent
versions of Interface Builder write these files as XML archives using the
<code class="language-plaintext highlighter-rouge">.xib</code> file extension.</p>
<p>At runtime, nib files are loaded and assigned an “owner” object that forms the
basis of the layout’s object hierarchy. This “owner” is very often a view
controller object. In this article, we’ll focus specifically on UIKit and its
<a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html"><code class="language-plaintext highlighter-rouge">UIViewController</code></a> class.</p>
<p>The nib loading process is generally abstracted away as part of the standard
<code class="language-plaintext highlighter-rouge">UIViewController</code> initialization process. Here’s a simple example:</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="n">id</span><span class="p">)</span><span class="n">init</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">((</span><span class="n">self</span> <span class="o">=</span> <span class="p">[</span><span class="n">super</span> <span class="nf">initWithNibName</span><span class="p">:</span><span class="s">@"SomeNib"</span> <span class="nf">bundle</span><span class="p">:</span><span class="nb">nil</span><span class="p">]))</span> <span class="p">{</span>
<span class="c1">// additional view controller initialization</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">self</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>
<p><code class="language-plaintext highlighter-rouge">-initWithNibName:bundle:</code> handles all of the nib loading and instantiation
work. While this is quite convenient, it has one major limitation: the nib
file must have been compiled and bundled (in the <code class="language-plaintext highlighter-rouge">NSBundle</code> sense) along with
the application itself. Fortunately, it is possible to manually load a nib
from arbitrary data and associate its contents with a view controller.</p>
<h2 id="the-uinib-class">The UINib Class</h2>
<p>The <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UINib_Ref/Reference/Reference.html"><code class="language-plaintext highlighter-rouge">UINib</code></a> class provides all of the functionality needed to
manually load nib files. One reason to do this is to pre-cache the contents
of a nib file in memory, ready for quick deserialization and instantiation
later in the application’s lifetime. Another reason (and our focus here) is
to load the raw nib data from an alternate (non-<code class="language-plaintext highlighter-rouge">NSBundle</code>) source.</p>
<p>The <code class="language-plaintext highlighter-rouge">UINib</code> class provides two methods for loading nibs:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">+nibWithNibName:bundle:</code> - load a bundled nib file</li>
<li><code class="language-plaintext highlighter-rouge">+nibWithData:bundle:</code> - load raw nib data</li>
</ul>
<p>Once loaded, the nib’s objects can be instantiated and assigned an owner using
the <code class="language-plaintext highlighter-rouge">-instantiateWithOwner:options:</code> instance method.</p>
<h2 id="manual-view-controller-loading">Manual View Controller Loading</h2>
<p>How can the <code class="language-plaintext highlighter-rouge">UINib</code> class be used in conjunction with a view controller?</p>
<p>First, the view controller needs to call <code class="language-plaintext highlighter-rouge">UIViewController</code>’s designated
initializer <em>without</em> a nib name. Note that passing <code class="language-plaintext highlighter-rouge">nil</code> as the nib name
will trigger an automatic lookup for a nib named the same as the view
controller class, so take care not to fall into that case unintentionally.</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="p">[</span><span class="n">super</span> <span class="nf">initWithNibName</span><span class="p">:</span><span class="nb">nil</span> <span class="nf">bundle</span><span class="p">:</span><span class="nb">nil</span><span class="p">]</span></code></pre></figure>
<p>Because this view controller hasn’t loaded a view during initialization, we
must implement the <code class="language-plaintext highlighter-rouge">-loadView</code> method. This is where all of the manual
loading is performed.</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">loadView</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">super</span> <span class="nf">loadView</span><span class="p">];</span>
<span class="n">UINib</span> <span class="o">*</span><span class="n">nib</span> <span class="o">=</span> <span class="p">[</span><span class="n">UINib</span> <span class="nf">nibWithNibName</span><span class="p">:</span><span class="s">@"SomeNib"</span> <span class="nf">bundle</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
<span class="p">[</span><span class="n">nib</span> <span class="nf">instantiateWithOwner</span><span class="p">:</span><span class="n">self</span> <span class="nf">options</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
<span class="p">}</span></code></pre></figure>
<p>This code effectively reproduces the standard nib loading process that was
previously being handled by <code class="language-plaintext highlighter-rouge">-initWithNibName:bundle:</code> itself.</p>
<h2 id="loading-raw-nib-data">Loading Raw nib Data</h2>
<p>At this point, our code is now manually loading the nib’s objects, but it’s
still reading the nib itself from our application bundle. We can go a step
further and load arbitrary nib data using the <code class="language-plaintext highlighter-rouge">+nibWithData:bundle:</code> method.</p>
<figure class="highlight"><pre><code class="language-objectivec" data-lang="objectivec"><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">loadView</span>
<span class="p">{</span>
<span class="p">[</span><span class="n">super</span> <span class="nf">loadView</span><span class="p">];</span>
<span class="n">NSData</span> <span class="o">*</span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSData</span> <span class="nf">dataWithContentsOfFile</span><span class="p">:</span><span class="s">@"SomeNib.xib.bin"</span><span class="p">];</span>
<span class="n">UINib</span> <span class="o">*</span><span class="n">nib</span> <span class="o">=</span> <span class="p">[</span><span class="n">UINib</span> <span class="nf">nibWithData</span><span class="p">:</span><span class="n">data</span> <span class="nf">bundle</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
<span class="p">[</span><span class="n">nib</span> <span class="nf">instantiateWithOwner</span><span class="p">:</span><span class="n">self</span> <span class="nf">options</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
<span class="p">}</span></code></pre></figure>
<p>The nib data can come from pretty much anywhere, such as from a bundled file
or a network-fetched resource. The only requirement is that the nib data be
compiled. To compile an existing <code class="language-plaintext highlighter-rouge">.xib</code> file, use <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/ibtool.1.html"><code class="language-plaintext highlighter-rouge">ibtool</code></a>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ibtool SomeNib.xib --compile SomeNib.xib.bin
</code></pre></div></div>
<h2 id="additional-considerations">Additional Considerations</h2>
<p>Now that the basic approach has been established, there are a few practical
considerations to keep in mind. First, we’ve largely ignored the <code class="language-plaintext highlighter-rouge">bundle</code>
parameter in the above code examples. This argument instructs the nib loader
where to look for dependent resources, such as images. Passing <code class="language-plaintext highlighter-rouge">nil</code> implies
that the main application bundle (<code class="language-plaintext highlighter-rouge">[NSBundle mainBundle]</code>) should be used.
There unfortunately doesn’t appear to be a way to redirect these lookups to
non-bundle locations, however.</p>
<p>Next, the nib data needs to be available by the time the view controller is
initialized. All I/O needs to block, and any stalls could result in a poor
user experience. Given that, any non-bundled nib data needs to be fetched
<em>before</em> the view is loaded.</p>
<p>Lastly, nibs can contain references to “external” objects. One such example
is the “owner” object, which is explicitly resolved by the call to
<code class="language-plaintext highlighter-rouge">-instantiateWithOwner:options:</code>. If the nib references any additional
external objects, the loading code must provide those objects via a dictionary
mapping passed through the <code class="language-plaintext highlighter-rouge">options:</code> interface’s <code class="language-plaintext highlighter-rouge">UINibExternalObjects</code> key.</p>
Password Composer for iPhone2009-10-25T00:00:00+00:00https://www.indelible.org/ink/iphone-pwdcomposerJon Parise<p>I often use <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/">Password Composer</a> (written by Johannes la Poutré)
to generate unique, per-site passwords. It does an excellent job because it’s
simple, unobtrusive, and reliable. The one downside is that you need to have
it available in order to (re)generate the password for a given web site, and
that isn’t always convenient, despite the large number of existing Password
Composer implementations.</p>
<p>The main place I find myself missing Password Composer is on my iPhone. The
only current solution that works from Mobile Safari is the <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/password_composer_form.html">public web-based
interface</a>, and I’m security-conscious enough to avoid using that version
whenever possible. I decided the only reasonable solution would be to find a
way to run Password Composer locally on my iPhone.</p>
<p>I first considered writing a full-blown native iPhone application. I know a
bit of Objective-C and have experimented with the iPhone SDK, but, additional
learning opportunities aside, this approach felt like overkill.</p>
<p>I then discovered the option of writing an iPhone-enhanced offline web
application. That would let me reuse Password Composer’s existing static web
form without having to work through the iPhone SDK. I found the early release
of Jonathan Stark’s <a href="http://building-iphone-apps.labs.oreilly.com/">Building iPhone Applications with HTML, CSS, and
JavaScript</a> and set out to adapt Password Composer to the iPhone.</p>
<h2 id="basic-application">Basic Application</h2>
<p>The basic application started as a single HTML file containing a form and some
JavaScript.</p>
<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><html></span>
<span class="nt"><head></span>
<span class="nt"><title></span>Password Composer<span class="nt"></title></span>
<span class="nt"></head></span>
<span class="nt"><body></span>
<span class="nt"><script </span><span class="na">type=</span><span class="s">"text/javascript"</span><span class="nt">></span>
<span class="c1">// Password Composer JavaScript</span>
<span class="nt"></script></span>
<span class="nt"><h1></span>Password Composer<span class="nt"></h1></span>
<span class="nt"><form></span>
<span class="nt"><table></span>
<span class="nt"><tr></span>
<span class="nt"><td></span>Master Key:<span class="nt"></td></span>
<span class="nt"><td><input</span> <span class="na">type=</span><span class="s">"password"</span> <span class="na">id=</span><span class="s">"masterpwd1"</span> <span class="na">onkeyup=</span><span class="s">"mpwd_generate()"</span>
<span class="na">onchange=</span><span class="s">"mpwd_generate()"</span><span class="nt">/></td></span>
<span class="nt"></tr></span>
<span class="nt"><tr></span>
<span class="nt"><td></span>Domain:<span class="nt"></td></span>
<span class="nt"><td><input</span> <span class="na">type=</span><span class="s">"text"</span> <span class="na">id=</span><span class="s">"domain1"</span> <span class="na">onkeyup=</span><span class="s">"mpwd_generate()"</span>
<span class="na">onchange=</span><span class="s">"mpwd_generate()"</span><span class="nt">/></td></span>
<span class="nt"></tr></span>
<span class="nt"><tr></span>
<span class="nt"><td></span>Password:<span class="nt"></td></span>
<span class="nt"><td><input</span> <span class="na">type=</span><span class="s">"text"</span> <span class="na">id=</span><span class="s">"genpwd1"</span> <span class="na">onkeyup=</span><span class="s">"mpwd_generate()"</span>
<span class="na">onchange=</span><span class="s">"mpwd_generate()"</span><span class="nt">/></td></span>
<span class="nt"></tr></span>
<span class="nt"></table></span>
<span class="nt"></form></span>
<span class="nt"></body></span>
<span class="nt"></html></span></code></pre></figure>
<p>The JavaScript and form were copied directly from Password Composer’s <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/password_composer_form.html">public
web-based interface</a> and worked just fine in Mobile Safari.</p>
<h2 id="styling-the-application">Styling the Application</h2>
<p>Next, I set about styling the look and feel of the page to more closely
resemble an iPhone application. I started by adding a stylesheet file. I
could have used inline CSS, and maybe I’ll merge the styles back into the main
page at some point in the future, but using a separate file keeps things more
manageable for the time being.</p>
<figure class="highlight"><pre><code class="language-css" data-lang="css"><span class="nt">body</span> <span class="p">{</span>
<span class="nl">background-color</span><span class="p">:</span> <span class="m">#ddd</span><span class="p">;</span>
<span class="nl">color</span><span class="p">:</span> <span class="m">#222</span><span class="p">;</span>
<span class="nl">font-family</span><span class="p">:</span> <span class="n">Helvetica</span><span class="p">;</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">14px</span><span class="p">;</span>
<span class="nl">margin</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="nt">h1</span> <span class="p">{</span>
<span class="nl">background-image</span><span class="p">:</span> <span class="n">-webkit-gradient</span><span class="p">(</span><span class="n">linear</span><span class="p">,</span> <span class="nb">left</span> <span class="nb">top</span><span class="p">,</span> <span class="nb">left</span> <span class="nb">bottom</span><span class="p">,</span>
<span class="n">from</span><span class="p">(</span><span class="m">#ccc</span><span class="p">),</span> <span class="n">to</span><span class="p">(</span><span class="m">#aaa</span><span class="p">));</span>
<span class="nl">background-color</span><span class="p">:</span> <span class="m">#ccc</span><span class="p">;</span>
<span class="nl">border-bottom</span><span class="p">:</span> <span class="m">1px</span> <span class="nb">solid</span> <span class="m">#666</span><span class="p">;</span>
<span class="nl">color</span><span class="p">:</span> <span class="m">#222</span><span class="p">;</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">20px</span><span class="p">;</span>
<span class="nl">font-weight</span><span class="p">:</span> <span class="nb">bold</span><span class="p">;</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">10px</span> <span class="m">0</span><span class="p">;</span>
<span class="nl">text-align</span><span class="p">:</span> <span class="nb">center</span><span class="p">;</span>
<span class="nl">text-decoration</span><span class="p">:</span> <span class="nb">none</span><span class="p">;</span>
<span class="nl">text-shadow</span><span class="p">:</span> <span class="m">0px</span> <span class="m">1px</span> <span class="m">0px</span> <span class="m">#ddd</span><span class="p">;</span>
<span class="p">}</span>
<span class="nt">form</span> <span class="p">{</span>
<span class="nl">background-color</span><span class="p">:</span> <span class="m">#FFFFFF</span><span class="p">;</span>
<span class="nl">border</span><span class="p">:</span> <span class="m">1px</span> <span class="nb">solid</span> <span class="m">#999999</span><span class="p">;</span>
<span class="nl">color</span><span class="p">:</span> <span class="m">#222222</span><span class="p">;</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">15px</span><span class="p">;</span>
<span class="nl">padding</span><span class="p">:</span> <span class="m">12px</span> <span class="m">10px</span><span class="p">;</span>
<span class="nl">margin</span><span class="p">:</span> <span class="m">10px</span><span class="p">;</span>
<span class="nl">-webkit-border-radius</span><span class="p">:</span> <span class="m">8px</span><span class="p">;</span>
<span class="p">}</span>
<span class="nt">td</span><span class="o">,</span> <span class="nt">input</span> <span class="p">{</span>
<span class="nl">font-size</span><span class="p">:</span> <span class="m">14px</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>
<p>Most of these styles are influenced by examples from <a href="http://building-iphone-apps.labs.oreilly.com/">Jonathan Stark’s
book</a>.</p>
<h3 id="viewport-definition">Viewport Definition</h3>
<p>The next change is the addition of a <code class="language-plaintext highlighter-rouge">viewport</code> meta tag:</p>
<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><meta</span> <span class="na">name=</span><span class="s">"viewport"</span> <span class="na">content=</span><span class="s">"user-scalable=no, width=device-width"</span> <span class="nt">/></span></code></pre></figure>
<p>This <code class="language-plaintext highlighter-rouge">viewport</code> definition convinces Mobile Safari not to rescale the HTML
content as though it were a “normal” 980px-wide web page.</p>
<h3 id="input-field-types">Input Field Types</h3>
<p>I was also interested in configuring the form’s <code class="language-plaintext highlighter-rouge"><input></code> fields to pop up the
most appropriate type of on-screen keyboard on the iPhone. <em>Master Key</em> was
already being recognized as a password field (<code class="language-plaintext highlighter-rouge">type=password</code>), but I wanted
the <em>Domain</em> field to use the iPhone’s special URL keyboard.</p>
<p><a href="http://www.bennadel.com/blog/1721-Default-To-The-Numeric-Email-And-URL-Keyboards-On-The-iPhone.htm">A little research</a> indicated that Mobile Safari recognizes a small
subset of the HTML5 input types, including the <code class="language-plaintext highlighter-rouge">url</code> type.</p>
<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><input</span> <span class="na">type=</span><span class="s">"url"</span> <span class="na">id=</span><span class="s">"domain1"</span><span class="nt">></span></code></pre></figure>
<h2 id="custom-icon">Custom Icon</h2>
<p>Because I want Password Composer to feel like a natural, first-class iPhone
application, it deserves to get a real icon. This icon is used when a link to
the application is saved to the user’s home screen. Home screen icons are
57×57 pixel PNG images.</p>
<p>There are two ways for a web application to specify its home screen icon:</p>
<ol>
<li>Provide a file named <code class="language-plaintext highlighter-rouge">apple-touch-icon.png</code> in the site’s root.</li>
<li>Add a <code class="language-plaintext highlighter-rouge"><link rel="apple-touch-icon" href="icon.png" /></code> tag to the page’s
<code class="language-plaintext highlighter-rouge"><head></code> block.</li>
</ol>
<p>I chose the second approach because I wasn’t planning on using an entire
domain to serve the Password Composer application. It also feels like better
encapsulation for a single-page web application.</p>
<h2 id="offline-application-cache">Offline Application Cache</h2>
<p>The last bit of work adds support for the iPhone’s offline application cache.
This cache allows the files used by a web-based applications to be stored
locally on the iPhone so that they can still be accessed when the phone
doesn’t have an active network connection. This “offline mode” is described
quite well in Stark’s book: <a href="http://building-iphone-apps.labs.oreilly.com/ch06.html">Chapter 6: Going Offline</a>.</p>
<p>Briefly, all that’s required is the creation of a “manifest” file, <a href="http://www.w3.org/TR/offline-webapps/">as
specified by HTML5</a>. My manifest file is named <code class="language-plaintext highlighter-rouge">pwdcomposer.manifest</code>:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>CACHE MANIFEST
index.html
iphone.css
icon.png
</code></pre></div></div>
<p>The manifest lists all of the files used by the web application. Manifest
files can be much more involved than this example. They can specify fallback
images for use when network-based files are inaccessible, for example. But
for my current purposes, the simple manifest above works great.</p>
<p>Manifest files must be served using the <code class="language-plaintext highlighter-rouge">text/cache-manifest</code> MIME type.
For Apache-like web servers, this can be configured using a directive like:</p>
<figure class="highlight"><pre><code class="language-apacheconf" data-lang="apacheconf">AddType text/cache-manifest .manifest</code></pre></figure>
<p>Lastly, the web page needs to specify its associated manifest file using the
<code class="language-plaintext highlighter-rouge">manifest</code> attribute of the <code class="language-plaintext highlighter-rouge"><html></code> element:</p>
<figure class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt"><html</span> <span class="na">manifest=</span><span class="s">"pwdcomposer.manifest"</span><span class="nt">></span></code></pre></figure>
<h2 id="deployment">Deployment</h2>
<p>All that is left to do is deploy the application. Simply serve up the source
files using a web server, and iPhone users can choose to bookmark the
application’s link just like they would for any other web page. The offline
application caching system will work automatically. When the iPhone is
connected to a network, Mobile Safari will attempt to fetch the original
manifest file to check for updates, but the application will otherwise be
running entirely from the cache, essentially making it a local iPhone
application.</p>
<p>My version is deployed here: <a href="https://www.indelible.org/pwdcomposer/">https://www.indelible.org/pwdcomposer/</a></p>
<p>The <a href="https://github.com/jparise/pwdcomposer">complete source code</a> is available on <a href="http://github.com/">GitHub</a>.</p>