a a 1 php login security: an event driven approach j. scott johnson the fuzzygroup friday, october...
TRANSCRIPT
1
PHP Login Security:An Event Driven Approach
J. Scott JohnsonThe FuzzyGroupFriday, October 25, 20021:45 to 3:15
2
Table of Contents
About Me Types of Web Security Constraints & Design Implementation Conclusion Q & A References / Reading 15 Security Practices Developers Screw Up
3
About J. Scott Johnson
15 year high tech veteran
Entrepreneur
Engineer
Marketer
Former VP of Engineering for a dot com
Been responsible for security in enterprise environments
Currently running a profitable internet consulting firm focused on Open Source technologies
7
Apache AuthenticationNo control over UIPasswords sent in the clearGenerally used to secure binary files or PDFsOnly real way to secure binariesUsed htpasswd utilityPhp classes for it here
8
Application SecurityFull look and feel control
Passwords via SSL if you wantOnly secure if content goes through some kind of dynamic page like PHP or ASP
9
Application Security – 2
Cookie or session basedCan’t protect binary files UNLESS you implement a 2 step approach
Application security Apache security with mod_mysql ??? and
the same user tables
11
Pros and ConsApache Pros Binaries are protected Conceptually simple Works w/ just html
Apache Cons Arcane to setup Not all hosting companies
let you Looks like crap Not scalable w/o apache
module Password sent in clear Really *nix command line
oriented
Application Security Pros Look and feel control Good integration w/
applicationApplication Security Cons Can be broken easily
depending on implementation Often is poorly implemented More coding
12
How to choose?
NO SECURITY IS PERFECT !!!See the last slideUse the right one for the applicationLook at your competitors and try and figure out why they used what they did
15
Constraints
PHP 4.2 require_globals off Magic Quotes Off MySQL 3.23 or later Display Templates via FastTemplate Easy Integration Into Other Sites Minimal # of PHP Scripts No subdirectories Translation Support
16
Features Distinct error messages for
wrong login wrong password
Log all login attempts to a system or “event” log
Remember the user’s desired post login destination
Let the user have forgotten password mailed to them
Let user change their own password
17
Features - 2
Need an admin tool Users
Show users Reset Passwords AND auto mail password to
user Delete Users
Events List events Purge Events
Resources Create, change resources
18
Basic Canonical, Atomic Actions
RegistrationLogin and access grantedLogin and access deniedLost Password with password emailed
19
File Structure
As few files as possible
Easier maintenance Every script is a point of failure
Types of Files
Required Display logic Application
20
File Structure - 2
Required Stuff
zcommondb.php – database settings zcommon.php – functions
Display Stuff
class.FastTemplate.php3 – templating pageheader.tpl – page footer pagefooter.tpl – page header
21
File Structure - 3 Application Stuff
login.php signup login logout change_password forgot_password password_hint login_pb.htm, signup_pb.htm, logout_pb.htm,
changepwd_pb.htm, forgotpwd_pb.htm, passwordhint_pb.htm
admin.php / admin_pb.htm error.php / error_pb.htm
22
Table Structure Tables
fo_users fo_config fo_events fo_resources
Relationships fo_resources has text strings used to display
the page fo_users stores the users login routines pull values from fo_config all login attempts are logged to fo_events
23
Table Structure - Users
Stores user details Who they are, when they signed up,
encrypted password, hints, type field user_id column, not just username, allowing
username changes if you want to support it
24
Table Structure – Users – SQL
create table users ( user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, username CHAR(50) NOT NULL UNIQUE, dateadded DATETIME, type INT(2), password CHAR(32) NOT NULL, email char(75), hintquestion CHAR(50), hintanswer CHAR(50))
25
Notes On Storing PasswordsNever store passwords in clear textNever, Never, NeverEncrypt w/ MD5
$password = md5($password); Returns 32 char hexadecimal hash Means you can never give a user a password You can reset it and give them a new one
Can use Javascript’s md5 to calculate the hash and submit that on login.
Even more secure.
26
Table Structure – Configuration
Allows configuration of the login routines w/o editing the code
Example: Changing cookie timeouts Name, Value Pairs Read as needed
27
Table Structure – Configuration – SQL
CREATE TABLE fo_config ( config_id int(11) NOT NULL auto_increment, name char(25) default NULL, value char(25) default NULL, PRIMARY KEY (config_id)) TYPE=MyISAM;
28
Table Structure – Events
An event log tracks what happens in the system
Mary logged in at 3:00 pm Ted tried to log in 7 times on
Wednesday (this is 7 events) Needed to disable login ability in event of
too many tries Fields
Who, what, type, user data, …
29
Table Structure – Events – SQLCREATE TABLE fo_events ( event_id int(11) NOT NULL auto_increment, dateadded datetime default NULL, epochadded int(10) default NULL, event varchar(25) default NULL, type char(10) default NULL, userdataname1 char(25) default NULL, userdatavalue1 varchar(100) default NULL, userdataname2 char(25) default NULL, userdatavalue2 varchar(100) default NULL, userdataname3 char(25) default NULL, userdatavalue3 varchar(100) default NULL, ipaddress varchar(15) default NULL, url varchar(125) default NULL, browser varchar(50) default NULL, user_id int(6) NOT NULL default '0', PRIMARY KEY (event_id)
) TYPE=MyISAM;
Fields need fine tuning Record probably too big Could move user data to
another table Should add another table
for true system messages (db errors)
Master list of events, types needs to be made for all coders
Should create a daemon to periodically purge event log
30
Table Structure – Resources A resource is a text chunk you want
translated Field label Error message Page title Etc
At load time: Script grabs the text it needs Stores it in an associative array Inserts it via templates
31
Table Structure – Resources – SQL
CREATE TABLE fo_resources ( resource_id int(11) NOT NULL auto_increment, language char(2) default NULL, resourcekey char(60) default NULL, type char(10) default NULL, resource char(254) default NULL, PRIMARY KEY (resource_id), UNIQUE KEY resourcekey (resourcekey,language)) TYPE=MyISAM;
34
Think About ThisDon’t go heavy on username or password restrictionsWhy? Users often NEED to log into different sites A lot of sites When every site has different rules that’s hard
Min 6 char password Min 6 char password 1 # Min 8 char password 6 char to 8 char password Username not more than 25 characters
35
Think - 2
Users have BAD memories More support goes into passwords than
anything else Making it hard wastes your time
36
Think – 3
You need distinct error messages for incorrect username Incorrect password If length of username or password is >
database field size NOTE:
Users can forget even a username !!!
37
Recommendations – Usernames Username:
any lowercase string at all as long as it is unique.
Force it lowercase Example:
scott fuzzygroup sjohnson [email protected]
Why support email addresses as logins? It’s easy for the user The database doesn’t care. Why do you?
38
Recommendations – PasswordsIf it’s not
$$$ oriented Data oriented Reputation oriented
Then Accept anything that is at least 5 characters
with one numberData / Reputation Oriented Email system Blogging tool
Why: Strong enough for most things
39
EXCEPT !!!! Ignore the above if $$$ are involved If so
Minimum 6 char username Password
8 characters Minimum 1 # Preferably non dictionary based word
But Tech support goes up Much better login help and explanation
screens
40
This is a WHAT more than HOW Presentation
Code is Being Revised Presently
It’s to teach security concepts
No Focus on Performance
43
login.php – 2 – Basic Event Loopswitch($action) {
case signup: signup(); die(); case login: login(); die(); case logout: logout(); die(); case changepwd: change_pwd(); die(); case passwordhint: password_hint(); die(); case emailpassword: email_password(); die(); default: $pagebody = current(explode('.', basename($SCRIPT_NAME))) .
"_pb.htm"; display($title, $pagebody); die();}
44
login.php – 3 – Sample Functionfunction email_password() { # get username or email address (user can enter either)
# check events table to see if this has been recently
# check fo_config table to see how often a user can do this
# verify against database that one of these exists
# create and reset a new password for them
# create an email to them w/ a url so their password can be changed
# send mail immediately
# display confirmation page with instructions
# log to event log that this happened}
45
zcommon.php
All common logic
initialize_templates() print_page_header() print_page_footer() display() log_event() check_security()
47
Understanding Templating
Goals Separate application and display Separate designers and developers Common user interface code Separate table stuff from db code
FastTemplate is a simple php only templating tool
Older, less sophisticated than smarty Works very, very well
48
Templating –2 I use a “php” container that wraps around an HTML
chunk or page Other approaches are valid (content from db) Well suited to web applications less so for
sites template.php has:
template_pb.htm pageheader.tpl, pagefooter.tpl
Login.php has login_pb.htm, logout_pb.htm, … (set
conditionally) pageheader.tpl, pagefooter.tpl
49
Templating – 3 – template.php example
#include common fileinclude "zcommon.php";
//Do the security check – grabs values from cookiecheck_security();
//Define the $title variable for the page title$title = "Template Page";
switch($action){ default: $pagebody = current(explode('.', basename($SCRIPT_NAME))) . "_pb.htm"; display($title, $pagebody); die();}
50
Templating – 4: display()function display($title, $pagebody){ //Initialize the templates initialize_templates($pagebody);
//Set up the page header print_page_header($title);
//Set up the body of the page print_page_body();
//Set up the footer of the page print_page_footer();}
Takes 2 params Sets up up the
templates, defining the body template
Passes page title to header routine
Prints body of the page
Prints footer of the page
51
Templating – 5: print_page_header()function print_page_header ($title) { global $tpl; $tpl->assign(PAGE_TITLE, $title); $tpl->parse(FINAL, "pageheader"); $tpl->FastPrint(FINAL);}
Takes 1 param Grabs the template
object Binds the variable
PAGE_TITLE to the value of the param
Parses the page Prints out the page
52
Admin.php
Database backed admin tool Single page with all options available Database queries build up a table array
which is output via templates Doesn’t use standard display routine
Has own display_admin() function Calls print_page_header() Calls print_page_footer()
54
Closing Thoughts
Easy to extend with one or more additional tables
This is something you want to do right Don’t think your user is like you Probably the single biggest problem the
user has is login Doing this part right saves huge tech
support down the road [email protected]
57
References
My article on www.phpbeginner.com Drupal, www.drupal.org, illustrates cross
site, cross password login
59
15 Security Practices We All Screw Up
1. Using Telnet/FTP not SSH/SCP.2. Using an FTP enabled code editor.
(If you have to use ftp then create an ftp only account)
3. Using the same password for login and email.
4. Storing passwords in plain text, not MD5’d format.
5. Relying on obscurity not security. (But obscurity is NOT bad).
60
15 Security Practices - 2
6. Using predictable sequence based URLs http://www.DOMAIN.com/support/monthly_cust_survey.php?survid=-3005
7. Not changing our own passwords regularly8. Weak root passwords9. Not having someone else do a code review10. Assuming that your ISP / Host’s setup is
secure. It’s Probably NOT!
61
15 Security Practices - 3
11. Only ever use phpMyAdmin with SSL12. Not staying up to date / reading security
bulletins13. Not monitoring access_log and error_log14. Poor centralization of all passwords used
by your code – old apps, directories leave passwords around
15. NOT changing every single password immediately when a developer or sysadmin leaves
16. Assuming other people’s code is secure