Skip to content
This repository was archived by the owner on Nov 11, 2024. It is now read-only.

Commit

Permalink
WE2-711 Implemented OCSP request and response. Added unit tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Guido Gröön authored and mrts committed Dec 5, 2022
1 parent 5b24f49 commit 636feda
Show file tree
Hide file tree
Showing 29 changed files with 1,973 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Ignore all test and documentation with "export-ignore".
/.gitattributes export-ignore
/.gitignore export-ignore
/phpunit.xml.dist export-ignore
/tests export-ignore
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
composer.lock
.phpunit.result.cache
vendor
build
.DS_Store
phpunit.xml
155 changes: 154 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,155 @@
# ocsp-php
OCSP library for PHP

ocsp-php is a library for PHP for checking if certificates are revoked, by using Online Certificate Status Protocol (OCSP).

This library does not include any HTTP client, you can use cURL for example.

# Quickstart

Complete the steps below to include the library in your project.

A PHP web application that uses Composer to manage packages is needed for running this quickstart.

## Add the library to your project

Add the following lines to composer.json to include the ocsp-php library in your project:

```json
"repositories": [
{
"type": "vcs",
"url": "https://github.com/web-eid/ocsp-php"
}
],
"require": {
"web_eid/ocsp_php": "dev-main"
},
```

## Loading the certificates

By using **CertificateLoader**, you can load certificates from file or string.

```php
// Loading certificate from file
$certificate = (new CertificateLoader)->fromFile('/path/to/cert.crt')->getCert();

// Loading certificate from string
$certificate = (new CertificateLoader)->fromString('-----BEGIN CERTIFICATE-----MIIEAzCCA...-----END CERTIFICATE-----')->getCert();
```

## Getting the issuer certificate from certificate

The certificate usually contains a URL where you can find certificate of the certificate issuer.

You can use this code to extract this URL from the certificate.

```php
$certLoader = (new CertificateLoader)->fromFile('/path/to/cert.crt');
$issuerCertificateUrl = $certLoader->getIssuerCertificateUrl();
```

`$issuerCertificateUrl` will contain the URL where the issuer certificate can be downloaded. When it is an empty string, that means the issuer certificate URL is not included in the SSL certificate.

## Getting the OCSP responder URL

To check if a SSL Certificate is valid, you need to know the OCSP URL, that is provided by the authority that issued the certificate. This URL can be called to check if the certificate has been revoked.

This URL may be included in the SSL Certificate itself.

You can use this code to extract the OCSP responder URL from the SSL Certificate.

```php
$certLoader = (new CertificateLoader)->fromFile('/path/to/cert.crt');
$ocspResponderUrl = $certLoader->getOcspResponderUrl();
```
When it is an empty string, that means the OCSP responder URL is not included in the SSL Certificate.

## Checking the revocation status of an SSL Certificate

Once you have the SSL Certificate, the issuer certificate, and the OCSP responder URL, you can check whether the SSL certificate has been revoked or is still valid.

```php
$subjectCert = (new CertificateLoader)->fromFile('/path/to/subject.crt')->getCert();
$issuerCert = (new CertificateLoader)->fromFile('/path/to/issuer.crt')->getCert();

// Create the certificateId
$certificateId = (new Ocsp)->generateCertificateId($subjectCert, $issuerCert);

// Build request body
$requestBody = new OcspRequest();
$requestBody->addCertificateId($certificateId);

// Add nonce extension when the nonce feature is enabled,
// otherwise skip this line
$requestBody->addNonceExtension(random_bytes(32));

// Send request to OCSP responder URL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $ocspResponderUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: ' .Ocsp::OCSP_REQUEST_MEDIATYPE]);
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody->getEncodeDer());
$result = curl_exec($curl);
$info = curl_getinfo($curl);
if ($info["http_code"] !== 200) {
throw new RuntimeException("HTTP status is not 200");
}

// Check the response content type
if ($info["content_type"] != Ocsp::OCSP_RESPONSE_MEDIATYPE) {
throw new RuntimeException("Content-Type header of the response is wrong");
}

// Decode the raw response from the OCSP Responder
$response = new OcspResponse($result);

// Verify response
// It will verify that OCSP response contains only one response,
// validates certificateId and signature
$response->verify($certificateId);

// Validate nonce when the nonce feature is enabled,
$basicResponse = $response->getBasicResponse();
if ($requestBody->getNonceExtension() != $basicResponse->getNonceExtension()) {
throw new RuntimeException("OCSP request nonce and response nonce do not match");
}

```
`$response` contains instance of the `web_eid\ocsp_php\OcspResponse` class:

* `$response->isRevoked() === false` when the certificate is not revoked
* `$response->isRevoked() === true` when the certificate is revoked (to get revoke reason, call `$response->getRevokeReason()`)
* when `$response->isRevoked()` returns null, then the certificate revoke status is unknown

To get more detailed information from response, you can use:

```php
// Read response status
$response->getStatus();
$basicResponse = $response->getBasicResponse();
```

