Voucher.php 16.7 KB
Newer Older
1
<?php
2

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/**
 *    Copyright (C) 2015 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;

use OPNsense\Core\Config;

/**
 * Class Voucher user database connector
 * @package OPNsense\Auth
 */
39
class Voucher extends Base implements IAuthConnector
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
{
    /**
     * @var null reference id
     */
    private $refid = null;

    /**
     * @var null database handle
     */
    private $dbHandle = null;

    /**
     * @var int password length to use
     */
    private $passwordLength = 10;

    /**
     * @var int username length
     */
    private $usernameLength = 8;

61 62 63 64 65
    /**
     * @var bool use simple passwords (less secure)
     */
    private $simplePasswords = false;

66 67 68 69 70
    /**
     * @var array internal list of authentication properties (returned by radius auth)
     */
    private $lastAuthProperties = array();

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    /**
     * 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");
    }

89 90 91 92 93
    /**
     * open database
     */
    private function openDatabase()
    {
94
        $db_path = '/conf/vouchers_' . $this->refid . '.db';
95
        $this->dbHandle = new \SQLite3($db_path);
96
        $this->dbHandle->busyTimeout(30000);
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        $results = $this->dbHandle->query('select count(*) cnt from sqlite_master');
        $row = $results->fetchArray();
        if ($row['cnt'] == 0) {
            // new database, setup
            $sql_create = "
                create table vouchers (
                      username      varchar2  -- username
                    , password      varchar2  -- user password (crypted)
                    , vouchergroup  varchar2  -- group of vouchers
                    , validity      integer   -- voucher credits
                    , starttime     integer   -- voucher start at
                    , vouchertype   varchar2  -- (not implemented) voucher type
                    , primary key (username)
                );
                create index idx_voucher_group on vouchers(vouchergroup);
            ";
            $this->dbHandle->exec($sql_create);
        }
    }

    /**
     * check if username does already exist
     * @param string $username username
     * @return bool
     */
    private function userNameExists($username)
    {
        $stmt = $this->dbHandle->prepare('select count(*) cnt from vouchers where username = :username');
        $stmt->bindParam(':username', $username);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        if ($row['cnt'] == 0) {
            return false;
        } else {
            return true;
        }
    }

    private function setStartTime($username, $starttime)
    {
        $stmt = $this->dbHandle->prepare('
                                update vouchers
                                set    starttime = :starttime
                                where username = :username
                                ');
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':starttime', $starttime);
        $stmt->execute();
    }

    /**
     * set connector properties
     * @param array $config connection properties
     */
    public function setProperties($config)
    {
        // fetch unique id for this authenticator
        if (array_key_exists('refid', $config)) {
            $this->refid = $config['refid'];
        } else {
            $this->refid = 'default';
        }
159 160 161 162 163 164 165 166 167 168 169 170
        // use simple passwords
        if (array_key_exists('simplePasswords', $config) && !empty($config['simplePasswords'])) {
            $this->simplePasswords = true;
        }
        // use predefined username and password length
        if (array_key_exists('usernameLength', $config) && is_numeric($config['usernameLength'])) {
            $this->usernameLength = (int)$config['usernameLength'];
        }
        if (array_key_exists('passwordLength', $config) && is_numeric($config['passwordLength'])) {
            $this->passwordLength = (int)$config['passwordLength'];
        }

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        $this->openDatabase();
    }

    /**
     * generate new vouchers and store in voucher database
     * @param string $vouchergroup voucher groupname
     * @param int $count number of vouchers to generate
     * @param int $validity time (in seconds)
     * @param int $starttime valid from
     * @return array list of generated vouchers
     */
    public function generateVouchers($vouchergroup, $count, $validity, $starttime = null)
    {
        $response = array();
        if ($this->dbHandle != null) {
186 187 188 189 190 191 192 193 194 195 196 197 198 199
            if ($this->simplePasswords) {
                // create a map of easy to read characters
                $characterMap = '';
                while (strlen($characterMap) < 256) {
                    $random_bytes = openssl_random_pseudo_bytes(10000);
                    for ($i = 0; $i < strlen($random_bytes); $i++) {
                        $chr_ord = ord($random_bytes[$i]);
                        if (($chr_ord >= 50 && $chr_ord <= 57) || // 2..9
                            ($chr_ord >= 65 && $chr_ord <= 78) || // A..N
                            ($chr_ord >= 80 && $chr_ord <= 90) || // P..Z
                            ($chr_ord >= 97 && $chr_ord <= 107) || // a..k
                            ($chr_ord >= 109 && $chr_ord <= 110) || // m..n
                            ($chr_ord >= 112 && $chr_ord <= 122)  // p..z
                        ) {
200
                            $characterMap .= $random_bytes[$i];
201 202 203 204 205 206 207 208 209 210 211 212 213 214
                        }
                    }
                }
            } else {
                // list of characters to skip for random generator
                $doNotUseChr = array('<', '>', '{', '}', '&', 'l' , 'O' ,'`', '\'', '|' ,'^', '"');

                // create map of random readable characters
                $characterMap = '';
                while (strlen($characterMap) < 256) {
                    $random_bytes = openssl_random_pseudo_bytes(10000);
                    for ($i = 0; $i < strlen($random_bytes); $i++) {
                        $chr_ord = ord($random_bytes[$i]);
                        if ($chr_ord >= 33 && $chr_ord <= 125 && !in_array($random_bytes[$i], $doNotUseChr)) {
215
                            $characterMap .= $random_bytes[$i];
216
                        }
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                    }
                }
            }

            // generate new vouchers
            $vouchersGenerated = 0;
            while ($vouchersGenerated < $count) {
                $generatedUsername = '';
                $random_bytes = openssl_random_pseudo_bytes($this->usernameLength);
                for ($j=0; $j < strlen($random_bytes); $j++) {
                    $generatedUsername .= $characterMap[ord($random_bytes[$j])];
                }
                $generatedPassword = '';
                $random_bytes = openssl_random_pseudo_bytes($this->passwordLength);
                for ($j=0; $j < strlen($random_bytes); $j++) {
                    $generatedPassword .= $characterMap[ord($random_bytes[$j])];
                }

                if (!$this->userNameExists($generatedUsername)) {
                    $vouchersGenerated++;
                    // save user, hash password first
                    $generatedPasswordHash = crypt($generatedPassword, '$6$');
                    $stmt = $this->dbHandle->prepare('
                                insert into vouchers(username, password, vouchergroup, validity, starttime)
                                values (:username, :password, :vouchergroup, :validity, :starttime)
                                ');
                    $stmt->bindParam(':username', $generatedUsername);
                    $stmt->bindParam(':password', $generatedPasswordHash);
                    $stmt->bindParam(':vouchergroup', $vouchergroup);
                    $stmt->bindParam(':validity', $validity);
                    $stmt->bindParam(':starttime', $starttime);
                    $stmt->execute();

                    $row = array('username' => $generatedUsername,
                        'password' => $generatedPassword,
                        'vouchergroup' => $vouchergroup,
                        'validity' => $validity,
                        'starttime' => $starttime
                    );
                    $response[] = $row;
                }
            }
        }
        return $response;
    }

    /**
     * drop all vouchers from voucher a voucher group
     * @param string $vouchergroup group name
     */
    public function dropVoucherGroup($vouchergroup)
    {
        $stmt = $this->dbHandle->prepare('
                                delete
                                from vouchers
                                where vouchergroup = :vouchergroup
                                ');
        $stmt->bindParam(':vouchergroup', $vouchergroup);
        $stmt->execute();
    }

    /**
     * list all voucher groups
     * @return array
     */
    public function listVoucherGroups()
    {
        $response = array();
        $stmt = $this->dbHandle->prepare('select distinct vouchergroup from vouchers');
        $result = $stmt->execute();
        while ($row = $result->fetchArray()) {
            $response[] = $row['vouchergroup'];
        }
        return $response;
    }

    /**
     * list vouchers in group
     * @param $vouchergroup voucher group name
     * @return array
     */
    public function listVouchers($vouchergroup)
    {
        $response = array();
        $stmt = $this->dbHandle->prepare('
                  select username, validity, starttime, vouchergroup
                  from vouchers
                  where vouchergroup = :vouchergroup');
        $stmt->bindParam(':vouchergroup', $vouchergroup);
        $result = $stmt->execute();
        while ($row = $result->fetchArray()) {
            $record = array();
            $record['username'] = $row['username'];
            $record['validity'] = $row['validity'];
311
            # always calculate a starttime, if not registered yet, use now.
312
            $record['starttime'] = empty($row['starttime']) ? time() : $row['starttime'];
313
            $record['endtime'] = $record['starttime'] + $row['validity'];
314

315 316
            if (empty($row['starttime'])) {
                $record['state'] = 'unused';
317
            } elseif (time() < $record['endtime']) {
318 319 320 321 322 323 324 325 326 327
                $record['state'] = 'valid';
            } else {
                $record['state'] = 'expired';
            }

            $response[] = $record;
        }
        return $response;
    }

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    /**
     * expire voucher
     * @param string $username username
     */
    public function expireVoucher($username)
    {
        if ($this->dbHandle != null) {
            $stmt = $this->dbHandle->prepare('
                                    update vouchers
                                    set validity = 0,
                                        starttime = :starttime
                                    where username = :username
                                    ');
            $stmt->bindParam(':username', $username);
            $starttime = time();
            $stmt->bindParam(':starttime', $starttime, SQLITE3_INTEGER);
            $stmt->execute();
        }
    }

348
    /**
Ad Schellevis's avatar
Ad Schellevis committed
349
     * drop expired vouchers in group
350 351 352 353 354 355 356 357 358
     * @param $vouchergroup voucher group name
     * @return int number of deleted vouchers
     */
    public function dropExpired($vouchergroup)
    {
        $stmt = $this->dbHandle->prepare('
                  delete
                  from vouchers
                  where vouchergroup = :vouchergroup
359
                  and starttime is not null
360 361 362 363 364 365 366 367 368 369
                  and starttime + validity < :endtime
                  ');
        $stmt->bindParam(':vouchergroup', $vouchergroup);
        $endtime = time();
        $stmt->bindParam(':endtime', $endtime, SQLITE3_INTEGER);
        $stmt->execute();

        return $this->dbHandle->changes();
    }

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    /**
     * return session info
     * @return array mixed named list of authentication properties
     */
    public function getLastAuthProperties()
    {
        return $this->lastAuthProperties;
    }

    /**
     * authenticate user against voucher database
     * @param string $username username to authenticate
     * @param string $password user password
     * @return bool authentication status
     */
    public function authenticate($username, $password)
    {
        $stmt = $this->dbHandle->prepare('
            select username, password,validity, starttime
            from vouchers
            where username = :username
         ');
        $stmt->bindParam(':username', $username);
        $result = $stmt->execute();
        $row = $result->fetchArray();
        if ($row != null) {
            $passwd = crypt($password, (string)$row['password']);
            if ($passwd == (string)$row['password']) {
                // correct password, check validity
                if ($row['starttime'] == null) {
                    // initial login, set starttime for counter
                    $row['starttime'] = time();
                    $this->setStartTime($username, $row['starttime']);
                }
                if (time() - $row['starttime'] < $row['validity']) {
405
                    $this->lastAuthProperties['session_timeout'] = $row['validity'] - (time() - $row['starttime']);
406 407 408 409 410 411
                    return true;
                }
            }
        }
        return false;
    }
412 413 414 415 416 417 418 419 420 421 422

    /**
     * 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";
423
        $fields["simplePasswords"]["help"] = gettext("Use simple (less secure) passwords, which are easier to read");
424
        $fields["simplePasswords"]["validate"] = function ($value) {
425 426 427 428 429 430 431
            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");
432
        $fields["usernameLength"]["validate"] = function ($value) {
433
            if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) {
434
                return array(gettext("Username length must be a number or empty for default."));
435 436 437 438 439 440 441 442 443
            } 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");
444
        $fields["passwordLength"]["validate"] = function ($value) {
445
            if (!empty($value) && filter_var($value, FILTER_SANITIZE_NUMBER_INT) != $value) {
446
                return array(gettext("Password length must be a number or empty for default."));
447 448 449 450 451 452 453
            } else {
                return array();
            }
        };

        return $fields;
    }
454 455 456 457 458 459 460 461 462 463 464

    /**
     * groups not supported
     * @param string $username username to check
     * @param string $gid group id
     * @return boolean
     */
    public function groupAllowed($username, $gid)
    {
        return false;
    }
465
}