From b40a2e8a9440787c9e377be71dae11eabd995e39 Mon Sep 17 00:00:00 2001 From: Ad Schellevis Date: Mon, 9 Nov 2015 22:23:55 +0100 Subject: [PATCH] (auth) add initial api authenticator --- .../mvc/app/library/OPNsense/Auth/API.php | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 src/opnsense/mvc/app/library/OPNsense/Auth/API.php diff --git a/src/opnsense/mvc/app/library/OPNsense/Auth/API.php b/src/opnsense/mvc/app/library/OPNsense/Auth/API.php new file mode 100644 index 000000000..f8855f62f --- /dev/null +++ b/src/opnsense/mvc/app/library/OPNsense/Auth/API.php @@ -0,0 +1,145 @@ +lastAuthProperties; + } + + + /** + * generate a new api key for an existing user + * @param $username username + * @return array|null apikey/secret pair + */ + public function createKey($username) + { + $configObj = Config::getInstance()->object(); + foreach ($configObj->system->children() as $key => $value) { + if ($key == 'user' && (string)$username == (string)$value->name) { + if (!isset($value->apikeys)) { + $apikeys = $value->addChild('apikeys'); + } else { + $apikeys = $value->apikeys; + } + $item = $apikeys->addChild('item'); + + $newKey = base64_encode(openssl_random_pseudo_bytes(60)); + $newSecret = base64_encode(openssl_random_pseudo_bytes(60)); + + $item->addChild('key', $newKey); + $item->addChild('secret', crypt($newSecret, '$6$')); + Config::getInstance()->save(); + $response = array('key' => $newKey, 'secret' => $newSecret); + return $response; + } + } + return null; + } + + /** + * authenticate user against local database (in config.xml) + * @param string $username username to authenticate + * @param string $password user password + * @return bool authentication status + */ + public function authenticate($username, $password) + { + // reset auth properties + $this->lastAuthProperties = array(); + + // search local user in database + $configObj = Config::getInstance()->object(); + $userObject = null; + $apiKey = null; + $apiSecret = null; + foreach ($configObj->system->children() as $key => $value) { + if ($key == 'user') { + if (!empty($value->apikeys)) { + foreach ($value->apikeys->children() as $apikey) { + if (!empty($apikey->key) && (string)$apikey->key == $username) { + // api key found, stop search + $userObject = $value; + $apiSecret = (string)$apikey->secret; + break; + } + } + } + } + } + + if ($userObject != null) { + if (isset($userObject->disabled)) { + // disabled user + return false; + } + if (!empty($userObject->expires) + && strtotime("-1 day") > strtotime(date("m/d/Y", strtotime((string)$userObject->expires)))) { + // expired user + return false; + } + $passwd = crypt($password, $apiSecret); + if ($passwd == $apiSecret) { + // password ok, return successfully authentication + $this->lastAuthProperties['username'] = (string)$userObject->name; + return true; + } + } + + return false; + } +}