authgui.inc 15.7 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1
<?php
2

Ad Schellevis's avatar
Ad Schellevis committed
3
/*
4 5 6 7 8 9
    Copyright (C) 2008 Shrew Soft Inc
    Copyright (C) 2007-2008 Scott Ullrich <sullrich@gmail.com>
    Copyright (C) 2005-2006 Bill Marquette <bill.marquette@gmail.com>
    Copyright (C) 2006 Paul Taylor <paultaylor@winn-dixie.com>
    Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>
    All rights reserved.
10

11 12
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
13

14 15
    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
16

17 18 19
    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.
20

21 22 23 24 25 26 27 28 29 30
    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.
Ad Schellevis's avatar
Ad Schellevis committed
31
*/
32

33 34
require_once("auth.inc");

35
// provided via legacy_bindings.inc
36 37 38 39 40 41
global $priv_list;
$acl = new OPNsense\Core\ACL();
$priv_list = $acl->getLegacyPrivList();


function cmp_page_matches($page, & $matches, $fullwc = true) {
42 43 44
    if (!is_array($matches)) {
        return false;
    }
45

46 47 48 49 50
    /* skip any leading fwdslash */
    $test = strpos($page, "/");
    if ($test !== false && $test == 0) {
        $page = substr($page, 1);
    }
51

52 53 54
    /* look for a match */
    foreach ($matches as $match) {
        /* possibly ignore full wildcard match */
55 56 57
        if (!$fullwc && !strcmp($match ,"*")) {
            continue;
        }
58

59 60 61
        /* compare exact or wildcard match */
        $match =  str_replace(array(".", "*","?"), array("\.", ".*","\?"), $match);
        $result = preg_match("@^/{$match}$@", "/{$page}");
62

63 64 65 66
        if ($result) {
            return true;
        }
    }
67

68
    return false;
69 70 71 72
}

function isAllowedPage($page)
{
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    if (!isset($_SESSION['Username'])) {
        session_write_close();
        return false;
    }

    /* root access check */
    $user = getUserEntry($_SESSION['Username']);
    session_write_close();
    if (isset($user)) {
        if (isset($user['uid'])) {
            if ($user['uid'] == 0) {
                return true;
            }
        }
    }
91 92 93
    if ($page == "/") {
        $page = "/index.php";
    }
94 95 96 97

    /* user privelege access check */
    $allowedpages = getAllowedPages($_SESSION['Username']);
    return cmp_page_matches($page, $allowedpages);
98 99
}

Ad Schellevis's avatar
Ad Schellevis committed
100

101
function getPrivPages(& $entry, & $allowed_pages) {
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    global $priv_list;

    if (!isset($entry['priv']) || !is_array($entry['priv'])) {
        return;
    }

    foreach ($entry['priv'] as $pname) {
        if (strncmp($pname, "page-", 5)) {
            continue;
        }
        $priv = &$priv_list[$pname];
        if (!is_array($priv)) {
            continue;
        }
        $matches = &$priv['match'];
        if (!is_array($matches)) {
            continue;
        }
        foreach ($matches as $match) {
            $allowed_pages[] = $match;
        }
    }
124 125 126 127 128
}



function getAllowedPages($username) {
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    global $config;

    $allowed_pages = array();
    $allowed_groups = array();

    // search for a local user by name
    $local_user = getUserEntry($username);
    getPrivPages($local_user, $allowed_pages);

    // obtain local groups if we have a local user
    $allowed_groups = local_user_get_groups($local_user);

    // build a list of allowed pages
    if (is_array($config['system']['group']) && is_array($allowed_groups)) {
        foreach ($config['system']['group'] as $group) {
            // a bit odd, we have seem some cases in the wild where $group doesn't contain a name attribute.
            // this shouldn't happen, but to avoid warnings we will check over here.
            if (isset($group['name']) && in_array($group['name'], $allowed_groups)) {
                getPrivPages($group, $allowed_pages);
            }
        }
    }

    return $allowed_pages;
153 154 155
}


