Skip to content

Commit

Permalink
Refactor API to prepare for bundle-update feature
Browse files Browse the repository at this point in the history
- Updated / improved README
- Added Sslurp::VERSION / Sslurp::getSystemCaRootBundlePath()
- Improved system bundle path detection
- Changed private properties to protected (helps with unit testing)
- Removed public static properties in userland classes in favor of mock
  classes that extend the userland classes for testing.
- Loosened regex for version/date match to allow checking some distro
  bundle file versions.
- CaRootPemBundle now wraps an SplFileObject instead of just the bundle
  string.
- Updated unit tests
  • Loading branch information
EvanDotPro committed Sep 17, 2012
1 parent 846b88f commit 497ea16
Show file tree
Hide file tree
Showing 18 changed files with 308 additions and 195 deletions.
116 changes: 60 additions & 56 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,67 +6,29 @@ v1.0 by Evan Coury

## Introduction

Dealing with SSL properly in PHP is a pain in the ass. Sslurp aims to make it
suck less. Sslurp can be used as a stand-alone library or a ZF2 module.
Dealing with SSL properly in PHP is a pain in the ass and completely insecure by default. Sslurp aims to make it easier to use SSL in PHP safely and securely. Sslurp can be used as a stand-alone library, CLI tool, or a ZF2 module.

**Note:** This library requires PHP with OpenSSL support. This is standard in
most Linux distributions' PHP packages, else you need to ensure you compile
using --with-openssl[=DIR].
**Note:** Sslurp requires PHP with OpenSSL support. This is standard in most Linux distributions' PHP packages, otherwise you need to compile PHP using --with-openssl[=DIR].

## Installation

### Composer / Packagist

```
./composer.phar require evandotpro/sslurp
```

### Normal

The `./bin/update-ca-bundle` CLI tool will "just work" out of the box.

Sslurp can _easily_ be used in any existing project, framework, or library.

To use Sslurp as a library in your project, the easiest method is to simply
include the `autoload_register.php` file:

```php
require_once 'vendor/Sslurp/autoload_register.php';
```
## Features / Usage

Alternatively, if you project supports loading classmap arrays, you may fetch
the classmap without registering an additional SPL autoloader:
### Root CA bundle management

