Welcome Guest ( Log In | Register )



 
Reply to this topicStart new topic
> A Simple Checking & Validation PHP Script
TavoxPeru
post Jun 9 2006, 05:30 AM
Post #1


Super Member
Group Icon

Group: [HOSTED]
Posts: 794
Joined: 8-April 06
From: Lima - Peru
Member No.: 12,579
myCENTs:78.07



Hi, there is sometimes that you need to password protect a directory in your site but you dont have access to a database or you dont need it because only a few users will access this directory, well the following script i develop will help in this situation.

With only 2 files you can implement a basic security, the first file is a simple txt file where you store your users information and the second file is the php script. You can name the files whatever you want and can be used in any site with php support.

The users.txt file: In this file simply put one line at the time your users information like this:
username1|userpassword1
username2|userpassword2
.
.
usernamen|userpasswordn

The chksec.php file: This file is the one that implements the basic security, here is the code:
CODE
<?php
if(!isset($_SERVER['PHP_AUTH_USER'])){
    Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");
    Header("HTTP/1.1 401 Unauthorized");
    echo "Authorization Required.";
    exit();
}
$theFile=file("users.txt");
$nUsers=sizeof($theFile);
$i=0;
$validated=FALSE;
while ($i<$nUsers && !$validated){
    $aFields=explode("|",$theFile[$i]);
    if (($_SERVER['PHP_AUTH_USER']==$aFields[0])&&($_SERVER['PHP_AUTH_PW']==chop($aFields[1]))) $validated=TRUE;
    $i++;
}
if(!$validated){
    Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");
    Header("HTTP/1.1 401 Unauthorized");
    echo "Authorization Required.";
    exit();
}
?>

Thats it, to work you just need to include this file in another php file. For example:
CODE
<?php
include("chksec.php");
echo "Welcome back " . $_SERVER['PHP_AUTH_USER'];
?>
Best regards,
Go to the top of the page
 
+Quote Post
Hercco
post Jun 9 2006, 02:35 PM
Post #2


Super Member
Group Icon

Group: Members
Posts: 595
Joined: 4-September 04
Member No.: 228



Nice script. I like how you used http authentication, which IMO is the proper way of doing it. Cookies and sessions are a bit... Well you know , they work on some cases are not particularly secure.
Go to the top of the page
 
+Quote Post
mastercomputers
post Jun 10 2006, 02:46 AM
Post #3


PESTICIDAL MANIAC
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



I like this except for the usage of the plain text file, if you were to do that, you should encode/encrypt your usernames and encrypt passwords, since having the username and password like this is not good, and encoding/encrypting the username eliminates half the problems while encrypting the password eliminates the other half.

You should really be using htpasswd for this, that's what their purpose is for and that has it's own encrypting methods for the file.

If you want the code for that method, I could write it up, strangely it's not different from your text file method, the only thing is we have encryption to work with.

Cheers,

MC
Go to the top of the page
 
+Quote Post
TavoxPeru
post Jun 10 2006, 04:19 AM
Post #4


Super Member
Group Icon

Group: [HOSTED]
Posts: 794
Joined: 8-April 06
From: Lima - Peru
Member No.: 12,579
myCENTs:78.07



QUOTE(mastercomputers @ Jun 9 2006, 09:46 PM) *

I like this except for the usage of the plain text file, if you were to do that, you should encode/encrypt your usernames and encrypt passwords, since having the username and password like this is not good, and encoding/encrypting the username eliminates half the problems while encrypting the password eliminates the other half.

You should really be using htpasswd for this, that's what their purpose is for and that has it's own encrypting methods for the file.

If you want the code for that method, I could write it up, strangely it's not different from your text file method, the only thing is we have encryption to work with.

Cheers,

MC

Yes you are right, i know that limitation and if you know the name of the txt file you get the user/password information and your security is fall down, if you do and post the code for the encryption method i think every body will very grateful.

regards,
Go to the top of the page
 
+Quote Post
mastercomputers
post Jun 10 2006, 04:26 AM
Post #5


PESTICIDAL MANIAC
Group Icon

Group: Members
Posts: 626
Joined: 1-September 04
From: Auckland, New Zealand
Member No.: 27



So I went ahead and created a method that can make use of .htpasswd.

You can still use the above code the alterations just differ in the handling of the file, so I created the htpasswd checking in a separate file:

htpasswd.inc.php

CODE
<?php
define('HTPASSWD','.htpasswd');

function load_htpasswd()
{
  if(file_exists(HTPASSWD) && filesize(HTPASSWD) > 0)
  {
    $htpasswd = file(HTPASSWD);
    $auth = array();
    foreach($htpasswd as $h)
    {
      $array = explode(':',$h);
      $user = $array[0];
      $pass = chop($array[1]);
      $auth[$user] = $pass;
    }
    return $auth;
  }
  else
    return array();
}

function sha1_htpasswd($pass)
{
  return '{SHA}' . base64_encode(pack('H*', sha1($pass)));
}

//function md5mod_htpasswd($pass)
//{
//  return 'I wonder where apache leaves this algorithm in their source, since I can not seem to work it out';
//}

function valid_user($userpass, $user, $pass)
{
  if(!isset($userpass[$user]))
    return false;

  $test = $userpass[$user];
  if(strcmp(substr($test,0,5),'{SHA}') == 0)
    return (strcmp(sha1_htpasswd($pass),$test) == 0);
//  else if(md5mod_htpasswd($pass))
//    return (strcmp(md5mod_htpasswd($pass),$test) == 0);
  else
    return (strcmp(crypt($pass, substr($test,0,CRYPT_SALT_LENGTH)),$test) == 0);
}
?>


