Solved

Site Access and Session ID

Posted on 2016-07-26
7
30 Views
Last Modified: 2016-07-28
Hi Guys'

I'm building a little intranet for my business and I'm trying to customise a session_id login system which I've poached from an online tutorial course I'm doing. I'm seeing a few issues that I'd like to understand in more detail with your help please.

The current index and login pages are located below I know it's a lot of information but I'm told you'd prefer more detail than less and I cant see anything overly confidential or risky about the code. (Feel free to shoot that plane down!) Ps... the "Signup" section of the index.php code is purposely commented out whilst I focus on what happens once a user has logged in (i.e me) and has access to what I call 'inventory.php' this is simple page that will display stock levels and allows the users to view and add new products.

My problem is that I was expecting that the code would prevent anyone who hasn't signed up to the database to be unable to access the pages behind index.php, however, what I'm seeing is that whether or not you've signed up you can bi-pass the index.php (i.e the login process completely) and call the inventory.php without any issues - if you know the url.

Infact if you were given the specific path anyone can bi-pass the need to login completely and call the sub-url's and enter data in my database system ... as you can imagine not ideal.

Please help?

<?php include("login.php"); ?>

<!DOCTYPE html>
<html lang="en">
<head>
			<meta charset="utf-8">
			<meta http-equiv="X-UA-Compatible" content="IE=edge">
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<title>TCH Login</title>

			<!-- Bootstrap -->
			<link href="css/bootstrap.min.css" rel="stylesheet">

			<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media
			queries -->
			<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
			<!--[if lt IE 9]>
			<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></
			script>
			<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/
			respond.min.js"></script>
			<![endif]-->
			
<style>
	.navbar-brand {
			font-size:1.6em;
			}

	#topContainer {
			background-image:url("");
			height:600px;
			width:100%;
			background-size:cover;
			}
			
	#topRow {
			margin-top:100px;
			text-align:center;
			}
			
	#topRow h1 {
			font-size:300%;
			}
			
	#emailSignup {
			margin-top:50px;
			}
			
	.bold {
			font-weight:bold;
			}
			
	.marginTop {
			margin-top:30px;
			}
			
	.center {
			text-align:center;
			}
			
	.title {
			margin-top:100px;
			font-size:300%;
			}

	#footer {
			background-color:#B0D1FB;
			padding-top:70px;
			width:100%;
			}
			
	.marginBottom {
			margin-bottom:30px;
			}
			
	.appstoreImage {
			width:250px;
			}
</style>

</head>
	
	<body data-spy="scroll" data-target=".navbar-collapse">
		
	<div class="navbar navbar-default navbar-fixed-top">
	
	<!-- Start of first container -->		
	<div class="container">
			
		<div class="navbar-header">
			
			<button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
			
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			
			</button>

				<a class="navbar-brand">TheChemicalHut.org</a>
			
		</div>
		
			
		<div class="collapse navbar-collapse">
			
		
		<!-- Bootstrap for email + password login in nav-bar -->	
		<form class="navbar-form navbar-right" method="post">
			
			<div class="form-group">
			
				<input type="email" name="loginemail" placeholder="Email" class="form-control" value="<?php echo addslashes($_POST['loginemail']); ?>"/>
			
			</div>
			
			<div class="form-group">
			
				<input type="password" name="loginpassword" placeholder="Password" class="form-control" value="<?php echo addslashes($_POST['loginpassword']); ?>"/>

			</div>

			<input type="submit" name="submit" value="Log In" class="btn btn-success" >
		
		</form>
		
	</div>
	
	</div>
	
	</div>
	
	<!--Start of second container for code section: My Awesome App
	<div class="container contentContainer" id="topContainer">

		<div class="row">

				<div class="col-md-6 col-md-offset-3" id="topRow">

					<h1 class="marginTop">Inventory Manager</h1>

					<p class="lead">Please enter your login details above.</p>
					
			<?php
			
				if ($error) {
			
					echo '<div class="alert alert-danger">'.addslashes($error).'</div>';
			
					}
			
				if ($message) {
			
					echo '<div class="alert alert-success">'.addslashes($message).'</div>';
			
					}
			
			
				?>
			
			<p class="bold marginTop">If you don't have an access please speak to you line manager.</p>
					
			
			<form class="marginTop" method="post">
		
					<div class="form-group">

						<label for="email">Email Address</label>
		
						<input type="email" name="email" class="form-control" placeholder="Enter your Email" value="<?php echo addslashes($_POST['email']); ?>"/>
						
					</div>
					
					<div class="form-group">

						<label for="password">Password</label>
		
						<input type="password" name="password" class="form-control" placeholder="Enter your Password" value="<?php echo addslashes($_POST['password']); ?>" />
						
					</div>


					<input type="submit" name="submit" value="Sign Up" class="btn btn-success btn-lg marginTop" />
	
			</form>
            End of second container for code section: My Awesome App-->
	
	</div>
	
	</div>

	</div>
	


		<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
		<!-- Include all compiled plugins (below), or include individual files as needed -->
		<script src="js/bootstrap.min.js"></script>
		
		<script> 
		
		$(".contentContainer").css("min-height",$(window).height());
		
		</script>

