Digest::Auth / Reference

A Perl library for Hash based authorization.

IMPORTANT:

For the latest version of documentation for Digest::Auth please view the POD documentation that is included with the Perl Module.

Table Of Contents (TOC):

Methods:

  1. new()
  2. Set()
  3. Get()
  4. Initialize()
  5. Validate()
  6. Authorize()
  7. AutoAuth()
  8. TableMake()
  9. UserAdd()
  10. SQL_Die()
  11. DebugAdd()
  12. DebugShow()
  13. CookieGet()
  14. CookieSet()
  15. WriteScript()
  16. JS_Digest()
  17. Keygen()
Parameters:
  1. dbh
  2. debug
  3. debuginfo
  4. cookiename
  5. domain
  6. usecookies
  7. digest
  8. connection
  9. validation
  10. idletime
  11. initcertretry
  12. forgiverate
  13. maxconperip
  14. maxconperuser
  15. maxbadpass
  16. compatmode
  17. locklength
  18. datamapping

SYNOPSIS:

Here is a simplistic script that utilizes the base functions of Digest::Auth

Code:

  1. #!/usr/bin/perl -w
  2. use Digest::Auth;
  3. use CGI;
  4. use DBI;
  5.  
  6. my $dsn = "DBI:mysql:database=mydatabase";
  7. my $user= "myuser";
  8. my $pass= "mypass";
  9. my $mydbh = DBI->connect($dsn,$user,$pass,{'RaiseError' => 1})
  10. my $Auth = Digest::Auth->new(dbh => $mydbh);
  11. my $query = CGI->new();
  12.  
  13. print "Content-Type: text/html\n\n";
  14.  
  15. if($query->param("ACTION") eq "display_login"){
  16. 	# Begin a dialog with User
  17. 	my %iresults = $Auth2->Initialize();
  18.  
  19. }elsif($query->param("ACTION") eq "display_login")
  20. 	# Autheticate User
  21. 	my %vresults = $Auth2->Validate(userid   => "Auth-Digest-Admin",
  22. 			                        cert     => $hash,
  23. 					                password => "Auth-Digest-Password");
  24. }else{
  25.  
  26. 	# Authorize User
  27. 	print ($Auth->Authorize(userid => $cresults{userid},
  28. 							hash   => $cresults{hash}) == 1) ? "Authorized" : "Not Authorized";
  29. }
  30.  

Methods

$Auth->new()

Declaring a new instance of Digest::Auth is easy.

This declares a new instance of Digest::Auth. You can pass any number of Parameters to it in this method however at minimum it is a good practice to pass the database handel Parameter since most of the other functions requrire it to work properly.

Code:

  1. 	# minimalist usage
  2. 	my($Auth)= Digest::Auth->new();
  3.  
  4. 	# OR
  5.  
  6. 	# with the basics
  7. 	my($Auth)= Digest::Auth->new(dbh => $my_dbh);
  8. 		

$Auth->Set()

Digest::Auth keeps tabs on how long sessions are allowed to last. To change or set options you can use the Set() and Get() methods. Set() takes one or multiple arguments as a Hash.

Code:

  1. 	# Set multiple arguements at once or only one.
  2. 	my $reuslt = $Auth->Set(connection => 7200,
  3. 					       validation => 300,
  4. 					       idletime   => 600);
  5.  
  6. 	# you get a result of 1 for each successful change so we can do this.
  7. 	if($result == 3){
  8. 		print "All changes successful!";
  9. 	}else{
  10. 		print "One or more change didn't work.";
  11. 	}
  12. 		

$Auth->Get()

Digest::Auth keeps tabs on how long sessions are allowed to last. To change or set options you can use the Set() and Get() methods. Get() takes single variable arguements.

Code:

  1. 	# Find the value of Auth->{datamapping}{session}{table}
  2. 	my($CurrentValue) = $Auth->Get(datamapping,session,table);
  3.  
  4. 	# Find the value of connection
  5. 	my($CurrentValue) = $Auth->Get(connection);
  6. 		

