Adding authentication to your website

Custom Authentication

Apache is a very extensible system – so flexible that you don't even have to use it for http. By writing Apache modules, you can extend Apache. Modules can be written in C, like the modules discussed in this article, but the C language is time consuming and cumbersome for web admins who aren't experienced software developers.

Thanks to modules such as mod_perl and mod_python, you can build your own custom Apache modules in more agile languages.

Apache provides great flexibility when dealing with access to content, but one thing it doesn't take into account is the time of day. As an example of how to customize Apache authentication, assume your company has a first and second shift and you want to ensure that first-shift employees can only access pages or applications during their work hours. First, enable mod_perl with:

LoadModule perl_module modules/mod_perl.so

mod_perl lets you override a particular phase of the Apache life cycle by writing a Perl module. In this case, the module compares the username and password but also makes sure the employee is authorized to work at the current time (Listing 4). Also, reject everyone who tries to work on Saturdays and Sundays.

Listing 4

No Weekend Work!

01 package ByShiftAuth;
02
03  use strict;
04  use warnings;
05
06  use Apache2::Access ();
07  use Apache2::RequestUtil ();
08  use Apache2::Const -compile => qw(OK HTTP_UNAUTHORIZED AUTH_REQUIRED);
09
10  use DBI;
11  use Digest::MD5 qw( md5_hex );
12
13  sub handler {
14      my $r = shift;
15
16      # See if this is the initial request or not, if it isn't
17      # they are already authentication and we just need to reset
18      # the username
19      if( !$r->is_initial_req ) {
20
21          if( defined $r->prev ) {
22              $r->user( $r->prev->user );
23          }
24
25          return Apache2::Const::OK;
26
27      }
28
29      # Check to see if it's a weekend
30      my $day_of_week = (localtime(time))[6];
31      if( $day_of_week == 0 or $day_of_week == 6 ) {
32          return Apache2::Const::HTTP_UNAUTHORIZED;
33      }
34
35      # Get the username and password
36      my ($rc, $password) = $r->get_basic_auth_pw();
37      my $user = $r->user;
38
39      unless ( $user and $password ) {
40          $r->note_basic_auth_failure;
41          return( Apache2::Const::AUTH_REQUIRED );
42      }
43
44      # Now let's connect to our database and compare things in
45      # our database we're going to store passwords as MD5 digests
46      my $dbhv = DBI->connect('dbi:Pg:dbname=admin', 'apache', 'secret')
47          or die "Cannot connect to database: $!";
48
49      my $sth = $dbh->prepare( qq{
50          SELECT password FROM users WHERE user = ? AND
51             current_time BETWEEN shift_begin AND shift_end });
52
53      $sth->execute( $user );
54      my $db_password = $sth->fetchrow;
55      $sth->finish;
56
57      # Make sure we found a password for this user, if we don't
58      # it means they don't exist or their shift isn't in progress
59      if( !$db_password ) {
60          $r->note_basic_auth_failure;
61          return( Apache2::Const::AUTH_REQUIRED );
62      }
63
64      # Check to make sure the passwords match
65      if( md5_hex( $password ) ne $db_passwd ) {
66          $r->note_basic_auth_failure;
67          return( Apache2::Const::AUTH_REQUIRED );
68      }
69
70      return( Apache2::Const::OK );
71
72 }

This code can be placed anywhere in Perl's @INC path in a file named ByShiftAuth.pm. If you want to put it in another location, add the following to your Apache configuration:

<Perl>
use lib qw( /path/to/directory );
</Perl>

After loading in the necessary mod_perl modules, DBI, and the MD5 libraries, Listing 4 defines the handler.

First, check to see whether this is the initial request or some sort of internal redirect. If it's not the initial request, the system has already authenticated this request and can just pass along the information.

Next, check to make sure the current day isn't a weekend, and if it is, simply reject everyone. The script then obtains the username and password from the user.

If both a username and password aren't available, the script bails out and tells the browser to re-prompt with the AUTH_REQUIRED return value.

Next, the script must connect to the database and look for the user's password. The query assumes the start and end times of the user's shift are in the users table.

If the user doesn't exist or is attempting to login outside of their shift hours, this query won't return any data. In production, you would probably want to tell the user that the reason they can't log in is that it isn't their shift so that they don't keep retrying.

Finally, compare the MD5 digest of the password with the password retrieved from the database.

If the test fails, the user is prompted again. If all goes well, return the OK constant, which tells Apache that the user is authenticated.

Now that you see how the code works, the next step is to tell Apache to use it, which you can do by overriding the authentication phase with the custom code:

<Location /admin>
AuthType Basic
AuthName "Admin Pages"
PerlAuthenHandler ByShiftAuth
Require valid-user
</Location>

Conclusion

These short examples show some of the ways you can protect your web pages using more advanced Apache configurations. For more options, I encourage you to check the Apache website (http://httpd.apache.org).

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • One-Time Passwords on the Web

    Add security to your website with a one-time password system.

  • Radius and 802.1X

    The Radius protocol is typically used to authenticate users in dial-up scenarios. But Radius is also useful in LAN environments: in combination with 802.1X, Radius forces users to authenticate at a low level before the switch opens up a port.

  • XSA Attack

    A new form of phishing attack deposits an HTML tag on the vulnerable service to trap users into authenticating.

  • Linux with Active Directory

    Microsoft's Active Directory system provides centralized user management and single sign-on. If you're ready for a few manual steps, Linux can leverage this potential.

  • Ajaxterm

    Public Internet access is often protected by restrictive firewalls, and you have no chance of running SSH. However, HTTPS over port 443 is typically permitted. Ajaxterm lets mobile users login to their home servers.

comments powered by Disqus

Direct Download

Read full article as PDF:

038-041_webauth.pdf (392.63 kB)

News

njobs Europe
What:
Where:
Country:
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia