Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ingria committed Oct 6, 2017
0 parents commit 9261886
Show file tree
Hide file tree
Showing 5 changed files with 298 additions and 0 deletions.
58 changes: 58 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Created by https://www.gitignore.io

### Composer ###
composer.phar
vendor/

# Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file
# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file
# composer.lock


### PhpStorm ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm

*.iml

## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:

# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries

# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml

# Gradle:
# .idea/gradle.xml
# .idea/libraries

# Mongo Explorer plugin:
# .idea/mongoSettings.xml

## File-based project format:
*.ipr
*.iws

## Plugin-specific files:

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Codefuhrer

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.
94 changes: 94 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Client certificate authentication middleware for Laravel 5

Also known as X.509 client authentication.

### How does it work
1. You have a user in your app. For example, `Admin:[email protected]`
2. You generate a certificate for that user. Make sure you're using `[email protected]` for certificate's `emailAddress` field.
3. This package allows `Admin` to use your app without ever logging in.
4. All users including `Admin` can still use plain password auth.

## Prerequisites

Please don't blindly copy-paste the commands. It's important for you to know what you're doing.

### 1. Generate CA and Client certificate
Generating Certificate Authority:
```bash
openssl genrsa -out ca.key 2048
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt
```

Generating client certificate and signing it with your CA. When asked for the email, enter email of your app's user which will be autheticated with this certificate.
```bash
openssl req -new -utf8 -nameopt multiline,utf8 -newkey rsa:2048 -nodes -keyout client.key -out client.csr
openssl x509 -req -days 3650 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt
```

Optionally, generate a PKCS certificate to be installed into the browser, mobile or whatever:
```bash
openssl pkcs12 -export -clcerts -in client.crt -inkey client.key -out client.p12
```

### 2. Configure your web-server
This example is for NGINX with FastCGI.
```conf
server {
...
ssl_client_certificate /etc/nginx/certs/Your_CA_Public_Key.crt;
ssl_verify_client optional;
location ~ \.php$ {
...
fastcgi_param SSL_CLIENT_VERIFY $ssl_client_verify;
fastcgi_param SSL_CLIENT_S_DN $ssl_client_s_dn;
}
}
```

You can also add pass some other useful params, see resources below.

#### Resources
- [NGINX docs on ssl_verify_client](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_verify_client)
- [NGINX docs on SSL module variables](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#var_ssl_client_verify)


## Installation

### 1. Install the package
This assumes that you have composer installed globally:
```bash
composer require ingria/laravel-x509-auth
```

### 2. Register middleware
Add `\Ingria\LaravelX509Auth\Middleware\AuthenticateWithClientCertificate::class` to your `routeMiddleware` array in `app/Http/Kernel.php`.

For example, you can call it `auth.x509`, by analogy with Laravel's `auth.basic` name:
```php
// app/Http/Kernel.php

...
protected $routeMiddleware = [
// a whole bunch of middlewares...
'auth.x509' => \Ingria\LaravelX509Auth\Middleware\AuthenticateWithClientCertificate::class,
];
```
#### Resources
- [Laravel docs on registering a middleware](https://laravel.com/docs/5.5/middleware#registering-middleware)

## Usage
Just add the middleware's name to any route or controller instead of default `auth`. For example:

```php
// routes/web.php

Route::get('/', 'YourController@method')->middleware('auth.x509');
```

#### Resources
- [Laravel docs on assigning a middleware](https://laravel.com/docs/5.5/middleware#assigning-middleware-to-routes)
- [Laravel docs on protecting routes](https://laravel.com/docs/5.5/authentication#protecting-routes)

## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
18 changes: 18 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "ingria/laravel-x509-auth",
"description": "Laravel 5 Client Certificate auth middleware",
"keywords": ["laravel", "auth", "x509", "certificate"],
"license": "MIT",
"authors": [{
"name": "Codefuhrer",
"email": "[email protected]"
}],
"require": {
"php": ">=7.0.0"
},
"autoload": {
"psr-4": {
"Ingria\\LaravelX509Auth\\": "src/"
}
}
}
107 changes: 107 additions & 0 deletions src/Middleware/AuthenticateWithClientCertificate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

namespace Ingria\LaravelX509Auth\Middleware;

use function abort, redirect, preg_match, count;

use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use App\User;
use Closure;

class AuthenticateWithClientCertificate
{
/**
* The authentication factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;

/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param null|string $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->check()) {
return $next($request);
}

if (! $request->secure()) {
return abort(400, 'The Client Certificate auth requires a HTTPS connection.');
}

/** If the certificate is valid, log in and remember the user: */
if ($request->server('SSL_CLIENT_VERIFY') === 'SUCCESS') {
$this->auth->guard($guard)->login(self::getUserFromCert($request), true);

return $next($request);
}

throw new AuthenticationException('Unauthenticated.');
}

/**
* Gets the user from cert.
*
* @throws RuntimeException
* @param Request $request
* @return App\User
*/
private static function getUserFromCert(Request $request)
{
/**
* Probably misconfigured Nginx:
* @see https://nginx.org/en/docs/http/ngx_http_ssl_module.html#var_ssl_client_s_dn
*/
if (empty($subject = $request->server('SSL_CLIENT_S_DN'))) {
throw new \RuntimeException('Missing SSL_CLIENT_S_DN param');
}

$email = self::getEmailFromDn($subject);

if (empty($user = User::where('email', '=', $email)->first())) {
return abort(403, 'User not found');
}

return $user;
}

/**
* Parses the email address from client cert subject.
*
* @param string $subject
* @return string
*/
private static function getEmailFromDn(string $subject): string
{
preg_match('/emailAddress=([\w\+]+@[a-z\-\d]+\.[a-z\-\.\d]{2,})/i', $subject, $match);

/**
* emailAddress must be set.
* @see http://www.ietf.org/rfc/rfc2459.txt
*/
if (empty($match) || count($match) < 2) {
return abort(400, 'Missing or invalid emailAddress in subject certificate');
}

return $match[1];
}
}

0 comments on commit 9261886

Please sign in to comment.