Subversion Repositories web_pages

Rev

Rev 15 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

<?php

/**
 * Copyright (c) 2025, Daily Data, Inc.
 * 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.
 * 3. Neither the name of Daily Data, Inc. nor the names of its contributors may be
 *    used to endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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.
 */

/**

   PHP script which reads configuration file containing user information. Users
   are presented with a username and password box and a router selector.
   When processed, will read data file and determine if the credentials match any line
   and
   * display a QR Code suitable for scanning with one time authentication app
   * display the OTP seed code in case user wants to enter it manually
   * provide a link to download the OpenVPN configuration file for that user

   Assumes configuration file generated by loadOpnSense.pl
   Assumes QR code images are pre-generated and stored in a web accessible location
   Assumes OpenVPN configuration files are pre-generated and stored in a web accessible location
   Assumes passwords are hashed using password_hash function

   
   Version 1.0.0 RWR 2025-09-21
      Initial Release
   Version 1.1.0 RWR 2025-09-27
      Added capability of downloading VPN configuration file
   Version 1.2.0 RWR 2025-10-01
     Reading from json file instead of csv
     Removed dependency on exec and external commands
     Added logging of successful logins
     automatically generate router list from config file
     Added some error checking for missing qr code image file and ovpn file

 */

   define('VERSION', '1.2.0');

// this is the only variable you may need to change
// everything else is in the configuration file
$configFile = __DIR__ . '/users.json';

$isValidUser = false;

// we need the config data for form processing and validation, so always load it
if (file_exists($configFile)) {
    $configData = json_decode(file_get_contents($configFile), true);
} else {
    die("Configuration file $configFile not found");
}

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset( $_REQUEST['btnLogin'])) {
    // Get the username and password from the form
    $username = $_POST['username'];
    $password = $_POST['password'];
    $router = $_POST['router'];

    if ($configData) {
        $isValidUser = false;
        if (isset($configData[$router]) && isset($configData[$router]['users'][$username])) {
            $data = $configData[$router]['users'][$username];
            if (password_verify($password, $data['password'])) {
                $isValidUser = true;
                $code = $data['otp_seed'];
                $imageFileName = $data['qrFile'];
                $ovpnFileName = $data['ovpnFile'];
                $log = date("Y-m-d H:i:s") . "\t" . $_SERVER['REMOTE_ADDR'] . "\t" .
                "Success\t" . $username."\t" .PHP_EOL;
                file_put_contents('./log_'.date("j.n.Y").'.log', $log, FILE_APPEND);
            }
        }
    } else {
        print '<h1>Could not open the configuration file.</h1>';
    }
} else if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['refreshRouter'])) {
    $router = preg_replace('/[^A-Za-z0-9_-]/', '', $_POST['refreshRouter']);
    $file = "/tmp/update_$router";
    file_put_contents($file, time());
    exit;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Get QR Code</title>
</head>
<body>
   <h1 style='text-align: center;'>OTP and OVPN configuration download</h1>
   <div id='debug'>
      <?php
         //print "<pre>REQUEST<br/>" . print_r( $_REQUEST, true) . "</pre>";
      ?>

   <div id='qr' style='text-align: center;'>
      <?php
         if ( isset( $_REQUEST['btnLogin']) ) {
            if ( $isValidUser ) {
               if (empty($code) || empty($imageFileName) || !file_exists($imageFileName)) {
                  print "<p><b>QR Code image file not found</b></p>";
                  print "<p>You may not be set up with a TOTP code on $router, talk to an administrator</p>";
               } else {
                  // all good
                  print "<img src='$imageFileName' alt='$code'>";
                  print "<br />Your code for $router is<br /><b>$code</b>";
               }
               if (empty($ovpnFileName)) {
                  print "<br />No OpenVPN configuration file available";
               } else {
                  print "<br /><a href='$ovpnFileName' download>Download your OpenVPN Config File</a>";
               }
            } else {
               print "<h1>Password wrong, or invalid user $username for router $router</h1>";
            }
         }
      ?>
   </div>

   <div id='login'>
      <form method="POST" action="">
         <label for="username">Username:</label>
         <input type="text" id="username" name="username" required>
         <br>
         <label for="password">Password:</label>
         <input type="password" id="password" name="password" required>
         <br>
         <label for="router">Router:</label>
            <select name="router" id="router" onchange="updateTimestampAndRefreshLink()">
               <?php
                  $routers = array_keys($configData);
                  foreach ($routers as $index => $name) {
                     print "<option value='$name'>$name</option>\n";
                  }
               ?>
            </select>        
         <br>
         <input type="submit" name="btnLogin" value="Login" id="loginBtn">
         <button type="button" id="refreshBtn" style="margin-left:10px;">Request Refresh</button>
         <div id="routerTimestamp" style="margin-top:10px;"></div>
         <div id="refreshDiv" style="margin-top:10px;"></div>
      </form>
   </div>

   <script>
   const configData = <?php echo json_encode($configData); ?>;
   function updateTimestampAndRefreshLink() {
      var router = document.getElementById('router').value;
      var tsDiv = document.getElementById('routerTimestamp');
      if (configData[router] && configData[router]['lastUpdate']) {
         var date = new Date(configData[router]['lastUpdate'] * 1000);
         tsDiv.innerHTML = '<b>Last update for ' + router + ':</b> ' + date.toLocaleString();
      } else {
         tsDiv.innerHTML = '<b>No update timestamp available for ' + router + '</b>';
      }
   }
   function requestRefresh(router) {
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '', true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.send('refreshRouter=' + encodeURIComponent(router));
      alert('Refresh requested for ' + router + "\nPlease wait 2 minutes before retrying");
   }
   document.getElementById('router').addEventListener('change', updateTimestampAndRefreshLink);
   window.onload = function() {
      updateTimestampAndRefreshLink();
      document.getElementById('refreshBtn').onclick = function() {
         var router = document.getElementById('router').value;
         requestRefresh(router);
      };
      document.getElementById('loginBtn').focus();
   };
   document.querySelector('form').addEventListener('keydown', function(e) {
      if (e.key === 'Enter') {
         e.preventDefault();
         document.getElementById('loginBtn').click();
      }
   });
   </script>

</body>
</html>