Commit 2a0b7a7a authored by Franco Fichtner's avatar Franco Fichtner

mvc: merge pluggable authentication remains et al

parent c91450bb
......@@ -371,6 +371,7 @@
/usr/local/opnsense/mvc/app/library/OPNsense/Auth/Local.php
/usr/local/opnsense/mvc/app/library/OPNsense/Auth/LocalTOTP.php
/usr/local/opnsense/mvc/app/library/OPNsense/Auth/Radius.php
/usr/local/opnsense/mvc/app/library/OPNsense/Auth/TOTP.php
/usr/local/opnsense/mvc/app/library/OPNsense/Auth/Voucher.php
/usr/local/opnsense/mvc/app/library/OPNsense/Base/Filters/QueryFilter.php
/usr/local/opnsense/mvc/app/library/OPNsense/Base/UIModelGrid.php
......
......@@ -42,6 +42,15 @@ class API implements IAuthConnector
*/
private $lastAuthProperties = array();
/**
* type name in configuration
* @return string
*/
public static function getType()
{
return 'api';
}
/**
* set connector properties
* @param array $config connection properties
......
......@@ -57,6 +57,33 @@ class AuthenticationFactory
return $result;
}
/**
* list installed auth connectors
* @return array
*/
private function listConnectors()
{
$connectors = array();
foreach (glob(__DIR__."/*.php") as $filename) {
$pathParts = explode('/', $filename);
$vendor = $pathParts[count($pathParts)-3];
$module = $pathParts[count($pathParts)-2];
$classname = explode('.php', $pathParts[count($pathParts)-1])[0];
$reflClass = new \ReflectionClass("{$vendor}\\{$module}\\{$classname}");
if ($reflClass->implementsInterface('OPNsense\\Auth\\IAuthConnector')) {
if ($reflClass->hasMethod('getType')) {
$connectorType = $reflClass->getMethod('getType')->invoke(null);
$connector = array();
$connector['class'] = "{$vendor}\\{$module}\\{$classname}";
$connector['classHandle'] = $reflClass;
$connector['type'] = $connectorType;
$connectors[$connectorType] = $connector;
}
}
}
return $connectors;
}
/**
* request list of configured servers, the factory needs to be aware of it's options and settings to
* be able to instantiate useful connectors.
......@@ -90,32 +117,16 @@ class AuthenticationFactory
$localUserMap = array();
$servers = $this->listServers();
$servers['Local API'] = array("name" => "Local API Database", "type" => "api");
// create a new auth connector
if (isset($servers[$authserver]['type'])) {
switch ($servers[$authserver]['type']) {
case 'local':
$authObject = new Local();
break;
case 'ldap':
$authObject = new LDAP();
$connectors = $this->listConnectors();
if (!empty($connectors[$servers[$authserver]['type']])) {
$authObject = $connectors[$servers[$authserver]['type']]['classHandle']->newInstance();
}
if ($servers[$authserver]['type'] == 'ldap') {
$localUserMap = $this->fetchUserDNs();
break;
case 'radius':
$authObject = new Radius();
break;
case 'voucher':
$authObject = new Voucher();
break;
case 'api':
$authObject = new API();
break;
case 'totp':
$authObject = new LocalTOTP();
break;
default:
$authObject = null;
}
if ($authObject != null) {
$props = $servers[$authserver];
// when a local user exist and has a different (distinguished) name on the authenticator we already
......@@ -128,4 +139,27 @@ class AuthenticationFactory
return null;
}
/**
* list configuration options for pluggable auth modules
* @return array
*/
public function listConfigOptions()
{
$result = array();
foreach ($this->listConnectors() as $connector) {
if ($connector['classHandle']->hasMethod('getDescription')) {
$obj = $connector['classHandle']->newInstance();
$authItem = $connector;
$authItem['description'] = $obj->getDescription();
if ($connector['classHandle']->hasMethod('getConfigurationOptions')) {
$authItem['additionalFields'] = $obj->getConfigurationOptions();
} else {
$authItem['additionalFields'] = array();
}
$result[$obj->getType()] = $authItem;
}
}
return $result;
}
}
......@@ -141,6 +141,24 @@ class LDAP implements IAuthConnector
return $result;
}
/**
* type name in configuration
* @return string
*/
public static function getType()
{
return 'ldap';
}
/**
* user friendly description of this authenticator
* @return string
*/
public function getDescription()
{
return gettext("LDAP");
}
/**
* construct a new LDAP connector
* @param null|string $baseSearchDN setup base searchDN or list of DN's separated by ;
......
......@@ -37,6 +37,15 @@ use OPNsense\Core\Config;
*/
class Local implements IAuthConnector
{
/**
* type name in configuration
* @return string
*/
public static function getType()
{
return 'local';
}
/**
* set connector properties
* @param array $config connection properties
......
......@@ -30,146 +30,48 @@
namespace OPNsense\Auth;
require_once 'base32/Base32.php';
/**
* RFC 6238 TOTP: Time-Based One-Time Password Authenticator
* @package OPNsense\Auth
*/
class LocalTOTP extends Local
{
/**
* @var int time window in seconds (google auth uses 30, some hardware tokens use 60)
*/
private $timeWindow = 30;
/**
* @var int key length (6,8)
*/
private $otpLength = 6;
use TOTP;
/**
* @var int number of seconds the clocks (local, remote) may differ
*/
private $graceperiod = 10;
/**
* set connector properties
* @param array $config connection properties
* type name in configuration
* @return string
*/
public function setProperties($config)
public static function getType()
{
parent::setProperties($config);
if (!empty($config['timeWindow'])) {
$this->timeWindow = $config['timeWindow'];
}
if (!empty($config['otpLength'])) {
$this->otpLength = $config['otpLength'];
}
if (!empty($config['graceperiod'])) {
$this->graceperiod = $config['graceperiod'];
}
return 'totp';
}
/**
* use graceperiod and timeWindow to calculate which moments in time we should check
* @return array timestamps
* user friendly description of this authenticator
* @return string
*/
private function timesToCheck()
public function getDescription()
{
$result = array();
if ($this->graceperiod > $this->timeWindow) {
$step = $this->timeWindow;
$start = -1 * floor($this->graceperiod / $this->timeWindow) * $this->timeWindow;
} else {
$step = $this->graceperiod;
$start = -1 * $this->graceperiod;
}
$now = time();
for ($count = $start; $count <= $this->graceperiod; $count += $step) {
$result[] = $now + $count;
if ($this->graceperiod == 0) {
// special case, we expect the clocks to match 100%, so step and target are both 0
break;
}
}
return $result;
return gettext("Local + Timebased One Time Password");
}
/**
* @param int $moment timestemp
* @param string $secret secret to use
* @return calculated token code
*/
private function calculateToken($moment, $secret)
{
// calculate binary 8 character time for provided window
$binary_time = pack("N", (int)($moment/$this->timeWindow));
$binary_time = str_pad($binary_time, 8, chr(0), STR_PAD_LEFT);
// Generate the hash using the SHA1 algorithm
$hash = hash_hmac('sha1', $binary_time, $secret, true);
$offset = ord($hash[19]) & 0xf;
$otp = (
((ord($hash[$offset+0]) & 0x7f) << 24 ) |
((ord($hash[$offset+1]) & 0xff) << 16 ) |
((ord($hash[$offset+2]) & 0xff) << 8 ) |
(ord($hash[$offset+3]) & 0xff)
) % pow(10, $this->otpLength);
$otp = str_pad($otp, $this->otpLength, "0", STR_PAD_LEFT);
return $otp;
}
/**
* return current token code
* @param $base32seed secret to use
* @return string token code
*/
public function testToken($base32seed)
{
$otp_seed = \Base32\Base32::decode($base32seed);
return $this->calculateToken(time(), $otp_seed);
}
/**
* authenticate TOTP RFC 6238
* @param string $secret secret seed to use
* @param string $code provided code
* @return bool is valid
* set connector properties
* @param array $config connection properties
*/
private function authTOTP($secret, $code)
public function setProperties($config)
{
foreach ($this->timesToCheck() as $moment) {
if ($code == $this->calculateToken($moment, $secret)) {
return true;
}
}
return false;
parent::setProperties($config);
$this->setTOTPProperties($config);
}
/**
* authenticate user against otp key stored in local database
* @param string $username username to authenticate
* @param string $password user password
* @return bool authentication status
* retrieve configuration options
* @return array
*/
public function authenticate($username, $password)
public function getConfigurationOptions()
{
$userObject = $this->getUser($username);
if ($userObject != null && !empty($userObject->otp_seed)) {
if (strlen($password) > $this->otpLength) {
// split otp token code and userpassword
$code = substr($password, 0, $this->otpLength);
$userPassword = substr($password, $this->otpLength);
$otp_seed = \Base32\Base32::decode($userObject->otp_seed);
if ($this->authTOTP($otp_seed, $code)) {
// token valid, do local auth
return parent::authenticate($userObject, $userPassword);
}
}
}
return false;
return $this->getTOTPConfigurationOptions();
}
}
......@@ -81,6 +81,24 @@ class Radius implements IAuthConnector
*/
private $lastAuthProperties = array();
/**
* type name in configuration
* @return string
*/
public static function getType()
{
return 'radius';
}
/**
* user friendly description of this authenticator
* @return string
*/
public function getDescription()
{
return gettext("Radius");
}
/**
* set connector properties
* @param array $config connection properties
......
<?php
/**
* Copyright (C) 2016 Deciso B.V.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace OPNsense\Auth;
require_once 'base32/Base32.php';
/**
* RFC 6238 TOTP: Time-Based One-Time Password Authenticator
* @package OPNsense\Auth
*/
trait TOTP
{
/**
* @var int time window in seconds (google auth uses 30, some hardware tokens use 60)
*/
private $timeWindow = 30;
/**
* @var int key length (6,8)
*/
private $otpLength = 6;
/**
* @var int number of seconds the clocks (local, remote) may differ
*/
private $graceperiod = 10;
/**
* @var string method accepting username and returning a simplexml user object
*/
private $getUserMethod = 'getUser';
/**
* use graceperiod and timeWindow to calculate which moments in time we should check
* @return array timestamps
*/
private function timesToCheck()
{
$result = array();
if ($this->graceperiod > $this->timeWindow) {
$step = $this->timeWindow;
$start = -1 * floor($this->graceperiod / $this->timeWindow) * $this->timeWindow;
} else {
$step = $this->graceperiod;
$start = -1 * $this->graceperiod;
}
$now = time();
for ($count = $start; $count <= $this->graceperiod; $count += $step) {
$result[] = $now + $count;
if ($this->graceperiod == 0) {
// special case, we expect the clocks to match 100%, so step and target are both 0
break;
}
}
return $result;
}
/**
* @param int $moment timestemp
* @param string $secret secret to use
* @return calculated token code
*/
private function calculateToken($moment, $secret)
{
// calculate binary 8 character time for provided window
$binary_time = pack("N", (int)($moment/$this->timeWindow));
$binary_time = str_pad($binary_time, 8, chr(0), STR_PAD_LEFT);
// Generate the hash using the SHA1 algorithm
$hash = hash_hmac('sha1', $binary_time, $secret, true);
$offset = ord($hash[19]) & 0xf;
$otp = (
((ord($hash[$offset+0]) & 0x7f) << 24 ) |
((ord($hash[$offset+1]) & 0xff) << 16 ) |
((ord($hash[$offset+2]) & 0xff) << 8 ) |
(ord($hash[$offset+3]) & 0xff)
) % pow(10, $this->otpLength);
$otp = str_pad($otp, $this->otpLength, "0", STR_PAD_LEFT);
return $otp;
}
/**
* return current token code
* @param $base32seed secret to use
* @return string token code
*/
public function testToken($base32seed)
{
$otp_seed = \Base32\Base32::decode($base32seed);
return $this->calculateToken(time(), $otp_seed);
}
/**
* authenticate TOTP RFC 6238
* @param string $secret secret seed to use
* @param string $code provided code
* @return bool is valid
*/
private function authTOTP($secret, $code)
{
foreach ($this->timesToCheck() as $moment) {
if ($code == $this->calculateToken($moment, $secret)) {
return true;
}
}
return false;
}
/**
* authenticate user against otp key stored in local database
* @param string $username username to authenticate
* @param string $password user password
* @return bool authentication status
*/
public function authenticate($username, $password)
{
$getUserMethod = $this->getUserMethod;
$userObject = $this->$getUserMethod($username);
if ($userObject != null && !empty($userObject->otp_seed)) {
if (strlen($password) > $this->otpLength) {
// split otp token code and userpassword
$code = substr($password, 0, $this->otpLength);
$userPassword = substr($password, $this->otpLength);
$otp_seed = \Base32\Base32::decode($userObject->otp_seed);
if ($this->authTOTP($otp_seed, $code)) {
// token valid, do parents auth
return parent::authenticate($userObject, $userPassword);
}
}
}
return false;
}
/**
* set TOTP specific connector properties
* @param array $config connection properties
*/
public function setTOTPProperties($config)
{
if (!empty($config['timeWindow'])) {
$this->timeWindow = $config['timeWindow'];
}
if (!empty($config['otpLength'])) {
$this->otpLength = $config['otpLength'];
}
if (!empty($config['graceperiod'])) {
$this->graceperiod = $config['graceperiod'];
}
}
/**
* retrieve TOTP specific configuration options
* @return array
*/
private function getTOTPConfigurationOptions()
{
$fields = array();
$fields["otpLength"] = array();
$fields["otpLength"]["name"] = gettext("Token length");
$fields["otpLength"]["type"] = "dropdown";
$fields["otpLength"]["default"] = 6;
$fields["otpLength"]["options"] = array();
$fields["otpLength"]["options"]["6"] = "6";
$fields["otpLength"]["options"]["8"] = "8";
$fields["otpLength"]["help"] = gettext("Token length to use");
$fields["otpLength"]["validate"] = function ($value) {
if (!in_array($value, array(6,8))) {
return array(gettext("Only token lengths of 6 or 8 characters are supported"));
} else {
return array();
}
};
$fields["timeWindow"] = array();
$fields["timeWindow"]["name"] = gettext("Time window");
$fields["timeWindow"]["type"] = "text";
$fields["timeWindow"]["default"] = null;
$fields["timeWindow"]["help"] = gettext("The time period in which the token will be valid,".
" default is 30 seconds (google authenticator)");
$fields["timeWindow"]["validate"] = function ($value) {
if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) {
return array(gettext("Please enter a valid time window in seconds"));
} else {
return array();
}
};
$fields["graceperiod"] = array();
$fields["graceperiod"]["name"] = gettext("Grace period");
$fields["graceperiod"]["type"] = "text";
$fields["graceperiod"]["default"] = null;
$fields["graceperiod"]["help"] = gettext("Time in seconds in which this server and the token may differ,".
" default is 10 seconds. Set higher for a less secure easier match.");
$fields["graceperiod"]["validate"] = function ($value) {
if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) {
return array(gettext("Please enter a valid grace period in seconds"));
} else {
return array();
}
};
return $fields;
}
}
......@@ -68,6 +68,24 @@ class Voucher implements IAuthConnector
*/
private $lastAuthProperties = array();
/**
* type name in configuration
* @return string
*/
public static function getType()
{
return 'voucher';
}
/**
* user friendly description of this authenticator
* @return string
*/
public function getDescription()
{
return gettext("Voucher");
}
/**
* open database
*/
......@@ -391,4 +409,46 @@ class Voucher implements IAuthConnector
}
return false;
}
/**
* retrieve configuration options
* @return array
*/
public function getConfigurationOptions()
{
$fields = array();
$fields["simplePasswords"] = array();
$fields["simplePasswords"]["name"] = gettext("Use simple passwords (less secure)");
$fields["simplePasswords"]["type"] = "checkbox";
$fields["simplePasswords"]["help"] = gettext("Use simple (less secure) passwords, which are easier to read");
$fields["simplePasswords"]["validate"] = function ($value) {
return array();
};
$fields["usernameLength"] = array();
$fields["usernameLength"]["name"] = gettext("Username length");
$fields["usernameLength"]["type"] = "text";
$fields["usernameLength"]["default"] = null;
$fields["usernameLength"]["help"] = gettext("Specify alternative username length for generating vouchers");
$fields["usernameLength"]["validate"] = function ($value) {
if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) {
return array(gettext("Username length must be a number or empty for default."));
} else {
return array();
}
};
$fields["passwordLength"] = array();
$fields["passwordLength"]["name"] = gettext("Password length");
$fields["passwordLength"]["type"] = "text";
$fields["passwordLength"]["default"] = null;
$fields["passwordLength"]["help"] = gettext("Specify alternative password length for generating vouchers");
$fields["passwordLength"]["validate"] = function ($value) {
if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) {
return array(gettext("Password length must be a number or empty for default."));
} else {
return array();
}
};
return $fields;
}
}
......@@ -27,7 +27,8 @@ try {
} catch (\Exception $e) {
$response = array();
$response['errorMessage'] = $e->getMessage();
header('HTTP', true, 500);
header("Content-Type: application/json;charset=utf-8");
echo htmlspecialchars(json_encode($response), ENT_NOQUOTES);
echo json_encode($response, JSON_UNESCAPED_SLASHES);
error_log($e);
}
......@@ -81,18 +81,7 @@ function saveFormToEndpoint(url,formid,callback_ok, disable_dialog) {
// execute callback function
callback_ok();
}
} else {
// error handling, show internal errors
// Normally the form should only return validation issues, if other things go wrong throw an error.
BootstrapDialog.show({
type: BootstrapDialog.TYPE_ERROR,
title: 'save',
message: 'Unable to save data, an internal error occurred.<br> ' +
'Response from server was: <br> <small>'+JSON.stringify(data)+'</small>'
});
}
});
}
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment