Apache2-AuthCookieDBI
view release on metacpan or search on metacpan
lib/Apache2/AuthCookieDBI.pm view on Meta::CPAN
use constant EMPTY_STRING => q{};
use constant HEX_STRING_REGEX => qr/ \A [0-9a-fA-F]+ \z /mx;
use constant HYPHEN_REGEX => qr/ - /mx;
use constant PERCENT_ENCODED_STRING_REGEX => qr/ \A [a-zA-Z0-9_\%]+ \z /mx;
use constant THIRTY_TWO_CHARACTER_HEX_STRING_REGEX =>
qr/ \A [0-9a-fA-F]{32} \z /mx;
use constant TRUE => 1;
use constant WHITESPACE_REGEX => qr/ \s+ /mx;
use constant LOG_TYPE_AUTH => 'authentication';
use constant LOG_TYPE_AUTHZ => 'authorization';
use constant LOG_TYPE_SYSTEM => 'system';
use constant LOG_TYPE_TIMEOUT => 'timeout';
#===============================================================================
# P E R L D O C
#===============================================================================
=head1 NAME
Apache2::AuthCookieDBI - An AuthCookie module backed by a DBI database.
=head1 COMPATIBILITY
Starting with version 2.03, this module is in the Apache2::* namespace,
L<Apache2::AuthCookieDBI>. For F<mod_perl 1.x> versions,
there is still L<Apache::AuthCookieDBI>.
=head1 SYNOPSIS
# In httpd.conf or .htaccess
# Optional: Initiate a persistent database connection using Apache::DBI.
# See: http://search.cpan.org/dist/Apache-DBI/
# If you choose to use Apache::DBI then the following directive must come
# before all other modules using DBI - just uncomment the next line:
#PerlModule Apache::DBI
PerlModule Apache2::AuthCookieDBI
PerlSetVar WhatEverPath /
PerlSetVar WhatEverLoginScript /login.pl
# Optional, to share tickets between servers.
PerlSetVar WhatEverDomain .domain.com
# These must be set
PerlSetVar WhatEverDBI_DSN "DBI:mysql:database=test"
PerlSetVar WhatEverDBI_SecretKey "489e5eaad8b3208f9ad8792ef4afca73598ae666b0206a9c92ac877e73ce835c"
# These are optional, the module sets sensible defaults.
PerlSetVar WhatEverDBI_User "nobody"
PerlSetVar WhatEverDBI_Password "password"
PerlSetVar WhatEverDBI_UsersTable "users"
PerlSetVar WhatEverDBI_UserField "user"
PerlSetVar WhatEverDBI_PasswordField "password"
PerlSetVar WhatEverDBI_UserActiveField "" # Default is skip this feature
PerlSetVar WhatEverDBI_CryptType "none"
PerlSetVar WhatEverDBI_GroupsTable "groups"
PerlSetVar WhatEverDBI_GroupField "grp"
PerlSetVar WhatEverDBI_GroupUserField "user"
PerlSetVar WhatEverDBI_EncryptionType "none"
PerlSetVar WhatEverDBI_SessionLifetime 00-24-00-00
# Protected by AuthCookieDBI.
<Directory /www/domain.com/authcookiedbi>
AuthType Apache2::AuthCookieDBI
AuthName WhatEver
PerlAuthenHandler Apache2::AuthCookieDBI->authenticate
PerlAuthzHandler Apache2::AuthCookieDBI->authorize
require valid-user
# or you can require users:
require user jacob
# You can optionally require groups.
require group system
</Directory>
# Login location.
<Files LOGIN>
AuthType Apache2::AuthCookieDBI
AuthName WhatEver
SetHandler perl-script
PerlHandler Apache2::AuthCookieDBI->login
# If the directopry you are protecting is the DocumentRoot directory
# then uncomment the following directive:
#Satisfy any
</Files>
=head1 DESCRIPTION
This module is an authentication handler that uses the basic mechanism provided
by Apache2::AuthCookie with a DBI database for ticket-based protection. It
is based on two tokens being provided, a username and password, which can
be any strings (there are no illegal characters for either). The username is
used to set the remote user as if Basic Authentication was used.
On an attempt to access a protected location without a valid cookie being
provided, the module prints an HTML login form (produced by a CGI or any
other handler; this can be a static file if you want to always send people
to the same entry page when they log in). This login form has fields for
username and password. On submitting it, the username and password are looked
up in the DBI database. The supplied password is checked against the password
in the database; the password in the database can be plaintext, or a crypt()
or md5_hex() checksum of the password. If this succeeds, the user is issued
a ticket. This ticket contains the username, an issue time, an expire time,
and an MD5 checksum of those and a secret key for the server. It can
optionally be encrypted before returning it to the client in the cookie;
encryption is only useful for preventing the client from seeing the expire
time. If you wish to protect passwords in transport, use an SSL-encrypted
connection. The ticket is given in a cookie that the browser stores.
After a login the user is redirected to the location they originally wished
to view (or to a fixed page if the login "script" was really a static file).
On this access and any subsequent attempt to access a protected document, the
browser returns the ticket to the server. The server unencrypts it if
encrypted tickets are enabled, then extracts the username, issue time, expire
time and checksum. A new checksum is calculated of the username, issue time,
expire time and the secret key again; if it agrees with the checksum that
the client supplied, we know that the data has not been tampered with. We
next check that the expire time has not passed. If not, the ticket is still
good, so we set the username.
lib/Apache2/AuthCookieDBI.pm view on Meta::CPAN
my $secret_key = shift;
my $auth_name = shift;
my $dbi_encryption_type = lc shift;
my $message;
if ( !defined $dbi_encryption_type ) {
Carp::confess('$dbi_encryption_type must be defined.');
}
if ( $dbi_encryption_type eq 'none' ) {
return $session_key;
}
my $cipher = $class->_get_cipher_for_type( $dbi_encryption_type, $auth_name,
$secret_key );
my $encrypted_key = $cipher->encrypt_hex($session_key);
return $encrypted_key;
}
#-------------------------------------------------------------------------------
# _log_not_set -- Log that a particular authentication variable was not set.
sub _log_not_set {
my ( $class, $r, $variable ) = @_;
my $auth_name = $r->auth_name;
my $message = "${class}\t$variable not set for auth realm $auth_name";
$class->logger( $r, Apache2::Const::LOG_ERR, $message, undef,
LOG_TYPE_SYSTEM, $r->uri );
return;
}
#-------------------------------------------------------------------------------
# _dir_config_var -- Get a particular authentication variable.
sub _dir_config_var {
my ( $class, $r, $variable ) = @_;
my $auth_name = $r->auth_name;
return $r->dir_config("$auth_name$variable");
}
#-------------------------------------------------------------------------------
# _dbi_config_vars -- Gets the config variables from the dir_config and logs
# errors if required fields were not set, returns undef if any of the fields
# had errors or a hash of the values if they were all OK. Takes a request
# object.
my %CONFIG_DEFAULT = (
DBI_DSN => undef,
DBI_SecretKey => undef,
DBI_User => undef,
DBI_Password => undef,
DBI_UsersTable => 'users',
DBI_UserField => 'user',
DBI_PasswordField => 'password',
DBI_UserActiveField => EMPTY_STRING, # Default is don't use this feature
DBI_CryptType => 'none',
DBI_GroupsTable => 'groups',
DBI_GroupField => 'grp',
DBI_GroupUserField => 'user',
DBI_EncryptionType => 'none',
DBI_SessionLifetime => '00-24-00-00',
DBI_sessionmodule => 'none',
);
sub _dbi_config_vars {
my ( $class, $r ) = @_;
my %c; # config variables hash
foreach my $variable ( keys %CONFIG_DEFAULT ) {
my $value_from_config = $class->_dir_config_var( $r, $variable );
$c{$variable}
= defined $value_from_config
? $value_from_config
: $CONFIG_DEFAULT{$variable};
if ( !defined $c{$variable} ) {
$class->_log_not_set( $r, $variable );
}
}
# If we used encryption we need to pull in Crypt::CBC.
if ( $c{'DBI_EncryptionType'} ne 'none' ) {
require Crypt::CBC;
}
# Compile module for password encryption, if needed.
if ( $c{'DBI_CryptType'} =~ /^sha/ ) {
require Digest::SHA;
}
return %c;
}
=head1 APACHE CONFIGURATION DIRECTIVES
All configuration directives for this module are passed in PerlSetVars. These
PerlSetVars must begin with the AuthName that you are describing, so if your
AuthName is PrivateBankingSystem they will look like:
PerlSetVar PrivateBankingSystemDBI_DSN "DBI:mysql:database=banking"
See also L<Apache2::Authcookie> for the directives required for any kind
of Apache2::AuthCookie-based authentication system.
In the following descriptions, replace "WhatEver" with your particular
AuthName. The available configuration directives are as follows:
=over 4
=item C<WhatEverDBI_DSN>
Specifies the DSN for DBI for the database you wish to connect to retrieve
user information. This is required and has no default value.
=item C<WhateverDBI_SecretKey>
Specifies the secret key for this auth scheme. This should be a long
random string. This should be secret; either make the httpd.conf file
only readable by root, or put the PerlSetVar in a file only readable by
root and include it.
This is required and has no default value. (NOTE: In AuthCookieDBI versions
lib/Apache2/AuthCookieDBI.pm view on Meta::CPAN
=item C<WhatEverDBI_PasswordField>
The field in the above table that has the password. This is not
required and defaults to 'password'.
=item C<WhatEverDBI_UserActiveField>
The field in the users' table that has a value indicating if the users' account
is "active". This is optional and the default is to not use this field.
If used then users will fail authentication if the value in this field
is not a Perlish true value, so NULL, 0, and the empty string are all false
values. The I<user_is_active> class method exposes this setting (and may be
overidden in a subclass.)
=item C<WhatEverDBI_CryptType>
What kind of hashing is used on the password field in the database. This can
be 'none', 'crypt', 'md5', 'sha256', 'sha384', or 'sha512'.
C<md5> will use Digest::MD5::md5hex() and C<sha...> will use
Digest::SHA::sha{n}_hex().
This is not required and defaults to 'none'.
=item C<WhatEverDBI_GroupsTable>
The table that has the user / group information. This is not required and
defaults to 'groups'.
=item C<WhatEverDBI_GroupField>
The field in the above table that has the group name. This is not required
and defaults to 'grp' (to prevent conflicts with the SQL reserved word 'group').
=item C<WhatEverDBI_GroupUserField>
The field in the above table that has the user name. This is not required
and defaults to 'user'.
=item C<WhatEverDBI_EncryptionType>
What kind of encryption to use to prevent the user from looking at the fields
in the ticket we give them. This is almost completely useless, so don't
switch it on unless you really know you need it. It does not provide any
protection of the password in transport; use SSL for that. It can be 'none',
'des', 'idea', 'blowfish', or 'blowfish_pp'.
This is not required and defaults to 'none'.
=item C<WhatEverDBI_SessionLifetime>
How long tickets are good for after being issued. Note that presently
Apache2::AuthCookie does not set a client-side expire time, which means that
most clients will only keep the cookie until the user quits the browser.
However, if you wish to force people to log in again sooner than that, set
this value. This can be 'forever' or a life time specified as:
DD-hh-mm-ss -- Days, hours, minute and seconds to live.
This is not required and defaults to '00-24-00-00' or 24 hours.
=item C<WhatEverDBI_SessionModule>
Which Apache2::Session module to use for persistent sessions.
For example, a value could be "Apache2::Session::MySQL". The DSN will
be the same as used for authentication. The session created will be
stored in $r->pnotes( WhatEver ).
If you use this, you should put:
PerlModule Apache2::Session::MySQL
(or whatever the name of your session module is) in your httpd.conf file,
so it is loaded.
If you are using this directive, you can timeout a session on the server side
by deleting the user's session. Authentication will then fail for them.
This is not required and defaults to none, meaning no session objects will
be created.
=back
=cut
#-------------------------------------------------------------------------------
# _now_year_month_day_hour_minute_second -- Return a string with the time in
# this order separated by dashes.
sub _now_year_month_day_hour_minute_second {
return sprintf '%04d-%02d-%02d-%02d-%02d-%02d', Today_and_Now;
}
sub _check_password {
my ( $class, $password, $crypted_password, $crypt_type ) = @_;
return
if not $crypted_password
; # https://rt.cpan.org/Public/Bug/Display.html?id=62470
my %password_checker = (
'none' => sub { return $password eq $crypted_password; },
'crypt' => sub {
return crypt( $password, $crypted_password ) eq $crypted_password;
},
'md5' => sub { return md5_hex($password) eq $crypted_password; },
'sha256' => sub {
return Digest::SHA::sha256_hex($password) eq $crypted_password;
},
'sha384' => sub {
return Digest::SHA::sha384_hex($password) eq $crypted_password;
},
'sha512' => sub {
return Digest::SHA::sha512_hex($password) eq $crypted_password;
},
);
return $password_checker{$crypt_type}->();
}
#-------------------------------------------------------------------------------
# _percent_encode -- Percent-encode (like URI encoding) any non-alphanumberics
( run in 0.583 second using v1.01-cache-2.11-cpan-ceb78f64989 )