Subversion Repositories web_pages

Rev

Rev 12 | Rev 14 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

<?php

/**
     Copyright (c) 2025, Daily Data, Inc.

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

        Redistributions of source code must retain the above copyright notice, this
           list of conditions and the following disclaimer.
        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 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 OWNER 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 tab delimited file users.csv (defined in $csvFile). 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, if so, display a QR Code suitable for scanning with one time password program.

    Assumes csv file and qr image created by processOPNSense.pl.

    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
 
 */

// Define the path to the CSV file
$csvFile = 'users.csv';
// Define the path to the .ovpn files, if applicable
$ovpnDir = 'ovpn_files/';
$ovpnRegex = 'mcnoc_([a-z0-9]+)\.ovpn';
$ovpnFileName = '';
// name of image file
$imageFileName = '';
// topt code
$code = '';


function csvToArray( $csvFile, $delimiter = "\t" ) {
   // Initialize an array to hold the data
   $dataArray = [];

   // Open the CSV file for reading
   if (($handle = fopen($csvFile, 'r')) !== FALSE) {
       // Get the headers from the first row
       $headers = fgetcsv($handle, 1000, $delimiter);

       // Loop through each row in the CSV
       while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
           // Combine headers with data to create an associative array
           $rowData = array_combine($headers, $data);
           // Add the associative array to the main data array
           $dataArray[] = $rowData;
       }
       fclose($handle);
   } else {
       echo "Could not open the CSV file for reading.";
   }
   return $dataArray;
} // csvToArray


function ovpnFile ( $path, $username, $ovpnRegex ) {
   if ( $files = scandir( $path ) ) {
      foreach ($files as $key => $value ) {
         if ( preg_match( "/$ovpnRegex/", $value, $matches ) ) {
            if ( $matches[1] == $username ) {
               return $path . $matches[0];
            }
         }
      }
   } else {
      die( "Error trying to scan directory $path\n" );
   }
   return '';
} // ovpnFile

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

    $users = csvToArray( $csvFile, "\t" );
    if ( $users ) {
       $isValidUser = false;
       foreach ( $users as $key => $data ) {
          if ( $data['name'] === $username && $data['router'] === $router ) {
             if ( password_verify( $password, $data['password'] ) ) {
                $code = $data['otp'];
                $imageFileName = $data['filename'];
                $isValidUser = true;
                $ovpnFileName = ovpnFile( $ovpnDir, $data['name'], $ovpnRegex );
                $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 );
             }
             break;
         }
      }
      if ( ! $isValidUser )
         echo "<h1>Password wrong, or invalid user $username for router $router</h1>";
    } else {
        echo '<h1>Could not open the CSV file.</h1>';
    }
}

?>

<!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>
    <?php
       if ( ! empty( $imageFileName ) && ! empty( $code ) ) {
          echo "<div style='text-align: center;'>";
          echo "<img src='$imageFileName' alt='$code'>";
          echo "<br />Your code for $router is<br /><b>$code</b>";
          if ( !empty( $ovpnFileName ) ) {
             echo "<br /><a href='$ovpnFileName' download>Download your OpenVPN Config File</a>";
          }
          echo '</div>';
       }
    ?>
    <p>This page is updated hourly. If change your password, it will not be reflected here for an hour</p>
    <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">
             <?php
                // gets a list of all routers listed in $csvFile into array $routers
                exec( "tail -n+2 $csvFile | cut -f1 | sort | uniq | sort", $routers );
                #die( "<pre>" . print_r( $routers, true) . "</pre>" );
                foreach ( $routers as $index => $name ) {
                   print "<option value='$name'>$name</option>\n";
                }
            ?>
         </select>        
        <br>
        <input type="submit" value="Login">
    </form>
</body>
</html>