$Auth->Initialize()

Establish a session with Initialize(). Ideally you would next use WriteScript() next unless compatmode is on to convert the users credentials to secure hashes before submitting the data back for validation.

Code:

  1. 	my %iresults = $Auth->Initialize()
  2. 	print "Session Validated: \n"
  3. 		. "\n Cert: " . 	$iresults{cert}
  4. 		. "\n IP: " . 		$iresults{ip}
  5. 		. "\n Stamp: " . 	$iresults{stamp};
  6. 		

$Auth->Validate()

Use Validate() to authorize the users credentials after a session has been initalized. Depending on the setting of compatmode there is a different argument you need to supply. Arguements are in a hash format. See below:

Code:

  1. 	# Method Options: opts{userid, cert, hash, pass}
  2. 	# userid, cert, (hash || password) required
  3. 	#
  4. 	# 	+ use only hash when self->compatmode = 0
  5. 	#  	+ use only pass when self->compatmode = 1
  6. 	#
  7. 	# The way you would normally call the method
  8. 	my %vresults = $Auth->Validate(userid => $your_userid, cert => $your_cert, hash => $your_hash);
  9.  
  10. 	# Or do it with compat mode on....
  11. 	my $SetReselt = $Auth->Set(compatmode => 1);
  12. 	my %vresults = $Auth->Validate(userid => $your_userid, cert => $your_cert, password => $your_password);
  13.  
  14. 	if( $vresults{result} ){
  15. 		print "Session Validated: \n"
  16. 			. "\n Result: " . $vresults{result}
  17. 			. "\n UserID: " . $vresults{userid}
  18. 			. "\n Hash: "   . $vresults{hash}
  19. 			. "\n Cookie: " . $vresults{cookie};
  20. 	}else{
  21. 		print "Session could not be validated.";
  22. 	}
  23. 		

$Auth->Authorize()

This takes the users credentials and attempts to authorize the validated user. It takes only two arguements, the userid and hash. If usecookies is off the you will need to call this function with arguments as below, if usecookies is on then it can be called without arguments.

Code:

  1. 	# standard way to do it
  2. 	my $results = $Auth->Authorize();
  3.  
  4. 	# OR
  5.  
  6. 	# usecookies is off, do it the hard way.
  7. 	my $results = $Auth->Authorize(userid => $userid, hash => $hash);
  8. 		

$Auth->Avalible()

Method to checks to see if based on the ruleset a session can be established. This is automatically called but can also be called manually. Returns a Hash.

Code:

  1. 	$Auth->Avalible();
  2. 		

$Auth->AttemptAdd()

Logs entry of a bad session attempt.

Code:

  1. 	$Auth->AttemptAdd();
  2. 		

$Auth->LockAdd()

Creates a lockout for a username/ip.

Code:

  1. 	$Auth->LockAdd();
  2. 		

$Auth->LockExpire()

Expires a lock entry.

Code:

  1. 	$Auth->LockExpire();
  2. 		

$Auth->AutoAuth()

This is an experimental automatic authorization method that chooses which functions are required. I would reccomend not using it until the method becomes more stable.

Code:

  1. 	$Auth->AutoAuth();
  2. 		

$Auth->TableMake()

To make your life easier if you don't have an existing table structure you can make all the tables for your database by just calling the TableMake() method.

Code:

  1. 	# Make all the tables
  2. 	TableMake(table => 'all');
  3.  
  4. 	# Just make the session table
  5. 	TableMake(table => 'session');
  6.  
  7. 	# Just make the session table
  8. 	TableMake(table => 'sessionattempts');
  9.  
  10. 	# Just make the session table
  11. 	TableMake(table => 'sessionlocks');
  12.  
  13. 	# Just make the session table
  14. 	TableMake(table => 'user');
  15. 		

$Auth->UserAdd()

This method simplifies adding a new user to the user table. Like all the other methods, they respect the datastructure, which means if you change the datamapping of user to myusers for the table name it will populate the myusers table instead.