</body>
</html>


	

Open in new window


<?php
	
	session_start();
	
	if ($_GET["logout"]==1 AND $_SESSION['id']) { session_destroy();
	
		$message="You have been logged out, have a nice day!";
	
	};
	
	include("connection.php");			
			
	if ($_POST['submit']=="Sign Up") {
	
		/* The following lines are actioned once the $_POST['submit'] command is actioned and
		checks firstly for an empty email address i.e "!" user has not posted an email
		this then triggers the $error.=function ... the DOT after the $error
		is needed when multiple error lines are to be posted.*/
		
		if (!$_POST['email']) $error.="<br />Please enter your email";
			else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) $error.="<br />Please enter a valid email address";
			
		if (!$_POST['password']) $error.="<br />Please enter your password";
			else {
			
			if	(strlen($_POST['password'])<8) $error.="<br />Please enter a password with at least 8 characters";
			if	(!preg_match('`[A-Z]`', $_POST['password'])) $error.="<br />Please include at least 1 capital letter in your password";
			
			}
			
		if ($error) $error = "There were error(s) in your signup details".$error;
		
		else {
		
			
			/* The "mysqli_real_escape_string" is critical to prevent an sql injection hack, by 
			escaping all of the characters that could cause the mysql to think a statement
			has ended and allow access to the Database i.e "]); SELECT * FROM `users` */
			
			$query= "SELECT * FROM `users` WHERE email ='".mysqli_real_escape_string($link, $_POST['email'])."'";
			
			/* This returns the result of how many times the email address currently
			exists within the current table named 'users'*/		
			$result = mysqli_query($link, $query);	
			
			/* This total no. of times 0 or otherwise is stored in the variable $result*/	
			$results = mysqli_num_rows($result);
			
			if ($results) $error =  "That email is already registered. Do you want to log in?".$error;
			
			else {
			
				$query = "INSERT INTO `users` (`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."', '".md5(md5($_POST['email']).$_POST['password'])."')";
				
				mysqli_query($link, $query);
				
				echo "Youve been signed up!";
				
				/* This function opens a session that allows access to the system for as long
				as the browser remains open ... must be used in conjunction with the 
				following example code:-
				
				<?php 
				
					start_session();
					
				......
				
				at the beginning of the PHP Code.*/
								
				$_SESSION['id']=mysqli_insert_id($link);
				
				header("Location:inventory.php");
				
            }
		
            }
        
					
		}
		
		if ($_POST['submit']=="Log In") {	
	
		$query = "SELECT * FROM users WHERE email='".mysqli_real_escape_string($link, $_POST['loginemail'])."' AND password='".md5(md5($_POST['loginemail']).$_POST['loginpassword'])."' LIMIT 1";

		$result = mysqli_query($link, $query);
		
		$row = mysqli_fetch_array($result);
		
		if ($row) {
		
			$_SESSION['id']=$row['id'];
			
			header("Location:inventory.php");
							
			} 
            
            else {
			
				$error = "We could not find a user with that email and password. Please try again.".$error;
			
			}
		
		}

?>

Open in new window

0
Comment
Question by:Ridgejp
  • 3
  • 3
7 Comments
 
LVL 52

Expert Comment

by:Scott Fell, EE MVE
ID: 41729946
You have a few issues here such as how you are encrypting passwords, "password='".md5(md5($_POST['loginemail']).$_POST['loginpassword'])."" but that should for another time.

On your config page where you have your database information is where you will have your       session_start(); and that is probably the only place you should have it.

At the very minimum, you need to have an include file that checks for logged in status that you will put at the top of every page.  If the session or token that you looked up in your db is not valid, then send them back to your log in page. If it is valid let the page continue.

On your login processing page, check for either log in or sign up.  If logging in, then test against your db and if found, set your session or token and send them to the next page.  If they are signing up, process the data, then either send them to a new log in page or auto log them in by updating the session or token, then move them to the next page.

See if that logic is being applied to what you are doing.  


Credit to Ray for a good article on the process that he continually updates https://www.experts-exchange.com/articles/2391/PHP-Client-Registration-Login-Logout-and-Easy-Access-Control.html
2
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 41729963
Hat tip to Scott Fell!

There are code examples in the PHP client authentication article that you can copy and use on your own server.

A couple of other articles may be helpful to your understanding of the process.

How HTTP protocols work:
https://www.experts-exchange.com/articles/11271/Understanding-Client-Server-Protocols-and-Web-Applications.html

How PHP sessions work:
https://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html

Good learning resources for anyone new to PHP:
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41731139
And now that I've had a chance to look over the code, here are some other ideas that might be helpful.

Please see this code snippet to learn how to validate an email address.  Of course, simply having a "valid" email address is not the same as having a usable email address.  You can follow the design pattern in this article to learn how to confirm that the email address actually works.
https://www.experts-exchange.com/articles/3939/Registration-and-Email-Confirmation-in-PHP.html
<?php // demo/email_validation.php
/**
 * How to use a utility function to test for a valid email address
 *
 * http://php.net/manual/en/intro.filter.php
 * http://php.net/manual/en/function.checkdnsrr.php
 *
 * See also:
 * https://www.experts-exchange.com/articles/3939/Registration-and-Email-Confirmation-in-PHP.html
 * https://www.experts-exchange.com/articles/9849/Making-CAPTCHA-Friendlier-with-Simple-Number-Tests-or-PHP-Image-Manipulation.html
 */
error_reporting(E_ALL);


function check_valid_email($email, $rout=TRUE)
{
    // OPTIONAL LIST OF BLOCKED DOMAINS
    $bogus = array
    ( '@unknown.com'
    , '@example.com'
    , '@gooseball.org'
    )
    ;

    // IF THE EMAIL STRING IS IMPROPERLY FORMED
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;

    // IF THE DOMAIN IS IN OUR BLOCKED LIST
    foreach ($bogus as $badguy)
    {
        if (stripos($email, $badguy)) return FALSE;
    }

    // FILTER_VAR() DOES NOT TEST TO SEE IF THE DOMAIN IS ROUTABLE
    if ($rout)
    {
        $domain = explode('@', $email);
        if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") ) return TRUE;
        return FALSE;
    }

    return TRUE;
}


// DEMONSTRATE THE FUNCTION IN ACTION
$e = !empty($_GET['e']) ? $_GET['e'] : NULL;
if ($e)
{
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e" . PHP_EOL;
    }
    else
    {
        echo "<br/>BOGUS: $e" . PHP_EOL;
    }
}


// END OF PROCESSING - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<form>
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

For some thoughts on passwords, please see the notes in this article near "An Afterword: About Storing Passwords."  You might want to consider using a pass-phrase instead of using a password.  Here's one idea: https://xkcd.com/936/, and the explanation: https://www.explainxkcd.com/wiki/index.php/936:_Password_Strength.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:Ridgejp
ID: 41731264
Thanks Ray,

I'm still digesting the first two posts - wow you guys are fast! Thanks so much for the help I'm currently building a remote version of your registration system to see how I can integrate the two.

J
0
 

Author Comment

by:Ridgejp
ID: 41731816
Hi Ray,

May I ask the meaning of this ... <a href=\"/\"> ... I understand this is a hypertext reference but after the = is \"/\" what does it mean? Does it look for the index.php page?

In my domain this is what it goes to without my telling it if that makes sense?

Jason.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41732909
In PHP strings, the backslash \ is used to escape the following character, nullifying its contextual meaning and injecting it into the string as a literal.

A link to the home page looks like this in HTML:
<a href="/">home</a>

Open in new window

And to code that in a PHP string, we would need to use something like this:
<?php echo "<a href=\"/\">home</a>";

Open in new window

0
 

Author Comment

by:Ridgejp
ID: 41733190
Thanks - I've managed to get the login form to work - it was previously allowing the same email in the UID to be entered multiple times which I realise was linked the the character length etc ... now that's been extended it works perfectly.

Moving onto the other links now ...
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now