and to use it as is:

CODE
<?php
// These are required...
function_exists('valid_user') || require('htpasswd.inc.php');
$userpass = load_htpasswd();
// ... End of requirements
// Below is just a test example.
if(valid_user($userpass, 'username', 'password'))
  echo 'User is valid';
else
  echo 'User is not valid';
?>


The only problem I have with this code is Apache's modified MD5 algorithm, I don't seem to be able to figure this out, or locate anyone who has this, so the only other option would be using system calls, but I won't do this method. So it will only work with SHA-1 (strong) and Crypt (weak).

This can be dropped into the above code (by TavoxPeru) which replaces everything after the first if(statement) and before the if(!validated) where you would change that to be:

CODE
if(!valid_user($userpass,$_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']))


Hopefully there's no errors, I tweaked some of the code in this thread, so I could have caused some errors.

I probably should have added a method to write an .htpasswd file and generate a hash for the password, though all it requires is creating/appending to .htpasswd a file that looks like:

CODE
username1:the_encoded_hash
username2:the_encoded_hash


Where the encoded hash is basically sending the plain password to the sha1_htpasswod('plain password') function to generate the password and storing that in the file, you could use crypt but it is a weak encryption. Could use a plain text file too, but you do not want to allow access to it, which is why you use .htpasswd, since you can not view these files online (well you should not be able to).

Cheers,

MC
Go to the top of the page
 
+Quote Post
TavoxPeru
post Jun 11 2006, 09:05 AM
Post #6


Super Member
Group Icon

Group: [HOSTED]
Posts: 794
Joined: 8-April 06
From: Lima - Peru
Member No.: 12,579
myCENTs:78.07



Thanks mastercomputers great code. I go ahead and implement your changes to my script and works fine and also i include the use of the defined() and define() functions to allow direct access to the included file only by the parent script as discussed here:CMS103 - Securing Your Website.

The new chksec.php:
CODE
<?php
defined( 'MY_ACCESS_CODE' ) or die( 'Direct Access to this location is not allowed.' );
function_exists('valid_user') || require('htpasswd.inc.php');
$userpass = load_htpasswd();
if(!isset($_SERVER['PHP_AUTH_USER'])){
    Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");
    Header("HTTP/1.1 401 Unauthorized");
    echo "Authorization Required.";
    exit();
}
if(!valid_user($userpass,$_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])){
    Header("WWW-Authenticate: Basic realm=\"Restricted Access\"");
    Header("HTTP/1.1 401 Unauthorized");
    echo "Authorization Required.";
    exit();
}
?>

This is the new test file:
CODE
<?php
define( "MY_ACCESS_CODE", true );
include("chksec.php");
echo "Welcome back " . $_SERVER['PHP_AUTH_USER'];
?>

I have a couple of questions, how do you do to implement a counter of login attempts??? for example only allow 3 login attempts, and do you have the method to write an .htpasswd file and generate a hash for the password??? If its true please post it to complete the script.

Best regards,
Go to the top of the page
 
+Quote Post
TavoxPeru
post Jun 14 2006, 08:52 PM
Post #7


Super Member
Group Icon

Group: [HOSTED]
Posts: 794
Joined: 8-April 06
From: Lima - Peru
Member No.: 12,579
myCENTs:78.07



I dont know if this the correct way to post this enhancement so to the admins please let me know if im wrong ok???.

In my previous post i drop a question related to how to implement a login counter attempts, for example 3 login attempts. Well, i go ahead and finish the script to support this behavior. So, if you want to implement this you only need to insert before line 2 of the chksec.php script the following code:
CODE
session_start();
if (!isset($_SESSION['access_count'])) {
    $_SESSION['access_count']=1;
}
else {
    $_SESSION['access_count']++;
}
if($_SESSION['access_count']>3) {
    unset($_SESSION['access_count']);
    $_SESSION = array(); // reset session array
    session_destroy();   // destroy session.
    die( 'You exceed the maximum number of login attempts.' );
}

That's it biggrin.gif

Best regards,
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic

Collapse

> Similar Topics

Topics Topics
  1. Trainable Anti-spam Filter Script(3)
  2. Php Script To Download File From Another Site(9)
  3. Need Help With A PHP - MySQL Registration Script(13)
  4. What Would Make A Good Registration Script?(4)
  5. How To Delete File Using PHP Shell Script(3)
  6. Online Multiplayer Chess Script(2)
  7. Automated File Structure Creation Script(3)
  8. Problem With Xhtml Validation(6)
  9. Authentication Script(1)
  10. Login Script(5)
  11. Xhtml Validation With Php In Cgi Mode(0)
  12. Please Help (php Join Script)(5)
  13. Automatic/remote Php Script Execution(9)
  14. Something Wrong With This Script?(9)
  15. Automated Product Suggestion Script(2)
  1. Run A Script When Expires A Session(6)
  2. Php Script Help(1)
  3. SQL Doesn't Connect In PHP Script(19)
  4. Warning: Mysql_result(): Supplied Argument Is Not A Valid Mysql Result Resource In ...(4)
  5. Password Recovery Script(6)
  6. Login Script(8)
  7. Free Forum Hosting Type Script Help!(2)
  8. Script Request(2)
  9. Writing And Testing My Own Login Script [solved](20)
  10. Make A Script Run Even If No User Is Online(6)
  11. Php Login Script(0)
  12. Myspacetv Download Php Script Help(6)
  13. Checking Without Loading(1)


 



- Lo-Fi Version Time is now: 22nd November 2008 - 06:42 AM