156 157
function session_auth(&$Login_Error)
{
158 159 160 161 162 163 164 165 166 167 168 169 170
    global $config, $_SESSION;

    // Handle HTTPS httponly and secure flags
    $currentCookieParams = session_get_cookie_params();
    session_set_cookie_params(
        $currentCookieParams["lifetime"],
        $currentCookieParams["path"],
        NULL,
        ($config['system']['webgui']['protocol'] == "https"),
        true
    );

    if (session_status() == PHP_SESSION_NONE) {
171 172 173 174
        if (session_start()) {
            $sess_name = session_name();
            setcookie($sess_name, session_id(), null, '/', null, null, ($config['system']['webgui']['protocol'] == "https"));
        }
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 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
    }

    // Detect protocol change
    if (!isset($_POST['login']) && !empty($_SESSION['Logged_In']) && $_SESSION['protocol'] != $config['system']['webgui']['protocol']) {
        session_write_close();
        return false;
    }

    /* Validate incoming login request */
    if (isset($_POST['login']) && !empty($_POST['usernamefld']) && !empty($_POST['passwordfld'])) {
        if (isset($config['system']['webgui']['authmode'])) {
            $authcfg = auth_get_authserver($config['system']['webgui']['authmode']);
        } else {
            $authcfg = null;
        }
        // authenticate using config settings, or local if failed
        if (authenticate_user($_POST['usernamefld'], $_POST['passwordfld'], $authcfg) ||
          authenticate_user($_POST['usernamefld'], $_POST['passwordfld'])) {
            // Generate a new id to avoid session fixation
            session_regenerate_id();
            $_SESSION['Logged_In'] = "True";
            $_SESSION['Username'] = $_POST['usernamefld'];
            $_SESSION['last_access'] = time();
            $_SESSION['protocol'] = $config['system']['webgui']['protocol'];
            if (!isset($config['system']['webgui']['quietlogin'])) {
              log_error(sprintf(gettext("Successful login for user '%1\$s' from: %2\$s"), $_POST['usernamefld'], $_SERVER['REMOTE_ADDR']));
            }
            header("Location: {$_SERVER['REQUEST_URI']}");
            exit;
        } else {
            /* give the user an error message */
            $Login_Error = gettext('Wrong username or password.');
            log_error("webConfigurator authentication error for '{$_POST['usernamefld']}' from {$_SERVER['REMOTE_ADDR']}");
        }
    }

    /* Show login page if they aren't logged in */
    if (empty($_SESSION['Logged_In'])) {
        session_write_close();
        return false;
    }

    /* If session timeout isn't set, we don't mark sessions stale */
    if (!isset($config['system']['webgui']['session_timeout'])) {
        /* Default to 4 hour timeout if one is not set */
        if ($_SESSION['last_access'] < (time() - 14400)) {
            $_GET['logout'] = true;
            $_SESSION['Logout'] = true;
        } else {
            $_SESSION['last_access'] = time();
        }
    } else if (intval($config['system']['webgui']['session_timeout']) == 0) {
          $_SESSION['last_access'] = time();
    } else {
        /* Check for stale session */
        if ($_SESSION['last_access'] < (time() - ($config['system']['webgui']['session_timeout'] * 60))) {
            $_GET['logout'] = true;
            $_SESSION['Logout'] = true;
        } else {
            $_SESSION['last_access'] = time();
        }
    }

    /* user hit the logout button */
    if (isset($_GET['logout'])) {
        if (isset($_SESSION['Logout'])) {
            log_error(sprintf(gettext("Session timed out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
        } else {
            log_error(sprintf(gettext("User logged out for user '%1\$s' from: %2\$s"), $_SESSION['Username'], $_SERVER['REMOTE_ADDR']));
        }

        /* wipe out $_SESSION */
        $_SESSION = array();

        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time()-42000, '/');
        }

        /* and destroy it */
        session_destroy();

        $scriptName = explode("/", $_SERVER["SCRIPT_FILENAME"]);
        $scriptElms = count($scriptName);
        $scriptName = $scriptName[$scriptElms-1];

        /* redirect to page the user is on, it'll prompt them to login again */
        header("Location: {$scriptName}");
        exit;
    }

    session_write_close();
    return true;
267 268
}

269
$Login_Error = '';
270

Ad Schellevis's avatar
Ad Schellevis committed
271
/* Authenticate user - exit if failed */
272 273
if (!session_auth($Login_Error)) {
    display_login_form($Login_Error);
274
    exit;
Ad Schellevis's avatar
Ad Schellevis committed
275 276 277 278 279 280
}

/*
 * redirect to first allowed page if requesting a wrong url
 */
if (!isAllowedPage($_SERVER['REQUEST_URI'])) {
281 282 283
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
284
    $allowedpages = getAllowedPages($_SESSION['Username']);
285 286 287 288 289 290 291 292
    if (count($allowedpages) > 0) {
        $page = str_replace('*', '', $allowedpages[0]);
        $username = empty($_SESSION["Username"]) ? "(system)" : $_SESSION['Username'];
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $username .= '@' . $_SERVER['REMOTE_ADDR'];
        }
        log_error("{$username} attempted to access {$_SERVER['REQUEST_URI']} but does not have access to that page. Redirecting to {$page}.");

293
        header("Location: /{$page}");
294 295 296 297 298
        exit;
    } else {
        display_error_form("201", gettext("No page assigned to this user! Click here to logout."));
        exit;
    }
299
}
Ad Schellevis's avatar
Ad Schellevis committed
300