Code:

  1. 	$Auth->UserAdd(user => $myusername, password => $mypassword);
  2. 		

$Auth->SQL_Die()

This is a debugging tool that helps neatly print SQL statements out in HTML when module for debug messages.

Code:

  1. 	$Auth->SQL_Die($subroutine_calling_method, $sql_code_executed, $error_code_received);
  2. 		

$Auth->DebugAdd()

A debugging tool that appends data to the debug info.

Code:

  1. 	$Auth->DebugAdd();
  2. 		

$Auth->DebugShow()

A debugging tool that prints out the debug information.

Code:

  1. 	# data = Debug Text, level = l through 3 (1:Error,2:Warning,3:Information);
  2. 	$Auth->DebugShow($data,$level);
  3. 		

$Auth->CookieGet()

Retreives cookie information. Note: when using usecookies you do not have to parse this and put it into the Authorize hash since it is done automatically for you.

Code:

  1. 	# by default if you have no arguments you
  2. 	# get the data from the cookiename pararameter.
  3. 	$Auth->CookieGet();
  4.  
  5. 	# Get the hash data from a cookie other then the default cookie.
  6. 	$Auth->CookieGet(name => $mycookiename);
  7. 		

$Auth->CookieSet()

Set some hash data into the cookie for reuse. Note: when using usecookies you do not have to take the hash results of Authorize() and put it into this method since it is done automatically for you.

Code:

  1. 	# Set some hash data into the cookie for reuse.
  2. 	$Auth->CookieSet(data   => $data,	# This is the only required parameter
  3. 	                 name   => $name,	# If excluded defauls to: cookiename parameter
  4. 					 domain => $domain, # If excluded defauls to: domain parameter
  5. 					 path   => $path,   # If excluded defauls to: "/"
  6. 					 gmt    => $gmt);   # If excluded defauls to: now plus idletime parameter
  7.  
  8. 		

$Auth->WriteScript()

Returns a javascript formatted to print out.

Code:

  1. 	$Auth->WriteScript( $Auth->JS_Digest() );
  2. 		

$Auth->JS_Digest()

Returns Javascript clientside code to produce hashes.

Code:

  1. 	$Auth->JS_Digest(); # Print SHA1 client javascript
  2.  
  3. 	$Auth->JS_Digest(digest => "MD5"); # Print MD5 client javascript
  4. 		

$Auth->Keygen()

The Keygen() method takes two arguements; Key Length (1 to 128) and Complexity (1 to 3). Key length is the length or number of characters you would like to have returned. Complexity is what type of data (1 Upper case letters, 2 uppercase letters and numbers, 3 uppercase letters, lowercase letters and numbers). By design Digest::Auth uses complexity 3. Since we are using by default 10 digit alpha-numeric random keys we are looking at around 1 in 58 to the power of 10 (about 1 in 430,804,206,899,405,800).

Code:

  1. 	$Auth->Keygen(10,3); # Print SHA1 client javascript
  2.  
  3. 	$Auth->Keygen(digest => "MD5"); # Print MD5 client javascript
  4. 		

Parameters

dbh