```php
$classmap = include 'vendor/Sslurp/autoload_classmap.php';
// Register $classmap with your project's existing classmap autoloader
```
Sslurp provides CLI and OOP interfaces for generating a trusted root Certificate Authority (CA) bundle using [certdata.txt](http:https://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1) from the source tree of Mozilla's [Network Security Services (NSS) libraries](https://www.mozilla.org/projects/security/pki/nss/) and keeping it up-to-date. The resulting root CA bundle includes the certificates vetted according to the [Mozilla Root Certificate Program](http:https://www.mozilla.org/projects/security/certs/policy/) — the same root CA bundle trusted by cURL, Firefox, Chrome, and many other applications, libraries, languages, and operating systems.

If you have an existing SPL autoloader that allows adding a callable to a stack
instead of directly registering the classmap array, you have the option of
simply getting a closure which can autoload the Sslurp classes:
Sslurp takes additional steps to protect against MITM attacks while fetching certdata.txt from Mozilla's source tree, ensuring that the generated bundle is truly authentic. When connecting to Mozilla's mxr.mozilla.org domain to fetch the updated certdata.txt, Sslurp forces the use of verified SSL. Sslurp uses the following process to establish the initial trust of the SSL certificate on mxr.mozilla.org:

```php
$sslurpLoader = include 'vendor/Sslurp/autoload_function.php';
// $sslurpLoader is a closure that can be registered with an existing autoloader
```
* Check the SSL\_CERT\_FILE environment variable (used by OpenSSL). If the value is the path to a readable file and valid certificate bundle, Sslurp will use it.
* If the SSL\_CERT\_FILE is not set or points to a non-existent / invalid certificate bundle, Sslurp will search several known/expected locations for the root CA bundle and use the first valid bundle found.
* If a valid bundle is not found in any of the expected paths, Sslurp will finally fall back to using a bundled, pre-verified copy of the root CA's public key which established trust for the mxr.mozilla.org certificate (Equifax Secure Certificate Authority at least until November 2013).

## Usage
As if that's not enough, Sslurp _additionally_ makes use of [public key pinning](http:https://tools.ietf.org/html/draft-ietf-websec-key-pinning-02) to further authenticate the authenticity of communications with Mozilla's mxr.mozilla.org domain. If the public key pin for mxr.mozilla.org changes before the expiration date of the current certificate, Sslurp will being to throw an exception, and refuse to update the root CA bundle. If the public key pin changes within the final month or after the expiration date of their current certificate (November, 2013), Sslurp will begin throwing a PHP notice encouraging you to update your copy of Sslurp to get the latest pin.

**You are STRONGLY ENCOURAGED to be using the latest version of Sslurp at all times.**

### CLI root CA bundle updater

[update-ca-bundle](https://github.com/EvanDotPro/Sslurp/blob/master/bin/update-ca-bundle)
is a handy command-line tool for fetching and building a PEM certificate bundle
from the latest trusted CAs in the [Mozilla source
tree](https://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt).
It bootstraps the initial trust of the mxr.mozilla.org SSL certificate using
[key pinning](http:https://tools.ietf.org/html/draft-ietf-websec-key-pinning-02) in
addition to verifying the key with either the system's trusted CA root bundle
or, as a fallback, the included Equifax\_Secure\_CA.pem public key. This
approach minimizes the possibility of MITM attacks at any point during the
process so that you can have a very high certainty that the CA bundle built is
authentic and has not been tampered with.
[./bin/update-ca-bundle](https://github.com/EvanDotPro/Sslurp/blob/master/bin/update-ca-bundle) is a handy command-line tool for fetching, building, and subsequently updating a root CA bundle in PEM format for use with PHP's OpenSSL support, curl, libcurl, php\_curl, etc. The output generated is fully compatible with the [mk-ca-bundle.pl](https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl) which is used to [generate cURL's trusted bundle](http:https://curl.haxx.se/docs/caextract.html).

```
Sslurp Root CA Bundle Updater
Expand All @@ -81,15 +43,13 @@ Options
### Using Sslurp as a library

In addition to the CLI tool, Sslurp can be used as a library through the OOP
interface. The
[source](https://github.com/EvanDotPro/Sslurp/tree/master/src/Sslurp) _is_ the
API documentation.
interface. The [source](https://github.com/EvanDotPro/Sslurp/tree/master/src/Sslurp) _is_ the API documentation.

```php
<?php
require_once 'autoload_register.php';
require_once 'vendor/Sslurp/autoload_register.php';

$bundle = new \Sslurp\CaRootPemBundle(file_get_contents('ca-bundle.pem'));
$bundle = new \Sslurp\CaRootPemBundle('ca-bundle.pem');

if ($bundle->isLatest()) {
echo 'Your CA root bundle is up to date!' . PHP_EOL;
Expand All @@ -99,11 +59,55 @@ if ($bundle->isLatest()) {
. 'Latest version available from Mozilla is ' . $bundle->getMozillaCertData()->getVersion() . '.' . PHP_EOL;

echo 'Updating...';
file_put_contents('ca-bundle.pem', $bundle->getUpdatedCaRootBundle());
$bundle->update();
echo "\tDone!" . PHP_EOL;
}
```

## Installation

### Composer / Packagist

```
./composer.phar require evandotpro/sslurp
```

### Normal

The `./bin/update-ca-bundle` CLI tool will "just work" out of the box.

Sslurp can _easily_ be used in any existing project, framework, or library.

To use Sslurp as a library in your project, the easiest method is to simply
include the `autoload_register.php` file:

```php
require_once 'vendor/Sslurp/autoload_register.php';
```

Alternatively, if you project supports loading classmap arrays, you may fetch
the classmap without registering an additional SPL autoloader:

```php
$classmap = include 'vendor/Sslurp/autoload_classmap.php';
// Register $classmap with your project's existing classmap autoloader
```

If you have an existing SPL autoloader that allows adding a callable to a stack
instead of directly registering the classmap array, you have the option of
simply getting a closure which can autoload the Sslurp classes:

```php
$sslurpLoader = include 'vendor/Sslurp/autoload_function.php';
// $sslurpLoader is a closure that can be registered with an existing autoloader
```

## To-Do

* **Paranoia level 1000** - Test environment for the ability to call the OpenSSL executable, and if possible, make use of OCSP to _further_ verify the validity of the mxr.mozilla.org domain.

## License

Sslurp is released under the BSD license. See the included LICENSE file.

The generated root CA bundle file is simply a converted version of the original and as such, it is licensed under the same licenses as the Mozilla source: MPL v2.0, GPL v2.0 or LGPL 2.1. See [nss/COPYING](http:https://mxr.mozilla.org/mozilla/source/security/nss/COPYING?raw=1) for details.
10 changes: 6 additions & 4 deletions autoload_classmap.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'Sslurp\AbstractCaRootData' => __DIR__ . '/src/Sslurp/AbstractCaRootData.php',
'Sslurp\MozillaCertData' => __DIR__ . '/src/Sslurp/MozillaCertData.php',
'Sslurp\CaRootPemBundle' => __DIR__ . '/src/Sslurp/CaRootPemBundle.php',
'Sslurp\X509Certificate' => __DIR__ . '/src/Sslurp/X509Certificate.php',
'Sslurp\Module' => __DIR__ . '/Module.php',
'Sslurp\Sslurp' => __DIR__ . '/src/Sslurp/Sslurp.php',
'Sslurp\AbstractCaRootData' => __DIR__ . '/src/Sslurp/AbstractCaRootData.php',
'Sslurp\MozillaCertData' => __DIR__ . '/src/Sslurp/MozillaCertData.php',
'Sslurp\CaRootPemBundle' => __DIR__ . '/src/Sslurp/CaRootPemBundle.php',
'Sslurp\X509Certificate' => __DIR__ . '/src/Sslurp/X509Certificate.php',
);
24 changes: 13 additions & 11 deletions src/Sslurp/AbstractCaRootData.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,44 +20,46 @@ abstract class AbstractCaRootData
*
* @var string
*/
private $version = null;
protected $version = null;

/**
* The date/time of the version commit
* The date/time of the certdataversion
*
* @var DateTime
*/
private $dateTime = null;
protected $dateTime = null;

/**
* Get the version number
* Get the version number according to CVS.
*
* @return string
*/
public function getVersion()
{
if ($this->version === null) {
if (preg_match('/^#?\s?(CVS_ID\s+\".*\")/m', $this->getContent('CVS_ID'), $match)) {
$parts = explode(' ', $match[1]);
$this->version = $parts[6];
$this->dateTime = new DateTime($parts[9] . ' ' . $parts[10], new DateTimeZone('UTC'));
if (preg_match('/^.*\$Revision: ([\d\.]+)/m', $this->getContent('Revision:'), $match)) {
$this->version = $match[1];
} else {
throw new \RuntimeException('Unable to detect CVS version ID.');
throw new \RuntimeException('Unable to detect revesion ID.');
}
}

return $this->version;
}

/**
* Get the date/time of the last update
* Get the date/time the certdata was modified by Mozilla according to CVS.
*
* @return DateTime
*/
public function getDateTime()
{
if ($this->dateTime === null) {
$this->getVersion();
if (preg_match('/^.*\$Date: ([\d\/-]+\s+[\d:]+)/m', $this->getContent('Date:'), $match)) {
$this->dateTime = new DateTime($match[1], new DateTimeZone('UTC'));
} else {
throw new \RuntimeException('Unable to detect revision date.');
}
}

return $this->dateTime;
Expand Down
44 changes: 23 additions & 21 deletions src/Sslurp/CaRootPemBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,28 @@
*/
namespace Sslurp;

use SplFileObject;

class CaRootPemBundle extends AbstractCaRootData
{
/**
* The content of the PEM bundle
*
* @var string
* @var SplFileObject
*/
private $pemContent = null;
protected $fileObject = null;

/**
* @var MozillaCertData
* @var string
*/
private $mozCertData = null;
protected $pemContent = null;

/**
* Override for unit testing
*
* @var string
* @var MozillaCertData
*/
public static $overrideDateTime = null;
protected $mozCertData = null;

public function __construct($pemContent = null, MozillaCertData $mozCertData = null)
public function __construct($filename = null, MozillaCertData $mozCertData = null)
{
$this->pemContent = $pemContent;
$this->fileObject = new SplFileObject($filename, 'r+');
$this->mozCertData = $mozCertData ?: new MozillaCertData();
}

Expand All @@ -43,7 +41,9 @@ public function __construct($pemContent = null, MozillaCertData $mozCertData = n
public function getContent($until = false)
{
if ($this->pemContent === null) {
$this->pemContent = $this->getUpdatedCaRootBundle();
$this->pemContent = '';
while (!$this->fileObject->eof()) $this->pemContent .= $this->fileObject->fgets();
//$this->pemContent = $this->fileObject->getUpdatedCaRootBundle();
}

if ($until) {
Expand Down Expand Up @@ -71,20 +71,22 @@ public function getUpdatedCaRootBundle()
protected function buildBundle($rawCertData)
{
$rawCertData = explode("\n", $rawCertData);
$currentDate = static::$overrideDateTime ?: date(DATE_RFC822);
$currentDate = date(DATE_ISO8601);
$caBundle = <<<EOT
##
## Bundle of CA Root Certificates
##
## Generated $currentDate
## Generated with Sslurp (https://github.com/EvanDotPro/Sslurp)
##
## This is a bundle of X.509 certificates of public Certificate Authorities
## (CA). These were automatically extracted from Mozilla's root certificates
## file (certdata.txt). This file can be found in the mozilla source tree:
## '/mozilla/security/nss/lib/ckfw/builtins/certdata.txt'
## This is a bundle of X.509 certificates of public Certificate Authorities.
## These were automatically extracted from Mozilla's root certificates
## file (certdata.txt). This file can be found in the Mozilla source tree:
## /mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt
##
## http:https://www.mozilla.org/projects/security/certs/policy/
## http:https://www.mozilla.org/projects/security/pki/nss/
##
## It contains the certificates in PEM format and therefore
## This file contains the certificates in PEM format and therefore
## can be directly used with curl / libcurl / php_curl, or with
## an Apache+mod_ssl webserver for SSL client authentication.
## Just configure this file as the SSLCACertificateFile.
Expand All @@ -99,7 +101,7 @@ protected function buildBundle($rawCertData)

$line = rtrim($line);

if (preg_match('/^(CVS_ID\s+\".*\")/', $line, $match)) {
if (preg_match('/^CVS_ID\s+\"(.*)\"/', $line, $match)) {
$caBundle .= "# {$match[1]}\n";
}

Expand Down
Loading

0 comments on commit 497ea16

Please sign in to comment.