301

302 303 304 305 306
/*
 * determine if the user is allowed access to the requested page
 */
function display_error_form($http_code, $desc)
{
307
    $themename = htmlspecialchars(get_current_theme());
Ad Schellevis's avatar
Ad Schellevis committed
308

309 310 311 312
?><!doctype html>
<!--[if IE 8 ]><html lang="en" class="ie ie8 lte9 lte8 no-js"><![endif]-->
<!--[if IE 9 ]><html lang="en" class="ie ie9 lte9 no-js"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en" class="no-js"><!--<![endif]-->
313 314 315 316 317 318 319 320 321 322 323 324 325
  <head>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <meta name="robots" content="index, follow, noodp, noydir" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <meta name="copyright" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

    <title><?=$http_code?></title>

Ad Schellevis's avatar
Ad Schellevis committed
326
    <link href="/ui/themes/<?= $themename ?>/build/css/main.css" rel="stylesheet">
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    <link href="/ui/themes/<?= $themename ?>/build/images/favicon.png" rel="shortcut icon">

    <!--[if lt IE 9]><script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script><![endif]-->
  </head>
  <body class="page-login">
    <div id="errordesc">
      <h1>&nbsp</h1>
      <a href="/index.php?logout">
      <p id="errortext" style="vertical-align: middle; text-align: center;">
        <span style="color: #000000; font-weight: bold;">
          <?=$desc;?>
        </span>
      </p>
    </div>
  </body>
342
</html><?php
Ad Schellevis's avatar
Ad Schellevis committed
343 344 345

} // end function