Following methods can be called with `$basicResponse`:

* `$basicResponse->getResponses()` - returns array of the responses
* `$basicResponse->getCertificates()` - returns array of X.509 certificates (phpseclib3\File\X509)
* `$basicResponse->getSignature()` - returns signature
* `$basicResponse->getProducedAt()` - returns DateTime object
* `$basicResponse->getThisUpdate()` - returns DateTime object
* `$basicResponse->getNextUpdate()` - returns DateTime object (is `null` when `nextUpdate` field does not exist)
* `$basicResponse->getSignatureAlgorithm()` - returns signature algorithm as string (throws exception, when signature algorithm is not implemented)
* `$basicResponse->getNonceExtension()` - returns nonce (when value is `null` then nonce extension does not exist in response)

# Exceptions

All exceptions are handled by the `web_eid\ocsp_php\exceptions\OcspException` class. To catch these errors, you can enclose your code within try/catch statements:

```php
try {
// code
} catch (OcspException $e) {
// exception handler
}
```
28 changes: 28 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "web_eid/ocsp_php",
"description": "OCSP library for PHP",
"license": "MIT",
"type": "library",
"authors": [
{
"name": "Guido Gröön",
"role" : "developer"
}
],
"require-dev": {
"phpunit/phpunit": "^9.5"
},
"autoload": {
"psr-4": {
"web_eid\\ocsp_php\\": ["src"]
}
},
"autoload-dev": {
"psr-4": {
"web_eid\\ocsp_php\\": ["tests"]
}
},
"require": {
"phpseclib/phpseclib": "3.0.14"
}
}
18 changes: 18 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="vendor/autoload.php" backupGlobals="false" backupStaticAttributes="false" colors="true" verbose="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">src/</directory>
</include>
<report>
<clover outputFile="build/logs/clover.xml" />
<html outputDirectory="build/coverage" />
<text outputFile="build/coverage.txt" />
</report>
</coverage>
<testsuites>
<testsuite name="OCSP PHP Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
109 changes: 109 additions & 0 deletions src/Ocsp.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php

/*
* Copyright (c) 2020-2021 Estonian Information System Authority
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

declare(strict_types=1);

namespace web_eid\ocsp_php;

use phpseclib3\File\ASN1;
use phpseclib3\File\ASN1\Maps\Name;
use phpseclib3\File\X509;
use web_eid\ocsp_php\exceptions\OcspCertificateException;
use web_eid\ocsp_php\util\AsnUtil;

class Ocsp {

/**
* The media type (Content-Type header) to be used when sending the request to the OCSP Responder URL.
*
* @var string
*/
const OCSP_REQUEST_MEDIATYPE = 'application/ocsp-request';

/**
* The media type (Content-Type header) that should be included in responses from the OCSP Responder URL.
*
* @var string
*/
const OCSP_RESPONSE_MEDIATYPE = 'application/ocsp-response';

/**
* Response type for a basic OCSP responder
*
* @var string
*/
public const ID_PKIX_OCSP_BASIC_STRING = 'id-pkix-ocsp-basic';

/**
* Generates certificate ID with subject and issuer certificates
*
* @param X509 certificate - subject certificate
* @param X509 issuerCertificate - issuer certificate
* @return array
* @throws OcspCertificateException when the subject or issuer certificates don't have required data
*/
public function generateCertificateId(X509 $certificate, X509 $issuerCertificate): array
{
AsnUtil::loadOIDs();

$certificateId = [
"hashAlgorithm" => [],
"issuerNameHash" => "",
"issuerKeyHash" => "",
"serialNumber" => [],
];

if (!isset($certificate->getCurrentCert()['tbsCertificate']['serialNumber'])) {
// Serial number of subject certificate does not exist
throw new OcspCertificateException("Serial number of subject certificate does not exist");
}

$certificateId["serialNumber"] = clone $certificate->getCurrentCert()['tbsCertificate']['serialNumber'];

// issuer name
if (!isset($issuerCertificate->getCurrentCert()['tbsCertificate']['subject'])) {
// Serial number of issuer certificate does not exist
throw new OcspCertificateException("Serial number of issuer certificate does not exist");
}

$issuer = $issuerCertificate->getCurrentCert()['tbsCertificate']['subject'];
$issuerEncoded = ASN1::encodeDER($issuer, Name::MAP);
$certificateId["issuerNameHash"] = hash("sha1", $issuerEncoded, true);

// issuer public key
if (!isset($issuerCertificate->getCurrentCert()['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'])) {
// SubjectPublicKey of issuer certificate does not exist
throw new OcspCertificateException("SubjectPublicKey of issuer certificate does not exist");
}

$publicKey = $issuerCertificate->getCurrentCert()['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'];
$certificateId['issuerKeyHash'] = hash("sha1", AsnUtil::extractKeyData($publicKey), true);

$certificateId['hashAlgorithm']['algorithm'] = Asn1::getOID('id-sha1');

return $certificateId;
}


}
Loading

0 comments on commit 636feda

Please sign in to comment.