Passes an open Database handel to the Digest::Auth perl module. If you dont have access to a database server there is a great module called SQLite (http://www.sqlite.org/) that will do the trick, all it requires is downloading the Perl Module and reading a few peices of documentation. This module was designed to originally work with MySQL, however any SQL compliant Database provided there is a DBI/DBD connecter should work.

Code:

  1. 	# connect to a database
  2. 	use DBI;
  3. 	my $dsn = "DBI:mysql:database=mydatabase";
  4. 	my $user= "myuser";
  5. 	my $pass= "mypass";
  6. 	my $mydbh = DBI->connect($dsn,$user,$pass);
  7.  
  8. 	$Auth->Set(dbh => $my_dbh); # pass the database handel
  9. 		

debug

Debug mode spews additional information. Use 1=on or 0=off. Default is off.

Code:

  1. 	$Auth->Set(debug => 1); # turn Debug on
  2. 		

debuginfo

This variable stores Debug information in HTML format when the parameter debug is is active. While you can't set this variable information, you can retrive it easily.

Code:

  1. 	$Auth->Get(debuginfo);
  2. 		

cookiename

Cookie name to use for authorization. This variable dertermines the name of the cookie that maintains user session credentials. In most cases you can leave it as is.

Code:

  1. 	# Cookie name to use for authorization
  2. 	$Auth->Set(cookiename => "MyCookieCert");
  3. 		

domain

Domain name to use for the for cookie, etc. If you are using cookies it is required for them to work properly.

Code:

  1. 	# change to accept everything from .avitar.net
  2. 	$Auth->Set(domain => ".avitar.net");
  3. 		

usecookies

Use cookies to maintain sessions. By default to make programmers lives easier

Code:

  1. 	$Auth->Set(usecookies => 0); # optional, puts the responsibility
  2. 				     # on the programmer to carry session data
  3. 				     # this is the reccomended behavor for higher compatibility
  4. 				     # although it reduces ease of use.
  5.  
  6. 	$Auth->Set(usecookies => 1); # default behaviour
  7. 		

digest

Hash Digest to use. An internal function DigestMake() looks at the digest Parameter and will try to make a new instance via SomeDigest->new(), then it trys to add data via SomeDigest->add(), and will finally try to get a hex digest by calling SomeDigest->hexdigest(). This basically means that if you make an object oreinted digest with these standard functions it will tie in without any problems.

Code:

  1. 	$Auth->Set(domain => "Digest::SHA1");   # This is the default value
  2. 	$Auth->Set(domain => "MD5"); 		    # Use the alternate MD5 hash algorythm
  3. 	$Auth->Set(domain => "My::New::Hash");  # Use an unknown hash type
  4. 		

connection

Maximum total length of time a session is allowed to be. Default is 86400 seconds (24 hours). To disable change to -1. This will expire an active session if it exceedes this amout of time which helps to prevent some bot/macro'ed actions that would keep the user active indefinately. The user should be able to log back in afterwards immediatly. This combined with a Human Readable Identification code will keep people from abusing login times. For help with random text you can use the Keygen() method.

Code:

  1. 	$Auth->Set(connection => 7200); # change to 2 hours
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(connection => -1); # change it to unlimited
  6. 		

validation

Amount of time a user has to enter a username and password and submit it back to the server before their validation cert/key becomes invalid. Default is 600 seconds (10 minutes). To disable change to -1.

Code:

  1. 	$Auth->Set(validation => 300); # change it to 5 mins
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(validation => -1); # change it to unlimited; not reccomended
  6. 		

idletime

Amount of time a user has to idle in the system without their session expiring. Default time is 3600 seconds (60 minutes). To disable change to -1.

Code:

  1. 	$Auth->Set(idletime => 900 ); # change it to 15 minutes
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(idletime => -1); # change it to unlimited; not reccomended
  6. 		

initcertretry

Number of times to retry intitializing a session if the key is a duplicate. Note that a collision in cert keys is extreemly rare. Since we are using by default 10 digit alpha-numeric random keys we are looking at around 1 in 58 to the power of 10 (about 1 in 430,804,206,899,405,800).

Code:

  1. 	# Try 20 times for a unique key before we give up and reject the init.
  2. 	$Auth->Set(initcertretry	=> 20);
  3. 		

forgiverate

This variable controls how long it takes for bad login attempts to expire. This is applies to loggin in on an invalid session hash, username, ip address, etc.

Code:

  1. 	$Auth->Set(forgiverate	=> 86400);
  2. 		

maxconperip

Maximum connections/sessions per IP address. Default is 1. For an unlimited number of sessions per IP address (Highly unreccomended) use the value of -1. If you were working with serveral machines that were NAT'ed behind a router you would want to have one entry per user beihnd that single IP address. Typically this is not a big deal for big businesses that have a huge block of IP's, but when working with small businesses you may want to have this set from 10 to 50 for companies that use one external IP off a T1/DSL/Cable line for 10 to 50 users (after which usually the companies tend to grow and buy a block of IP addresses). Setting this above 1 tends to reduce security by opening a possible man in the middle attack. Then again it may be the lesser of two evils where people would share a single username and password circumventing security in a worse way.

Code:

  1. 	$Auth->Set(maxconperip => 10); # change it to 10
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(maxconperip => -1); # change it to unlimited
  6. 		

maxconperuser

Maximum connections/sessions per user name. Default is 1. For an unlimited number of sessions per IP address (Highly unreccomended) use the value of -1.

Code:

  1. 	$Auth->Set(maxconperuser => 10); # change it to 10
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(maxconperuser => -1); # change it to unlimited
  6. 		

maxbadpass

Maximum number of times a user can enter a bad password before they get banned/locked out. Default is 5. For an unlimited number of sessions per IP address (Highly unreccomended) use the value of -1.

Code:

  1. 	$Auth->Set(maxconperuser => 10); # change it to 10
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(maxconperuser => -1); # change it to unlimited
  6. 		

compatmode

WARNING: THIS REDUCES SECURITY: Change to 1 to enable compatibility for non-javascript browsers. Instead the password will be passed in plaintext to the server with the other credentials which makes a hash out of the credential data and compairs it to the stored user credentials and the session credentials to attempt to validate or authorize the users.

Code:

  1. 	$Auth->Set(compatmode => 1); # Enable compat mode
  2.  
  3. 	# OR
  4.  
  5. 	$Auth->Set(compatmode => 1); # Disable compat mode (default setting)
  6. 		

locklength

This determines how bans/locks for rule violations are handeled. In most cases you can just leave these as is. The ban length goes up with each additional rule violation that occours within the forgiverate. This is one of the trickier items to configure.

The defaults are: 5 min, then 15 min, then 1 hr, then 1 day, then permenent. You can add or remove levels in between each section if you want for the ban length rules. All times are in seconds, and you can use -1 for permenent. The library expects concurrently increasing ban lengths.

Code:

  1. 	# make all bans permenent
  2. 	$Auth->Set(banlength => [-1]);
  3.  
  4. 	# make all bans 1 h
  5. 	$Auth->Set(banlength => [3600]);
  6.  
  7. 	# change bans to 10 min, 2 hrs, 2 hrs, 2 hrs, then permenent.
  8. 	$Auth->Set(banlength => [900,7200,7200,7200,-1]);
  9. 		

datamaping

Optionally use this option if you are using this module with an existing user database. It allows you to modify the column names the module utilizes. The first level of the hash array corrosponds. The changes are immediatly respected.

Code:

  1. 	$Auth->Set(
  2. 	datamaping	=>
  3.        (session => {
  4. 		table		=> "session",
  5. 	        ip		=> "ip",
  6. 	        key		=> "key",
  7. 	        hash		=> "hash",
  8. 	        userid		=> "userid",
  9. 	        firstactive	=> "firstactive",
  10. 	        lastactive	=> "lastactive",
  11.     	},
  12. 		sessionlocks => {
  13.     		table		=> "sessionlocks",
  14. 	        ip		=> "ip",
  15. 	        stamp		=> "stamp",
  16. 	        expires		=> "expires",
  17. 	        expired		=> "expired",
  18. 	        key		=> "key",
  19. 	        hash		=> "hash",
  20. 	        userid		=> "userid",
  21. 	        type		=> "type",
  22.         },
  23. 		sessionattempts => {
  24.  		table		=> "sessionattempts",
  25. 	        ip		=> "ip",
  26. 	        stamp		=> "stamp",
  27. 	        key		=> "key",
  28. 	        hash		=> "hash",
  29. 	        userid		=> "userid",
  30. 		},
  31. 		user => {
  32.                 table		=> "user",
  33.                 userid		=> "userid",
  34.                 password	=> "password",
  35. 		},
  36. 	   )
  37. 	);
  38.  
  39. 		

Donate to Digest::Auth SourceForge.net Logo