346
function display_login_form($Login_Error = '')
347
{
348
    global $config, $g;
349 350

    $themename = htmlspecialchars(get_current_theme());
351 352 353

    unset($input_errors);

354 355 356 357 358
    /*
     * Check against locally configured IP addresses, which will catch when
     * someone port-forwards WebGUI access from WAN to an internal IP on the
     * router.
     */
359
    $local_ip = isAuthLocalIP($http_host);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

    if (isset($config['openvpn']['openvpn-server'])) {
        foreach ($config['openvpn']['openvpn-server'] as $ovpns) {
            if (is_ipaddrv4($http_host) && !empty($ovpns['tunnel_network']) && ip_in_subnet($http_host, $ovpns['tunnel_network'])) {
                $local_ip = true;
                break;
            }

            if (is_ipaddrv6($http_host) && !empty($ovpns['tunnel_networkv6']) && ip_in_subnet($http_host, $ovpns['tunnel_networkv6'])) {
                $local_ip = true;
                break;
            }
        }
    }
    setcookie("cookie_test", time() + 3600);
    $have_cookies = isset($_COOKIE["cookie_test"]);
376

377 378 379 380
?><!doctype html>
<!--[if IE 8 ]><html lang="en" class="ie ie8 lte9 lte8 no-js"><![endif]-->
<!--[if IE 9 ]><html lang="en" class="ie ie9 lte9 no-js"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en" class="no-js"><!--<![endif]-->
381
  <head>
382

383 384
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
385

386 387 388 389 390
    <meta name="robots" content="index, follow, noodp, noydir" />
    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <meta name="copyright" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
391

392
    <title><?=gettext("Login"); ?></title>
393

Ad Schellevis's avatar
Ad Schellevis committed
394
    <link href="/ui/themes/<?= $themename ?>/build/css/main.css" rel="stylesheet">
395
    <link href="/ui/themes/<?= $themename ?>/build/images/favicon.png" rel="shortcut icon">
396

397
    <!--[if lt IE 9]><script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script><![endif]-->
398

399 400
  </head>
  <body class="page-login">
401

402 403
  <div class="container">
    <?php
404
        if (is_ipaddr($http_host) && !$local_ip && !isset($config['system']['webgui']['nohttpreferercheck'])) {
405
            print_info_box(sprintf(gettext("You are accessing this router by an IP address not configured locally, which may be forwarded by NAT or other means. %sIf you did not setup this forwarding, you may be the target of a man-in-the-middle attack."),'<br /><br />'));
406 407 408
        }
                $loginautocomplete = isset($config['system']['webgui']['loginautocomplete']) ? '' : 'autocomplete="off"';
            ?>
409 410


411 412 413
    <main class="login-modal-container">
      <header class="login-modal-head" style="height:55px;">
        <div class="navbar-brand">
Ad Schellevis's avatar
Ad Schellevis committed
414
          <img src="/ui/themes/<?= $themename ?>/build/images/default-logo.png" height="30" alt="logo"/>
415 416
        </div>
      </header>
417

418 419
      <div class="login-modal-content">
        <div id="inputerrors" class="text-danger"><?= !empty($Login_Error) ? $Login_Error : '&nbsp;' ?></div><br />
420

421
            <form class="clearfix" id="iform" name="iform" method="post" <?= $loginautocomplete ?> action="<?=$_SERVER['REQUEST_URI'];?>">
422

423 424 425 426
        <div class="form-group">
          <label for="usernamefld"><?=gettext("Username:"); ?></label>
          <input id="usernamefld" type="text" name="usernamefld" class="form-control user" tabindex="1" autofocus="autofocus" autocapitalize="off" autocorrect="off" />
        </div>
427

428 429 430 431
        <div class="form-group">
          <label for="passwordfld"><?=gettext("Password:"); ?></label>
          <input id="passwordfld" type="password" name="passwordfld" class="form-control pwd" tabindex="2" />
        </div>
432

433
        <button type="submit" name="login" value="1" class="btn btn-primary pull-right"><?=gettext("Login"); ?></button>
434

435
      </form>
436

437 438 439 440 441 442
      <?php if (!$have_cookies && isset($_POST['login'])) : ?>
        <br /><br />
        <span class="text-danger">
          <?= gettext("Your browser must support cookies to login."); ?>
        </span>
      <?php endif; ?>
443

444
          </div>
445

446 447 448 449 450
      </main>
      <div class="login-foot text-center">
        <a target="_blank" href="<?=$g['product_website']?>" class="redlnk"><?=$g['product_name']?></a> (c) <?=$g['product_copyright_years']?>
        <a href="<?=$g['product_copyright_url']?>" class="tblnk"><?=$g['product_copyright_owner']?></a>
      </div>
451

452
    </div>
453

454 455
    </body>
  </html>
456
<?php } // end function