Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@frankleromain
Created April 14, 2012 20:25
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save frankleromain/2387759 to your computer and use it in GitHub Desktop.
Save frankleromain/2387759 to your computer and use it in GitHub Desktop.
Creating a Secure PHP Login Script
<?php
header('HTTP/1.1 403 Forbidden');
?>
<html>
<head>
<title>Congratulations! You have been DENIED access</title>
</head>
<body>
<font size="4">You have been denied access because of the following reasons:<br /><br />
1.) Too many failed login attempts, so you are likely brute forcing through logins.<br />
2.) You have been accessing an authorized user account login through a stolen or hijacked session.<br /></font>
</body>
</html>
<?php
require('authenticate.php');
?>
This is a private website that utilizes some form of secure login for selected visitors.
<br />
<br />
===============<br />
Navigation Menu<br />
===============<br />
<a href="index.php">Homepage</a><br />
<a href="about.php">About this page</a><br />
<?php if (isset($_SESSION['logged_in'])) { ?><a href="logout.php?signature=<?php echo $_SESSION['signature']; ?>">Logout</a><br /><?php } ?>
<?php
/*
* This is a PHP Secure login system.
* - Documentation and latest version
* Refer to readme.txt
* - To download the latest copy:
* http://www.php-developer.org/php-secure-authentication-of-user-logins/
* - Discussion, Questions and Inquiries
* email codex_m@php-developer.org
*
* Copyright (c) 2011 PHP Secure login system -- http://www.php-developer.org
* AUTHORS:
* Codex-m
* Refer to license.txt to how code snippets from other authors or sources are attributed.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//require user configuration and database connection parameters
//Start PHP session
session_start();
//require user configuration and database connection parameters
require('config.php');
if (($_SESSION['logged_in']) == TRUE) {
//valid user has logged-in to the website
//Check for unauthorized use of user sessions
$iprecreate = $_SERVER['REMOTE_ADDR'];
$useragentrecreate = $_SERVER["HTTP_USER_AGENT"];
$signaturerecreate = $_SESSION['signature'];
//Extract original salt from authorized signature
$saltrecreate = substr($signaturerecreate, 0, $length_salt);
//Extract original hash from authorized signature
$originalhash = substr($signaturerecreate, $length_salt, 40);
//Re-create the hash based on the user IP and user agent
//then check if it is authorized or not
$hashrecreate = sha1($saltrecreate . $iprecreate . $useragentrecreate);
if (!($hashrecreate == $originalhash)) {
//Signature submitted by the user does not matched with the
//authorized signature
//This is unauthorized access
//Block it
header(sprintf("Location: %s", $forbidden_url));
exit;
}
//Session Lifetime control for inactivity
//Credits: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes
if ((isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $sessiontimeout))) {
session_destroy();
session_unset();
//redirect the user back to login page for re-authentication
$redirectback = $domain . 'securelogin/';
header(sprintf("Location: %s", $redirectback));
}
$_SESSION['LAST_ACTIVITY'] = time();
}
//Pre-define validation
$validationresults = TRUE;
$registered = TRUE;
$recaptchavalidation = TRUE;
//Trapped brute force attackers and give them more hard work by providing a captcha-protected page
$iptocheck = $_SERVER['REMOTE_ADDR'];
$iptocheck = mysql_real_escape_string($iptocheck);
if ($fetch = mysql_fetch_array(mysql_query("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`='$iptocheck'"))) {
//Already has some IP address records in the database
//Get the total failed login attempts associated with this IP address
$resultx = mysql_query("SELECT `failedattempts` FROM `ipcheck` WHERE `loggedip`='$iptocheck'");
$rowx = mysql_fetch_array($resultx);
$loginattempts_total = $rowx['failedattempts'];
If ($loginattempts_total > $maxfailedattempt) {
//too many failed attempts allowed, redirect and give 403 forbidden.
header(sprintf("Location: %s", $forbidden_url));
exit;
}
}
//Check if a user has logged-in
if (!isset($_SESSION['logged_in'])) {
$_SESSION['logged_in'] = FALSE;
}
//Check if the form is submitted
if ((isset($_POST["pass"])) && (isset($_POST["user"])) && ($_SESSION['LAST_ACTIVITY'] == FALSE)) {
//Username and password has been submitted by the user
//Receive and sanitize the submitted information
function sanitize($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = mysql_real_escape_string($data);
return $data;
}
$user = sanitize($_POST["user"]);
$pass = sanitize($_POST["pass"]);
//validate username
if (!($fetch = mysql_fetch_array(mysql_query("SELECT `username` FROM `authentication` WHERE `username`='$user'")))) {
//no records of username in database
//user is not yet registered
$registered = FALSE;
}
if ($registered == TRUE) {
//Grab login attempts from MySQL database for a corresponding username
$result1 = mysql_query("SELECT `loginattempt` FROM `authentication` WHERE `username`='$user'");
$row = mysql_fetch_array($result1);
$loginattempts_username = $row['loginattempt'];
}
if (($loginattempts_username > 2) || ($registered == FALSE) || ($loginattempts_total > 2)) {
//Require those user with login attempts failed records to
//submit captcha and validate recaptcha
require_once('recaptchalib.php');
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
//captcha validation fails
$recaptchavalidation = FALSE;
} else {
$recaptchavalidation = TRUE;
}
}
//Get correct hashed password based on given username stored in MySQL database
if ($registered == TRUE) {
//username is registered in database, now get the hashed password
$result = mysql_query("SELECT `password` FROM `authentication` WHERE `username`='$user'");
$row = mysql_fetch_array($result);
$correctpassword = $row['password'];
$salt = substr($correctpassword, 0, 64);
$correcthash = substr($correctpassword, 64, 64);
$userhash = hash("sha256", $salt . $pass);
}
if ((!($userhash == $correcthash)) || ($registered == FALSE) || ($recaptchavalidation == FALSE)) {
//user login validation fails
$validationresults = FALSE;
//log login failed attempts to database
if ($registered == TRUE) {
$loginattempts_username = $loginattempts_username + 1;
$loginattempts_username = intval($loginattempts_username);
//update login attempt records
mysql_query("UPDATE `authentication` SET `loginattempt` = '$loginattempts_username' WHERE `username` = '$user'");
//Possible brute force attacker is targeting registered usernames
//check if has some IP address records
if (!($fetch = mysql_fetch_array(mysql_query("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`='$iptocheck'")))) {
//no records
//insert failed attempts
$loginattempts_total = 1;
$loginattempts_total = intval($loginattempts_total);
mysql_query("INSERT INTO `ipcheck` (`loggedip`, `failedattempts`) VALUES ('$iptocheck', '$loginattempts_total')");
} else {
//has some records, increment attempts
$loginattempts_total = $loginattempts_total + 1;
mysql_query("UPDATE `ipcheck` SET `failedattempts` = '$loginattempts_total' WHERE `loggedip` = '$iptocheck'");
}
}
//Possible brute force attacker is targeting randomly
if ($registered == FALSE) {
if (!($fetch = mysql_fetch_array(mysql_query("SELECT `loggedip` FROM `ipcheck` WHERE `loggedip`='$iptocheck'")))) {
//no records
//insert failed attempts
$loginattempts_total = 1;
$loginattempts_total = intval($loginattempts_total);
mysql_query("INSERT INTO `ipcheck` (`loggedip`, `failedattempts`) VALUES ('$iptocheck', '$loginattempts_total')");
} else {
//has some records, increment attempts
$loginattempts_total = $loginattempts_total + 1;
mysql_query("UPDATE `ipcheck` SET `failedattempts` = '$loginattempts_total' WHERE `loggedip` = '$iptocheck'");
}
}
} else {
//user successfully authenticates with the provided username and password
//Reset login attempts for a specific username to 0 as well as the ip address
$loginattempts_username = 0;
$loginattempts_total = 0;
$loginattempts_username = intval($loginattempts_username);
$loginattempts_total = intval($loginattempts_total);
mysql_query("UPDATE `authentication` SET `loginattempt` = '$loginattempts_username' WHERE `username` = '$user'");
mysql_query("UPDATE `ipcheck` SET `failedattempts` = '$loginattempts_total' WHERE `loggedip` = '$iptocheck'");
//Generate unique signature of the user based on IP address
//and the browser then append it to session
//This will be used to authenticate the user session
//To make sure it belongs to an authorized user and not to anyone else.
//generate random salt
function genRandomString() {
//credits: http://bit.ly/a9rDYd
$length = 50;
$characters = "0123456789abcdef";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$random = genRandomString();
$salt_ip = substr($random, 0, $length_salt);
//hash the ip address, user-agent and the salt
$useragent = $_SERVER["HTTP_USER_AGENT"];
$hash_user = sha1($salt_ip . $iptocheck . $useragent);
//concatenate the salt and the hash to form a signature
$signature = $salt_ip . $hash_user;
//Regenerate session id prior to setting any session variable
//to mitigate session fixation attacks
session_regenerate_id();
//Finally store user unique signature in the session
//and set logged_in to TRUE as well as start activity time
$_SESSION['signature'] = $signature;
$_SESSION['logged_in'] = TRUE;
$_SESSION['LAST_ACTIVITY'] = time();
}
}
if (!$_SESSION['logged_in']):
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
.invalid {
border: 1px solid #000000;
background: #FF00FF;
}
</style>
</head>
<body >
<h2>Restricted Access</h2>
<br />
Hi! This private website is restricted to public access. Please enter username and password to proceed.
<br /><br />
<!-- START OF LOGIN FORM -->
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
Username: <input type="text" class="<?php if ($validationresults == FALSE)
echo "invalid"; ?>" id="user" name="user">
Password: <input name="pass" type="password" class="<?php if ($validationresults == FALSE)
echo "invalid"; ?>" id="pass" >
<br /><br />
<?php if (($loginattempts_username > 2) || ($registered == FALSE) || ($loginattempts_total > 2)) { ?>
Type the captcha below:
<br /> <br />
<?php
require_once('recaptchalib.php');
echo recaptcha_get_html($publickey);
?>
<br />
<?php } ?>
<?php if ($validationresults == FALSE)
echo '<font color="red">Please enter valid username, password or captcha (if required).</font>'; ?><br />
<input type="submit" value="Login">
</form>
<!-- END OF LOGIN FORM -->
<br />
<br />
If you are not registered. You can register by clicking <a href="register.php">here</a>.
</body>
</html>
<?php
exit();
endif;
?>
<?php
/*
* This is a PHP Secure login system.
* - Documentation and latest version
* Refer to readme.txt
* - To download the latest copy:
* http://www.php-developer.org/php-secure-authentication-of-user-logins/
* - Discussion, Questions and Inquiries
* email codex_m@php-developer.org
*
* Copyright (c) 2011 PHP Secure login system -- http://www.php-developer.org
* AUTHORS:
* Codex-m
* Refer to license.txt to how code snippets from other authors or sources are attributed.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//require user configuration and database connection parameters
///////////////////////////////////////
//START OF USER CONFIGURATION/////////
/////////////////////////////////////
//Define MySQL database parameters
$username = "Your MySQL username";
$password = "Your MySQL password";
$hostname = "Your MySQL hostname";
$database = "Your MySQL database name";
//Define your canonical domain including trailing slash!, example:
$domain = "http://www.example.com/";
//Define sending email notification to webmaster
$email = 'youremail@example.com';
$subject = 'New user registration notification';
$from = 'From: www.example.com';
//Define Recaptcha parameters
$privatekey = "Your Recaptcha private key";
$publickey = "Your Recaptcha public key";
//Define length of salt,minimum=10, maximum=35
$length_salt = 15;
//Define the maximum number of failed attempts to ban brute force attackers
//minimum is 5
$maxfailedattempt = 5;
//Define session timeout in seconds
//minimum 60 (for one minute)
$sessiontimeout = 180;
////////////////////////////////////
//END OF USER CONFIGURATION/////////
////////////////////////////////////
//DO NOT EDIT ANYTHING BELOW!
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select $database");
$loginpage_url = $domain . 'securelogin/';
$forbidden_url = $domain . 'securelogin/403forbidden.php';
?>
<?php
require('authenticate.php');
?>
Hi this is a protected content! You are logged-in. Happy viewing.
<br />
<br />
===============<br />
Navigation Menu<br />
===============<br />
<a href="index.php">Homepage</a><br />
<a href="about.php">About this page</a><br />
<?php if (isset($_SESSION['logged_in'])) { ?><a href="logout.php?signature=<?php echo $_SESSION['signature']; ?>">Logout</a><br /><?php } ?>
PHP Secure Login System
Copyright 2011 by Codex-m at www.php-developer.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Wherever third party code has been used, credit has been given in the code's
comments.
PHP Secure Login System is released under the GPL
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
WRITTEN OFFER
The source code for any program binaries or compressed scripts that are
included with this program can be freely obtained at the following URL:
http://www.php-developer.org/php-secure-authentication-of-user-logins/
<?php
session_start();
require('config.php');
function sanitize($data) {
$data = trim($data);
$data = htmlspecialchars($data);
return $data;
}
$signature = sanitize($_GET['signature']);
if ($signature === $_SESSION['signature']) {
//authenticated user request
$_SESSION['logged_in'] = False;
session_destroy();
session_unset();
echo 'You have successfully logout from the private website! Thank you.<br /><br />';
?>
===============<br />
Navigation Menu<br />
===============<br />
<a href="index.php">Homepage</a><br />
<a href="about.php">About this page</a><br />
<?php
} else {
//unauthorized logout
header(sprintf("Location: %s", $forbidden_url));
exit;
}
?>
<?php
/*
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* http://recaptcha.net/plugins/php/
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
* Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
* AUTHORS:
* Mike Crawford
* Ben Maurer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* The reCAPTCHA server URL's
*/
define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
define("RECAPTCHA_VERIFY_SERVER", "www.google.com");
/**
* Encodes the given data into a query string format
* @param $data - array of string elements to be encoded
* @return string - encoded request
*/
function _recaptcha_qsencode($data) {
$req = "";
foreach ($data as $key => $value)
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
// Cut the last '&'
$req = substr($req, 0, strlen($req) - 1);
return $req;
}
/**
* Submits an HTTP POST to a reCAPTCHA server
* @param string $host
* @param string $path
* @param array $data
* @param int port
* @return array response
*/
function _recaptcha_http_post($host, $path, $data, $port = 80) {
$req = _recaptcha_qsencode($data);
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($req) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $req;
$response = '';
if (false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) )) {
die('Could not open socket');
}
fwrite($fs, $http_request);
while (!feof($fs)) $response .= fgets($fs, 1160); // One TCP-IP packet
fclose($fs);
$response = explode("\r\n\r\n", $response, 2);
return $response;
}
/**
* Gets the challenge HTML (javascript and non-javascript version).
* This is called from the browser, and the resulting reCAPTCHA HTML widget
* is embedded within the HTML form it was called from.
* @param string $pubkey A public key for reCAPTCHA
* @param string $error The error given by reCAPTCHA (optional, default is null)
* @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
* @return string - The HTML to be embedded in the user's form.
*/
function recaptcha_get_html($pubkey, $error = null, $use_ssl = true) {
if ($pubkey == null || $pubkey == '') {
die("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
if ($use_ssl) {
$server = RECAPTCHA_API_SECURE_SERVER;
} else {
$server = RECAPTCHA_API_SERVER;
}
$errorpart = "";
if ($error) {
$errorpart = "&amp;error=" . $error;
}
return '<script type="text/javascript" src="' . $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
<noscript>
<iframe src="' . $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>';
}
/**
* A ReCaptchaResponse is returned from recaptcha_check_answer()
*/
class ReCaptchaResponse {
var $is_valid;
var $error;
}
/**
* Calls an HTTP POST function to verify if the user's guess was correct
* @param string $privkey
* @param string $remoteip
* @param string $challenge
* @param string $response
* @param array $extra_params an array of extra variables to post to the server
* @return ReCaptchaResponse
*/
function recaptcha_check_answer($privkey, $remoteip, $challenge, $response,
$extra_params = array()) {
if ($privkey == null || $privkey == '') {
die("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
if ($remoteip == null || $remoteip == '') {
die("For security reasons, you must pass the remote ip to reCAPTCHA");
}
//discard spam submissions
if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
$recaptcha_response = new ReCaptchaResponse();
$recaptcha_response->is_valid = false;
$recaptcha_response->error = 'incorrect-captcha-sol';
return $recaptcha_response;
}
$response = _recaptcha_http_post(RECAPTCHA_VERIFY_SERVER,
"/recaptcha/api/verify",
array(
'privatekey' => $privkey,
'remoteip' => $remoteip,
'challenge' => $challenge,
'response' => $response
) + $extra_params
);
$answers = explode("\n", $response [1]);
$recaptcha_response = new ReCaptchaResponse();
if (trim($answers [0]) == 'true') {
$recaptcha_response->is_valid = true;
} else {
$recaptcha_response->is_valid = false;
$recaptcha_response->error = $answers [1];
}
return $recaptcha_response;
}
/**
* gets a URL where the user can sign up for reCAPTCHA. If your application
* has a configuration page where you enter a key, you should provide a link
* using this function.
* @param string $domain The domain where the page is hosted
* @param string $appname The name of your application
*/
function recaptcha_get_signup_url($domain = null, $appname = null) {
return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode(array('domains' => $domain, 'app' => $appname));
}
function _recaptcha_aes_pad($val) {
$block_size = 16;
$numpad = $block_size - (strlen($val) % $block_size);
return str_pad($val, strlen($val) + $numpad, chr($numpad));
}
/* Mailhide related code */
function _recaptcha_aes_encrypt($val, $ky) {
if (!function_exists("mcrypt_encrypt")) {
die("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
}
$mode = MCRYPT_MODE_CBC;
$enc = MCRYPT_RIJNDAEL_128;
$val = _recaptcha_aes_pad($val);
return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}
function _recaptcha_mailhide_urlbase64($x) {
return strtr(base64_encode($x), '+/', '-_');
}
/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($pubkey, $privkey, $email) {
if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
die("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
"you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
}
$ky = pack('H*', $privkey);
$cryptmail = _recaptcha_aes_encrypt($email, $ky);
return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64($cryptmail);
}
/**
* gets the parts of the email to expose to the user.
* eg, given johndoe@example,com return ["john", "example.com"].
* the email is then displayed as john...@example.com
*/
function _recaptcha_mailhide_email_parts($email) {
$arr = preg_split("/@/", $email);
if (strlen($arr[0]) <= 4) {
$arr[0] = substr($arr[0], 0, 1);
} else if (strlen($arr[0]) <= 6) {
$arr[0] = substr($arr[0], 0, 3);
} else {
$arr[0] = substr($arr[0], 0, 4);
}
return $arr;
}
/**
* Gets html to display an email address given a public an private key.
* to get a key, go to:
*
* http://www.google.com/recaptcha/mailhide/apikey
*/
function recaptcha_mailhide_html($pubkey, $privkey, $email) {
$emailparts = _recaptcha_mailhide_email_parts($email);
$url = recaptcha_mailhide_url($pubkey, $privkey, $email);
return htmlentities($emailparts[0]) . "<a href='" . htmlentities($url) .
"' onclick=\"window.open('" . htmlentities($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities($emailparts [1]);
}
?>
<?php
/*
* This is a PHP Secure login system.
* - Documentation and latest version
* Refer to readme.txt
* - To download the latest copy:
* http://www.php-developer.org/php-secure-authentication-of-user-logins/
* - Discussion, Questions and Inquiries
* email codex_m@php-developer.org
*
* Copyright (c) 2011 PHP Secure login system -- http://www.php-developer.org
* AUTHORS:
* Codex-m
* Refer to license.txt to how codes from other projects are attributed.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//require user configuration and database connection parameters
require('config.php');
//pre-define validation parameters
$usernamenotempty = TRUE;
$usernamevalidate = TRUE;
$usernamenotduplicate = TRUE;
$passwordnotempty = TRUE;
$passwordmatch = TRUE;
$passwordvalidate = TRUE;
$captchavalidation = TRUE;
//Check if user submitted the desired password and username
if ((isset($_POST["desired_password"])) && (isset($_POST["desired_username"])) && (isset($_POST["desired_password1"]))) {
//Username and Password has been submitted by the user
//Receive and validate the submitted information
//sanitize user inputs
function sanitize($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = mysql_real_escape_string($data);
return $data;
}
$desired_username = sanitize($_POST["desired_username"]);
$desired_password = sanitize($_POST["desired_password"]);
$desired_password1 = sanitize($_POST["desired_password1"]);
//validate username
if (empty($desired_username)) {
$usernamenotempty = FALSE;
} else {
$usernamenotempty = TRUE;
}
if ((!(ctype_alnum($desired_username))) || ((strlen($desired_username)) > 11)) {
$usernamevalidate = FALSE;
} else {
$usernamevalidate = TRUE;
}
if (!($fetch = mysql_fetch_array(mysql_query("SELECT `username` FROM `authentication` WHERE `username`='$desired_username'")))) {
//no records for this user in the MySQL database
$usernamenotduplicate = TRUE;
} else {
$usernamenotduplicate = FALSE;
}
//validate password
if (empty($desired_password)) {
$passwordnotempty = FALSE;
} else {
$passwordnotempty = TRUE;
}
if ((!(ctype_alnum($desired_password))) || ((strlen($desired_password)) < 8)) {
$passwordvalidate = FALSE;
} else {
$passwordvalidate = TRUE;
}
if ($desired_password == $desired_password1) {
$passwordmatch = TRUE;
} else {
$passwordmatch = FALSE;
}
//Validate recaptcha
require_once('recaptchalib.php');
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
//captcha validation fails
$captchavalidation = FALSE;
} else {
$captchavalidation = TRUE;
}
if (($usernamenotempty == TRUE)
&& ($usernamevalidate == TRUE)
&& ($usernamenotduplicate == TRUE)
&& ($passwordnotempty == TRUE)
&& ($passwordmatch == TRUE)
&& ($passwordvalidate == TRUE)
&& ($captchavalidation == TRUE)) {
//The username, password and recaptcha validation succeeds.
//Hash the password
//This is very important for security reasons because once the password has been compromised,
//The attacker cannot still get the plain text password equivalent without brute force.
function HashPassword($input) {
//Credits: http://crackstation.net/hashing-security.html
//This is secure hashing the consist of strong hash algorithm sha 256 and using highly random salt
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$hash = hash("sha256", $salt . $input);
$final = $salt . $hash;
return $final;
}
$hashedpassword = HashPassword($desired_password);
//Insert username and the hashed password to MySQL database
mysql_query("INSERT INTO `authentication` (`username`, `password`) VALUES ('$desired_username', '$hashedpassword')") or die(mysql_error());
//Send notification to webmaster
$message = "New member has just registered: $desired_username";
mail($email, $subject, $message, $from);
//redirect to login page
header(sprintf("Location: %s", $loginpage_url));
exit;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Register as a Valid User</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
.invalid {
border: 1px solid #000000;
background: #FF00FF;
}
</style>
</head>
<body >
<h2>User registration Form</h2>
<br />
Hi! This private website is restricted to public access. If you want to see the content, please register below. You will be redirected to a login page after successful registration.
<br /><br />
<!-- Start of registration form -->
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
Username: (<i>alphanumeric less than 12 characters</i>) <input type="text" class="<?php if (($usernamenotempty == FALSE) || ($usernamevalidate == FALSE) || ($usernamenotduplicate == FALSE))
echo "invalid"; ?>" id="desired_username" name="desired_username"><br /><br />
Password: (<i>alphanumeric greater than 8 characters</i>) <input name="desired_password" type="password" class="<?php if (($passwordnotempty == FALSE) || ($passwordmatch == FALSE) || ($passwordvalidate == FALSE))
echo "invalid"; ?>" id="desired_password" ><br /><br />
Type the password again: <input name="desired_password1" type="password" class="<?php if (($passwordnotempty == FALSE) || ($passwordmatch == FALSE) || ($passwordvalidate == FALSE))
echo "invalid"; ?>" id="desired_password1" ><br />
<br /><br />
Type the captcha below:
<br /> <br />
<?php
require_once('recaptchalib.php');
echo recaptcha_get_html($publickey);
?>
<br /><br />
<input type="submit" value="Register">
<br /><br />
<a href="index.php">Back to Homepage</a><br />
<!-- Display validation errors -->
<?php if ($captchavalidation == FALSE)
echo '<font color="red">Please enter correct captcha</font>'; ?><br />
<?php if ($usernamenotempty == FALSE)
echo '<font color="red">You have entered an empty username.</font>'; ?><br />
<?php if ($usernamevalidate == FALSE)
echo '<font color="red">Your username should be alphanumeric and less than 12 characters.</font>'; ?><br />
<?php if ($usernamenotduplicate == FALSE)
echo '<font color="red">Please choose another username, your username is already used.</font>'; ?><br />
<?php if ($passwordnotempty == FALSE)
echo '<font color="red">Your password is empty.</font>'; ?><br />
<?php if ($passwordmatch == FALSE)
echo '<font color="red">Your password does not match.</font>'; ?><br />
<?php if ($passwordvalidate == FALSE)
echo '<font color="red">Your password should be alphanumeric and greater 8 characters.</font>'; ?><br />
<?php if ($captchavalidation == FALSE)
echo '<font color="red">Your captcha is invalid.</font>'; ?><br />
</form>
<!-- End of registration form -->
</body>
</html>
@rolarblaze
Copy link

great job!
Please is this code base still valid in PHP7?

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment