Presentation is loading. Please wait.

Presentation is loading. Please wait.

Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 9: Login Management.

Similar presentations


Presentation on theme: "Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 9: Login Management."— Presentation transcript:

1 Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 9: Login Management

2 Week 9: Password management: login and register Login best practices Apache access controls 2

3 Week 9: Midterm answers 3

4 4 Security: ‘Good guy’ versus ‘bad guys’ Attacks and countermeasures (karsı) Protections ¸ http://foreverkins.blogspot.com

5 5 Security: ¸ http://www.codesecurely.org/Wiki/print.aspx/Security_Code_Reviews/Data_Validation

6 Website security: Validation of data Configuration of Apache/MySQL servers Encryption: SSL for transmission/2-way data Hashing for one-way verification 6

7 Configuring Apache:.htaccess and.htpasswd Combination acts as sentry (nöbetçi) Requires additional password to access content Today: holds general configuration files 7

8 8.htpasswd.htaccess AuthName "Uniform Server - Server Access" AuthType Basic AuthUserFile /htpasswd/www/.htpasswd Require valid-user Configuring Apache: Combined use limits access to resources

9 Security and SSL: Any confidential data must be sent via SSL Including: new account information username/password credit card data transactions/transaction history etc. 9

10 Security and SSL: 10 Application Presentation Session Transport Network Data Link Physical Application Presentation Session Transport Network Data Link Physical Packets SSL goFener

11 Security and SSL: Make a page ‘SSL’ it must be in SSL folder Called via port 443 (https://) 11

12 Security and SSL: Plaintext, cleartext, ciphertext: how transmitted Cipher: algorithm that encode/decode Encrypt: use a cipher Handshake: generation of common key Symmetric: same key encodes/decodes Asymmetric: different keys used; one is secret Certificate: 3 rd party verifies your identity CA: Certificate authority 12

13 Security and SSL: “SSL” provides: transmission technology confidentiality by encrypting message SSL may provide*: client authentication server authentication 13*NOT in the normal configuration

14 Security and SSL: SSL 3.0: Secure Sockets Layer (Netscape, 1996) TLS: Transport Layer Security (IETF, 1999) Not interoperable, but do same thing Both operate primarily at presentation layer (OSI) End-to-end security 14 Application Presentation Session Transport Internetworking Services to users Data transformations; compression, encryption Manages communication flow Defines packet size, error

15 Security and SSL: Encryption strength determined by bits Original bit strengths: 40 and 56; now 128, 256 Bit strength: number of bits in cipher number of keys that can be uniquely made 15 10100101 11001100 10010011 00111100 01101010

16 Security and SSL: Differences: Initial handshake in different OSI stack level TLS can use many ports TLS stronger* encryption 16*differences are very minor

17 Security and SSL: TLS: key exchange: asymmetric message exchange: symmetric 17 Secure? SSL/TLS version number cipher settings session-specific data

18 Security and SSL: System is based in trust Trust backed up by 3 rd party certification (CA) Server certificate holds public/private keys Must be purchased CAs: Verisign TrusTe Microsoft, Netscape, others 18

19 Role Based Access Control: Role determines use: student teacher administrator Can also use X.509 certificate 19

20 Role Based Access Control: A type of access control (RBAC) Our use: a field value in a database customers see only normal site employees can see customer and employee managers see everything 20 Customer1 Employee2 Manager3 Supervisor4 if ($role > 3) view the page else no view

21 21 Password security: Good passwords: sufficiently long mixed characters not repeated Save password to a separate table* Transmit using TLS/SSL Hash the password (after adding salt) before saving

22 22 Password security: Hash: a one-way encrypted digest Salt: long random string of auto-generated stuff added to password before hashing salt is unique for each client (must track) purpose: deal with duplicated entries

23 23 Password security: Uniform Server support for hashing Described in phpInfo

24 24 Password security: Hashing algorithm (sha1) messagesha1160-bit digest40 hex characters (description) 32Uv7YgkiTvLpo6QZvdRmnPiKgdWSDr2

25 25 Password security: Length of hash: 32 characters Test of support: if (CRYPT_SHA1 == 1) “true” Commands used to hash: crypt($pass,[$salt]): md5($pass.$salt): sha1($pass, $salt): check salt for your use

26 26 Password security: Message Digest (md) “the old standby” (rahat) Ronald Rivest (1989) Versions: md2, md4, md5 (1991), md6 (2008) Creates a128-bit (32 hex chars) signature for a file Used to prove integrity of files

27 27 Password security: Secure Hashing Algorithm (sha) NSA (1993) Up to 512 bits Recommended replacement: sha (x) sha1: creates a 40-character digest (160 bit)

28 28 Password security: md5, sha are good at integrity of data 40 seconds* to brute force attack password made of lowercase, uppercase, numbers Block users after multiple errors

29 29 Password security: Salt: use a value that varies (datetime, rand(), etc) Salts don’t protect against brute force, dictionary $password = “me”; $salt = date(“j:m:Y G:i:s”); //$salt = time();//seconds (INT) since UNIX epoch //$salt = rand($min, $max); //rand(1, 32767) $password = sha1($password.$salt) me13072012 23:12:10 → $yhUjThn76%kM me13072012 23:12:11 → $yh#j2h.76%kM

30 30 Password security: Salts deal with: duplicate password entries rainbow tables Knowing the salt won’t help crack password Salt can be stored as cleartext $password = “Ieu2014”; $salt = 4581543; $pass = sha1($password.$salt); $pass = “1$341*.ye784TflMibUHcjdE3S6C4m9n”;

31 31 Password security: Extra security: pepper (value stored in site, not DB) $pepper = “thiswebsite”; $password = “Ieu2014”; $salt = 4581543; $password = sha1($pepper.$password.$salt)

32 32 Password security: Testing a password Tv6&#s!T4re56Vx0Jnmt45 salt value Tv6&#s!T4re56Vx0Jnmt45

33 33 Password security: Security question used if password forgotten usually, choose from list (menu) be careful with your list create table for security questions, answers

34 34 Password security: What makes a good question: can’t be easily guessed don’t change over time memorable (unutulmaz) definitive (kesin) simple characters that are typically used to answer http://goodsecurityquestions.com/examples.htm

35 35 Password security: What was your childhood nickname?* In what city did you meet your spouse/significant other? What is the name of your favorite childhood friend?* What street did you live on in third grade? What is your oldest sibling’s birthday month and year? (e.g., January 1900) What is the middle name of your oldest child?* What is your oldest sibling's middle name? What school did you attend for sixth grade? What was your childhood phone number including area code? (e.g., 000-000-0000) What is your oldest cousin's first and last name? http://goodsecurityquestions.com/examples.htm

36 Captchas: Completely Automated Public Turing Test To Tell Computers and Humans Apart Invented at Carnegie Mellon (2000) Image with a message embedded Humans can read, machines cannot read Block computers pretending (sahte) to be humans Reverse Turing test (separates machines from humans) 36http://www.captcha.net

37 Captchas: Types of captchas: text image: fancy font modest distortions added drop shadows, non-linear audio captchas cognitive captchas Problems with captchas: visual impairments 37

38 Captchas: If captcha used, easier to install Code can be free, or with charge 38 http://www.captcha.net captcha-software.blogspot.com www.captchasoftware.in www.webwiz.co.uk/web-applications/ download.cnet.com/Internet-Captcha/3000-10247_4-10824424.html

39 OpenID: Like a password to your passwords Single Sign-On 39 http://openidexplained.com/

40 40 Login attempt success? count & log attempt security question? true? reset password count & log attempt count = 0 reset = 0 count > 3? block login reset > 3? block question

41 Break

42 Security and SSL: 42 Install SSL: Open UniServer interface Open ‘Apache’, choose ‘General Certificate’

43 Security and SSL: 43 Click ‘Generate’ button Add information as you see fit (not real) Real life: must purchase from CA Click ‘Run Generate’ to create

44 Security and SSL: 44 Turn UniServer off and then on View SSL is now available

45 Security and SSL: 45

46 Security and SSL: 46 Add this site as an exception

47 Security and SSL: 47

48 Security and SSL: 48 Certificate and key untrusted (not purchased)

49 Security and SSL: 49 May be asked to open port 443 firewall 3306 80 443

50 Lab: Login Everything goes in the SSL folder “normal web”: www folder port 80http://localhost “secure web”: ssl folder port 443https://localhost 50

51 Security and SSL: 51 Secured content must be in ‘ssl’ folder (images) Path to folder: https://localhost/

52 Lab: login 52 Collection of technologies to serve a purpose

53 Shopping Interface (session) Login: Site map 53 Manager (session) Employee (session) SSL Index

54 Shopping Interface (session) Login: Site map 54 Manager (session) Employee (session) SSL password Login passwordreset passworderror passwordfail passwordsuccess Index Register registersuccess loginerror loginfail Login

55 Lab: Login Update link: Create: https://localhost/tatli/register.php Sign in: https://localhost/tatli/login.php

56 56 Login attempt success? count & log attempt security question? true? reset password count & log attempt count = 0 reset = 0 count > 3? block login reset > 3? block question create user account Lab: login

57 SQL is a programming language SQL is declarative; not procedural solves problems with queries 57 x = 3; y = 5; z = x*y; Input Generate SELECT query output Use output as data for QUERY

58 Create necessary pages: register & login Build necessary tables to support system Transmit using SSL Require ‘strong’ username, password (validate) Password is hashed and salted Login errors on BOTH username & password Use Ajax to test usernames 58 Lab: login

59 Use challenge question & answer Update & forget password page (s) Use roles De-activate after 3 unsuccessful attempts: login security question 59 Lab: login

60 Not use: NTLM, Shibboleth, or OpenID?? CAPTCHA? Login history (in, out, time) Track IP addresses Forget username? (if not email address) Track password usage history Mailed resets for password (later) 60 Lab: login

61 61 tblregister tblpassword tblquestion tblloginerror* tblchallengeerror* tblogin * How do I know? I did requirements analysis *not used in this assignment

62 Lab: login tblregister: 62 Field Name:Type:SizeKeyIncrement registeridINT8PrimaryAuto usernameVARCHAR20Unique emailVARCHAR255Unique roleINT2 firstnameVARCHAR40 lastnameVARCHAR40 enrolldateDATE19 challengeidINT2Foreign challengeanswerVARCHAR75 loginerrorINT1 challengeerrorINT1

63 63

64 Lab: login tblpassword: 64 Field Name:Type:SizeKeyIncrement passwordidINT5PrimaryAuto registeridINT8Foreign passwordVARCHAR40 saltINT15

65 65

66 Lab: login tblquestion: 66 Field Name:Type:SizeKeyIncrement challengeidINT2PrimaryAuto questionVARCHAR125

67 67

68 Lab: Full-contact login Connect the foreign keys: 68 Table:Field:KeyTo:Relationship tblregisterchallengeidForeigntblchallenge. challengeid 1:1 tblpasswordregisteridForeigntblregister. registerid 1:1 tblloginerrorregisteridForeigntblregister. registerid 1:n

69 69

70 70 Lab: Full-contact login Table data for ‘tblregister’: RegisteridUsernamePasswordemailrolefirstnamelastnameenrolldatechallengeidchallengeanswer 1Denizlicottontravel@ttnet.com1MehmetOKTAY2010-04-031Shorty 2Vansnowizmirgood@ttnet.com1AsliOZER2012-11-082Istanbul 3Ankaracoldgobeskitas@turktelecom.com1DenizSIMSEKOGLU2006-01-253Bahar 4Trabzonwetfenerbache@ttnet.com1ElifKARS2013-07-25433 sokak 5Antalyasunnymevlana@superonline.net1CengizKEKLIK2011-04-2951987-11-04 6Bodrumhotdenizyuz@ttnet.com1SamsunTOPRAK2009-12-181Mutlu 7Bondurmarainygunestanrim@superonline.net1VeraDANE2008-02-142Izmir 8Muglacloudysuperusta@ttnet.com1HarunSIVACI2009-06-123Ali 9Ayvalikwindyfutbolforever@superonline.net1CemalYILMAZ2010-04-134Anyplace 10Edirnedryfolkdancer@trabzon.net1ZeynepCANBAZ2012-07-1551982-08-13 11YOU

71 Quiz: 1. Threats to e-commerce sites come from: A. Not validating input and output B. Social engineering C. DoS D. Virus/Trojan horse E. keyloggers 71

72 Quiz: 2. Typical input attacks include: A. Virus/Trojan horse B. DoS attacks C. Injections and overflow attacks D. Social engineering attachs E. Black hats, white hats, gray hats 72

73 Quiz: 3. Output attacks include: A. Buffer overflow attacks B. SQL injection attacks C. Cross-site scripting attacks D. Cross-site request forgery 73

74 Quiz: 4. The main defense against attacks to web sites is: A. SSL B. TLS C. Validation of data D. mysqli_real_escape_string() 74

75 Quiz: 5. SSL and TLS are both primarily: A. Application layer protocols B. Presentation layer protocols C. Session layer protocols D. Transport layer protocols 75

76 Quiz: 6. The port number for SSL is: A. 80 B. 1443 C. 21 D. 443 76

77 Quiz: 7. A hash is different from encryption because: A. Encryption can’t be decrypted B. Hashes can’t be de-hashed C. Encrypted data can’t be sent by a network D. Hashed data can’t be sent by a network E. Encrypted data can’t be stored in a table F. Hashed data can’t be stored in a table 77

78 Quiz: 8. Salt added to hashes: A. Makes them easier to create B. Makes them harder to break C. Makes them faster to calculate D. Makes them 2-way 78

79 Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 9: Login Management

80 Lab: login Queries needed for this assignment: SELECT queries allow reading of data INSERT, UPDATE, and DELETE are writing 80 SELECT field1, field2 FROM table WHERE a=b AND c=d; INSERT into table (col_1, col_2) VALUES(‘a’, ‘b’); UPDATE table SET name=‘Steve’ WHERE id=42; DELETE FROM table WHERE Username=‘Roadkill’;

81 Shopping Interface (session) Login: Site map 81 Ye olde site mappe Manager (session) Employee (session) SSL password Login passwordreset passworderror passwordfail passwordsuccess Index Register registersuccess loginerror loginfail Login

82 Lab: login All files this week are in SSL folder Copy ‘tatli’ from Week 9 folder into SSL folder ‘HTML’ part is built; you add ‘PHP’ part Update ‘dbconnect’ 82 <?php //dbconnect.php $host = “localhost”; $database = “tatlidb”; $username = "username”; $password = “password”; $con = mysqli_connect($host, $username, $password, $database) or trigger_error(mysqli_error(),E_USER_ERROR); ?>

83 Lab: login Fix the register page by: insert into tblregister, tblpassword onsubmit connect to DB for security question write query in ajaxconnect 83

84 Lab: Full-contact login 84 Register.php uses Ajax Ajax: opens; uses, doesn’t display, a data source

85 Lab: login 85 //ajax code on register.php function usernameCheck(username) { if (username) { if (username.length > 5 && username.length < 13) { ajaxRequest = new XMLHttpRequest(); ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4 && ajaxRequest.status==200) { document.getElementById("message").innerHTML = ajaxRequest.responseText; if (ajaxRequest.responseText == "Error") { alert ("This username has already been used.\nPlease select another username"); setTimeout("document.getElementById('username').select()", 2); setTimeout("document.getElementById('username').focus()", 2); } if (ajaxRequest.responseText != "") { document.getElementById("message").innerHTML = ajaxRequest.responseText; } queryString = "?username=" + username; url = "ajaxconnect.php" +queryString; ajaxRequest.open("GET", url, true); ajaxRequest.send(); } else { alert ("The username must be between 6 and 12 characters in length"); setTimeout("document.getElementById('username').select()", 2); setTimeout("document.getElementById('username').focus()", 2); }

86 Get ‘username’ from form SELECT any records with ‘username’ as username Return result (okay, not okay) Lab: login 86 /* ajaxconnect.php. This file is the Ajax connector used with ‘register.php’. It determines if the username has already been used (helps control for duplicate usernames */ <?php $username = mysqli_real_escape_string($con, $_GET['username']); $query = "SELECT registerid from tblregister WHERE username='$username'"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $row = mysqli_num_rows($recordset); if ($row != 0) { $msg = "Error"; } if ($row == 0) { $msg = ""; } echo $msg; mysqli_free_result($recordset); mysqli_close($con); ?> Web page Data

87 Lab: Full-contact login register.phptblregister 87 Field Name:Type:SizeKeyIncrement registeridINT8PrimaryAuto usernameVARCHAR20Unique emailVARCHAR255Unique roleINT2 firstnameVARCHAR40 lastnameVARCHAR40 enrolldateDATE19 challengeidINT2Foreign challengeanswerVARCHAR75 loginerrorINT1 challengeerrorINT1

88 Lab: Full-contact login Add the security questions to ‘tblquestion’ 88 Field Name:Type:SizeKeyIncrement challengeidINT2PrimaryAuto questionVARCHAR125

89 Lab: Full-contact login Add the security questions to ‘tblquestion’ Allows us to add questions easily in the future 89 INSERT INTO `tatlidb`.`tblquestion` (`challengeid`, `question`) VALUES ('1', 'What was your childhood nickname?'), ('2', 'In what city did you meet your spouse?'), ('3', 'What is the name of your best childhood friend?'), ('4', 'What street did you live on in 3rd grade?'), ('5', 'What is your oldest sibling\'s birthday?'), ('6', 'What is the middle name of your oldest child?'), ('7', 'What is your oldest sibling\'s middle name?');

90 Lab: Full-contact login Loop through ‘tblquestion’ to populate menu Must load with the page (NOT ‘onsubmit’) Select questions from tblquestion 90

91 Lab: login 91 //HTML version: **Please choose a security question** Germany //label is ‘Germany’ (shown text), value is ‘1’ France Turkey //PHP version: **Please choose a security question** ">

92 Get the question from the question table Create a recordset Play the recordset in the Option items Lab: login 92 //above in register.php NOT inside an ‘isset’ <?php $query = "SELECT challengeid, question from tblquestion"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $count = mysqli_num_rows($recordset); ?> //around menu row "> ?> //at bottom of file <?php mysqli_free_result($recordset); mysqli_close($con); ?>

93 Lab: Full-contact login 93 Finished menu:

94 Lab: login Process used: collect data using form INSERT data into tblregister SELECT registerid for username Calculate salt value using PHP Encrypt/hash password INSERT registerid, password, salt into tblpassword goto success page 94

95 Lab: Full-contact login Write the insert query to add new customer Insert ‘onsubmit’ (reload same page) 95 INSERT into tblregister (username, role, firstname, lastname, enrolldate, challengeid, challengeanswer) VALUES (‘$_POST[‘username’]’, …); Field Name:Type:SizeKeyIncrement registeridINT8PrimaryAuto usernameVARCHAR20Unique roleINT2 firstnameVARCHAR40 lastnameVARCHAR40 enrolldateDATE19 challengeidINT2Foreign challengeanswerVARCHAR75 loginerrorINT1 challengeerrorINT1

96 96 //top of page <?php $query = "SELECT challengeid, question from tblquestion"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $count = mysqli_num_rows($recordset); ?> //top of page <?php if(isset($_POST['Submit'])) { $role = 1; //customer $date = date("Y-m-d"); $username = mysqli_real_escape_string($con, $_POST['username']); $password = mysqli_real_escape_string($con, $_POST['password']); $firstname = mysqli_real_escape_string($con, $_POST['firstname']); $lastname = mysqli_real_escape_string($con, $_POST['lastname']); $question = mysqli_real_escape_string($con, $_POST['securityquestion']); $answer = mysqli_real_escape_string($con, $_POST['securityanswer']); mysqli_query($con,"INSERT INTO tblregister (username, role, firstname, lastname, enrolldate, challengeid, challengeanswer) VALUES ('$username', '$role', '$firstname', '$lastname', '$date', '$question', '$answer')"); } ?> //top of page <?php if(isset($_POST['Submit'])) { $role = 1; //customer $date = date("Y-m-d"); $username = mysqli_real_escape_string($con, $_POST['username']); $email = mysqli_real_escape_string($con, $_POST['email']); $password = mysqli_real_escape_string($con, $_POST['password']); $firstname = mysqli_real_escape_string($con, $_POST['firstname']); $lastname = mysqli_real_escape_string($con, $_POST['lastname']); $question = mysqli_real_escape_string($con, $_POST['securityquestion']); $answer = mysqli_real_escape_string($con, $_POST['securityanswer']); $salt = time(); $password = sha1($password.$salt); mysqli_query($con,"INSERT INTO tblregister (username, email, role, firstname, lastname, enrolldate, challengeid, challengeanswer) VALUES ('$username', '$email', '$role', '$firstname', '$lastname', '$date', '$question', '$answer')"); } ?>

97 Lab: login Put data into tblpassword user enters data, get registerid, role, errors If errors > 2 go to loginfail (block account) to loginfail 97

98 SELECT registerid from tblregister Calculate time(); (salt value) Hash password+salt INSERT registerid, password, salt 98 //top of page <?php if(isset($_POST['Submit'])) { $username = mysqli_real_escape_string($con, $_POST['username']); $password = mysqli_real_escape_string($con, $_POST['password']); $query = "SELECT registerid FROM tblregister WHERE username='$username'"; $set = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $RS = mysqli_fetch_assoc($set); $registerid = $RS['registerid']; $salt = time(); $password = sha1($password.$salt); mysqli_query($con,"INSERT INTO tblpassword (registerid, password, salt) VALUES ('$registerid', '$password', '$salt')"); header("location: registersuccess.php"); } ?> <?php mysqli_free_result($RS); mysqli_free_result($recordset); mysqli_close($con); ?>

99 Lab: login Register goes to ‘registersuccess’: information page with re-directs 99 register.phpregistersuccess.phpindex.php

100 Break

101 Shopping Interface (session) Lab: login 101 Ye olde site mappe Manager (session) Employee (session) SSL password Login passwordreset passworderror passwordfail passwordsuccess Register registersuccess Index loginerror loginfail Login

102 Capture username, password off form Get salt, role, registerid, loginerror for username from tblregister If errors > 2 go to loginfail (block account) Get password, salt for registerid from tblpassword Use password+salt to calculate hash of password entry Compare calculated hash to stored hash If same, update loginerror, challengeerror to 0 Go to identified page by role If different, add 1 to loginerror Update tblregister with new loginerror Repeat login attempt Clear results 102

103 Capture username, password off form Get salt, role, registerid, loginerror for username from tblregister If errors > 2 go to loginfail (block account) 103 //login.php <?php if(isset($_POST['Submit'])) { $username = mysqli_real_escape_string($con, $_POST['username']); $password = mysqli_real_escape_string($con, $_POST['password']); $userquery = "SELECT role, registerid, loginerror FROM tblregister WHERE username='$username'"; $userRS = mysqli_query($con, $userquery) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $rowUser = mysqli_fetch_assoc($userRS); $registerid = $rowUser['registerid']; $role = $rowUser['role']; $loginerror = $rowUser['loginerror']; if($loginerror>2) header("location: loginfail.php"); } ?>

104 Get password, salt for registerid from tblpassword Use password+salt to calculate hash of password entry Compare calculated hash to stored hash If same, update loginerror, challengeerror to 0 Go to identified page by role 104 //login.php else { $passquery = "SELECT password, salt FROM tblpassword WHERE registerid='$registerid'"; $passRS = mysqli_query($con, $passquery) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $rowPass = mysqli_fetch_assoc($passRS); $salt = $rowPass['salt']; $shapassword = $rowPass['password']; $password = sha1($password.$salt); if($password==$shapassword) { mysqli_query($con,"UPDATE tblregister SET loginerror='0' WHERE registerid='$registerid'"); if($role==1) header("location: http://localhost/tatli/index.php"); if($role==2) header("location: http://localhost/tatli/index.php"); if($role==3) header("location: http://localhost/tatli/index.php"); if($role==4) header("location: http://localhost/tatli/index.php"); } ?>

105 If different, add 1 to loginerror Update tblregister with new loginerror Send to loginerror page Clear results 105 //login.php else { $loginerror++; mysqli_query($con,"UPDATE tblregister SET loginerror='$loginerror' WHERE registerid='$registerid'"); header("location: loginerror.php"); } mysqli_free_result($rowUser); mysqli_free_result($rowPass); mysqli_close($con);?>

106 Lab: login Two error routes off of ‘login’: loginerror (try again) loginfail (blocked) Re-direct can use: PHP JavaScript 106

107 Lab: login Loginerror.php 107 meta charset="utf-8"> Unsuccessful Login Attempt setTimeout("window.location='login.php'", 3000); The username and password you entered are not found in our database. Please try again.

108 Lab: login Loginerror.php 108 meta charset="utf-8"> Account Blocked setTimeout("window.location=‘password.php'", 3000); There have been too many unsuccessful attempts to use account. As a security precaution, this account is blocked until you reset your password. You will be directed there now.

109 Shopping Interface (session) Lab: login 109 Ye olde site mappe Manager (session) Employee (session) SSL password Login passwordreset passworderror passwordfail passwordsuccess Register registersuccess Index loginerror loginfail Login

110 Lab: login Determine username (enter or pass) Get registerid, challengeerror, challengeanswer by username from tblregister If challengeerror > 2, go to passwordfail If challengeanswer == entered value Update challengeerror = 0 by registerid Go to passwordreset.php Add 1 to challengeerror Update challengeerror on tblregister Go to passworderror 110

111 Determine username (enter or pass) Get registerid, challengeerror, challengeanswer by username from tblregister 111 //password.php <?php $username = $_GET['username']; if(isset($_POST['Submit'])) { $answer = mysqli_real_escape_string($con, $_POST['answer']); $username = $_POST['username']; $query = "SELECT registerid, challengeerror, challengeanswer from tblregister WHERE username='$username'"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $row = mysqli_fetch_assoc($recordset); $count = mysqli_num_rows($recordset); $registerid = $row['registerid']; $challengeerror = $row['challengeerror']; $challengeanswer = $row['challengeanswer'];

112 //ajaxquestion.php if($challengeerror > 2) { header("location: passwordfail.php"); } else { if($challengeanswer == $answer) { mysqli_query($con,"UPDATE tblregister SET challengeerror=0, loginerror=0 WHERE registerid='$registerid'"); header("location: passwordreset.php?registerid=$registerid"); } else { $challengeerror++; mysqli_query($con,"UPDATE tblregister SET challengeerror='$challengeerror' WHERE registerid='$registerid'"); header("location: passworderror.php?username=$username"); } mysqli_free_result($row); mysqli_close($con); ?> 112

113 //ajax code on password.php calls to ajaxquestion.php (provided) if (!error && username.length > 5 && username.length < 13) { ajaxRequest = new XMLHttpRequest(); ajaxRequest.onreadystatechange = function() { if(ajaxRequest.readyState == 4 && ajaxRequest.status==200) { if (ajaxRequest.responseText == "Error") { alert ("There is a problem with your security question. \nPlease contact customer assistance"); } if (ajaxRequest.responseText != "Error") { document.getElementById("response").innerHTML = ajaxRequest.responseText; } queryString = "?username=" + username; url = "ajaxquestion.php" +queryString; ajaxRequest.open("GET", url, true); ajaxRequest.send(); } 113

114 //ajaxquestion.php <?php /* Ajax backend for 'password.php' */ $username = mysqli_real_escape_string($con, $_GET['username']); $query = "SELECT registerid, challengeid, challengeerror from tblregister WHERE username='$username'"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $count = mysqli_num_rows($recordset); $row = mysqli_fetch_assoc($recordset); $challengeid = $row['challengeid']; $challengeerror = $row['challengeerror']; if($challengeerror > 2) { header("location: securityfail.php"); } if ($count== 0) { $msg = "Error"; } if ($count == 1) { $query = "SELECT question from tblquestion WHERE challengeid='$challengeid'"; $set = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $questionrow = mysqli_fetch_assoc($set); $msg = $questionrow['question']; } echo $msg; mysqli_free_result($recordset); mysqli_close($con); ?> 114

115 Lab: login 3 outcomes to ‘password’ (ask security question) error fail pass question and reset password 115

116 Lab: login ‘error’ and ‘fail’ similar to login: 116

117 Lab: login Loginerror.php 117 <?php $username = $_GET['username']; ?> Mistake with Security Question "> Sorry, but your security answer doesn't match our records. Please try again. You'll be re-directed back to the security question page in 3 seconds. setTimeout("window.location='password.php?username="+ document.getElementById('username').value+"'", 3000);

118 Lab: login passworderror.php 118 futbolfan futbolfan

119 Lab: login Loginerror.php 119 Failed to Answer Security Question You have not been able to answer the security question in 3 attempts. To help keep your account secure, it has been de-activated. (Email resets later on in the course).

120 Lab: login 3 outcome: pass question and reset password Username added by PHP script 120 futbolfan

121 121 futbolfan Given registerid; convert to username <?php $registerid = mysqli_real_escape_string($con, $_GET['registerid']); $query = "SELECT username from tblregister WHERE registerid='$registerid'"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $set = mysqli_fetch_assoc($recordset); $username = $set['username']; ?>

122 //passwordreset.php <?php $registerid = mysqli_real_escape_string($con, $_GET['registerid']); $query = "SELECT username from tblregister WHERE registerid='$registerid'"; $recordset = mysqli_query($con, $query) or die("A MySQL query error has occurred. Error number: ". mysql_errno()." ". mysql_error()); $set = mysqli_fetch_assoc($recordset); $username = $set['username']; ?> 122 futbolfan

123 Determine if passwords match If match: Calculate new salt, new hashed password update tblpassword Reset loginerror, passworderror //passwordreset.php <?php if(isset($_POST['Submit'])) { $password = mysqli_real_escape_string($con, $_POST['password']); $password2 = mysqli_real_escape_string($con, $_POST['password2']); if($password != $password2) { header("location: passwordreset.php"); } else { $salt = time(); $password = sha1($password.$salt); mysqli_query($con,"UPDATE tblpassword SET salt='$salt', password='$password' WHERE registerid='$registerid'"); mysqli_query($con,"UPDATE tblregister SET loginerror=0, challengeerror=0 WHERE registerid='$registerid'"); header("location: passwordsuccess.php"); } mysqli_free_result($set); mysqli_close($con); ?> 123 futbolfan

124 Password Successfully Changed! setTimeout("window.location='login.php'", 3000); <img src="images/logo.png" width="390" height="90" alt="Company Logo" title="Company Logo"> Your password has been updated and you can login at any time with it. 124

125 125 Lab: login Back to login

126 Assignment: 126 Complete login system including 10 customers

127 Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 9: Login Management


Download ppt "Server Side Scripting Languages SE 362: Copyright © Steven W. Johnson October 1, 2012 Week 9: Login Management."

Similar presentations


Ads by Google