The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Apache::AuthDBI - Authentication and Authorization via Perl's DBI

SYNOPSIS

# Configuration in httpd.conf or startup.pl:

PerlModule Apache::AuthDBI

# Authentication and Authorization in .htaccess:

AuthName DBI
AuthType Basic

PerlAuthenHandler Apache::AuthDBI::authen
PerlAuthzHandler  Apache::AuthDBI::authz

PerlSetVar Auth_DBI_data_source   dbi:driver:dsn
PerlSetVar Auth_DBI_username      db_username
PerlSetVar Auth_DBI_password      db_password
#DBI->connect($data_source, $username, $password)

PerlSetVar Auth_DBI_pwd_table     users
PerlSetVar Auth_DBI_uid_field     username
PerlSetVar Auth_DBI_pwd_field     password
# authentication: SELECT pwd_field FROM pwd_table WHERE uid_field=$user
PerlSetVar Auth_DBI_grp_field     groupname
# authorization: SELECT grp_field FROM pwd_table WHERE uid_field=$user

require valid-user
require user   user_1  user_2 ...
require group group_1 group_2 ...

The AuthType is limited to Basic. You may use one or more valid require lines. For a single require line with the requirement 'valid-user' or with the requirements 'user user_1 user_2 ...' it is sufficient to use only the authentication handler.

DESCRIPTION

This module allows authentication and authorization against a database using Perl's DBI. For supported DBI drivers see:

http://dbi.perl.org/

Authentication:

For the given username the password is looked up in the cache. If the cache is not configured or if the user is not found in the cache, or if the given password does not match the cached password, it is requested from the database.

If the username does not exist and the authoritative directive is set to 'on', the request is rejected. If the authoritative directive is set to 'off', the control is passed on to next module in line.

If the password from the database for the given username is empty and the nopasswd directive is set to 'off', the request is rejected. If the nopasswd directive is set to 'on', any password is accepted.

Finally the passwords (multiple passwords per userid are allowed) are retrieved from the database. The result is put into the environment variable REMOTE_PASSWORDS. Then it is compared to the password given. If the encrypted directive is set to 'on', the given password is encrypted using perl's crypt() function before comparison. If the encrypted directive is set to 'off' the plain-text passwords are compared.

If this comparison fails the request is rejected, otherwise the request is accepted and the password is put into the environment variable REMOTE_PASSWORD.

The SQL-select used for retrieving the passwords is as follows:

SELECT pwd_field FROM pwd_table WHERE uid_field = user

If a pwd_whereclause exists, it is appended to the SQL-select.

This module supports in addition a simple kind of logging mechanism. Whenever the handler is called and a log_string is configured, the log_field will be updated with the log_string. As log_string - depending upon the database - macros like TODAY can be used.

The SQL-select used for the logging mechanism is as follows:

UPDATE pwd_table SET log_field = log_string WHERE uid_field = user

Authorization:

When the authorization handler is called, the authentication has already been done. This means, that the given username/password has been validated.

The handler analyzes and processes the requirements line by line. The request is accepted if the first requirement is fulfilled.

In case of 'valid-user' the request is accepted.

In case of one or more user-names, they are compared with the given user-name until the first match.

In case of one or more group-names, all groups of the given username are looked up in the cache. If the cache is not configured or if the user is not found in the cache, or if the requested group does not match the cached group, the groups are requested from the database. A comma separated list of all these groups is put into the environment variable REMOTE_GROUPS. Then these groups are compared with the required groups until the first match.

If there is no match and the authoritative directive is set to 'on' the request is rejected.

In case the authorization succeeds, the environment variable REMOTE_GROUP is set to the group name, which can be used by user scripts without accessing the database again.

The SQL-select used for retrieving the groups is as follows (depending upon the existence of a grp_table):

SELECT grp_field FROM pwd_table WHERE uid_field = user
SELECT grp_field FROM grp_table WHERE uid_field = user

This way the group-information can either be held in the main users table, or in an extra table, if there is an m:n relationship between users and groups. From all selected groups a comma-separated list is build, which is compared with the required groups. If you don't like normalized group records you can put such a comma-separated list of groups (no spaces) into the grp_field instead of single groups.

If a grp_whereclause exists, it is appended to the SQL-select.

Cache:

The module maintains an optional cash for all passwords/groups. See the method setCacheTime(n) on how to enable the cache. Every server has it's own cache. Optionally the cache can be put into a shared memory segment, so that it can be shared among all servers. See the CONFIGURATION section on how to enable the usage of shared memory.

In order to prevent the cache from growing indefinitely a CleanupHandler can be initialized, which skips through the cache and deletes all outdated entries. This can be done once per request after sending the response, hence without slowing down response time to the client. The minimum time between two successive runs of the CleanupHandler is configurable (see the CONFIGURATION section). The default is 0, which runs the CleanupHandler after every request.

LIST OF TOKENS

  • Auth_DBI_data_source (Authentication and Authorization)

    The data_source value has the syntax 'dbi:driver:dsn'. This parameter is passed to the database driver for processing during connect. The data_source parameter (as well as the username and the password parameters) may be a tilde ('~') separated list of several data_sources. All of these triples will be used until a successful connect is made. This way several backup-servers can be configured. if you want to use the environment variable DBI_DSN instead of a data_source, do not specify this parameter at all.

  • Auth_DBI_username (Authentication and Authorization)

    The username argument is passed to the database driver for processing during connect. This parameter may be a tilde ('~') separated list. See the data_source parameter above for the usage of a list.

  • Auth_DBI_password (Authentication and Authorization)

    The password argument is passed to the database driver for processing during connect. This parameter may be a tilde ('~') separated list. See the data_source parameter above for the usage of a list.

  • Auth_DBI_pwd_table (Authentication and Authorization)

    Contains at least the fields with the username and the (possibly encrypted) password. The username should be unique.

  • Auth_DBI_uid_field (Authentication and Authorization)

    Field name containing the username in the Auth_DBI_pwd_table.

  • Auth_DBI_pwd_field (Authentication only)

    Field name containing the password in the Auth_DBI_pwd_table.

  • Auth_DBI_pwd_whereclause (Authentication only)

    Use this option for specifying more constraints to the SQL-select.

  • Auth_DBI_grp_table (Authorization only)

    Contains at least the fields with the username and the groupname.

  • Auth_DBI_grp_field (Authorization only)

    Field-name containing the groupname in the Auth_DBI_grp_table.

  • Auth_DBI_grp_whereclause (Authorization only)

    Use this option for specifying more constraints to the SQL-select.

  • Auth_DBI_log_field (Authentication only)

    Field name containing the log string in the Auth_DBI_pwd_table.

  • Auth_DBI_log_string (Authentication only)

    String to update the Auth_DBI_log_field in the Auth_DBI_pwd_table. Depending upon the database this can be a macro like 'TODAY'.

  • Auth_DBI_authoritative < on / off> (Authentication and Authorization)

    Default is 'on'. When set 'on', there is no fall-through to other authentication methods if the authentication check fails. When this directive is set to 'off', control is passed on to any other authentication modules. Be sure you know what you are doing when you decide to switch it off.

  • Auth_DBI_nopasswd < on / off > (Authentication only)

    Default is 'off'. When set 'on' the password comparison is skipped if the password retrieved from the database is empty, i.e. allow any password. This is 'off' by default to ensure that an empty Auth_DBI_pwd_field does not allow people to log in with a random password. Be sure you know what you are doing when you decide to switch it on.

  • Auth_DBI_encrypted < on / off > (Authentication only)

    Default is 'on'. When set to 'on', the password retrieved from the database is assumed to be crypted. Hence the incoming password will be crypted before comparison. When this directive is set to 'off', the comparison is done directly with the plain-text entered password.

  • Auth_DBI_encryption_method < sha1hex/md5hex/crypt > (Authentication only)

    Default is blank. When set to one or more encryption method, the password retrieved from the database is assumed to be crypted. Hence the incoming password will be crypted before comparison. The method supports falling back so specifying 'sha1hex/md5hex' would allow for a site that is upgrading to sha1 to support both methods. sha1 is the recommended method.

  • Auth_DBI_encryption_salt < password / userid > (Authentication only)

    When crypting the given password AuthDBI uses per default the password selected from the database as salt. Setting this parameter to 'userid', the module uses the userid as salt.

  • Auth_DBI_uidcasesensitive < on / off > (Authentication and Authorization)

    Default is 'on'. When set 'off', the entered userid is converted to lower case. Also the userid in the password select-statement is converted to lower case.

  • Auth_DBI_pwdcasesensitive < on / off > (Authentication only)

    Default is 'on'. When set 'off', the entered password is converted to lower case.

  • Auth_DBI_placeholder < on / off > (Authentication and Authorization)

    Default is 'off'. When set 'on', the select statement is prepared using a placeholder for the username. This may result in improved performance for databases supporting this method.

CONFIGURATION

The module should be loaded upon startup of the Apache daemon. Add the following line to your httpd.conf:

PerlModule Apache::AuthDBI

A common usage is to load the module in a startup file via the PerlRequire directive. See eg/startup.pl for an example.

There are three configurations which are server-specific and which can be done in a startup file:

Apache::AuthDBI->setCacheTime(0);

This configures the lifetime in seconds for the entries in the cache. Default is 0, which turns off the cache. When set to any value n > 0, the passwords/groups of all users will be cached for at least n seconds. After finishing the request, a special handler skips through the cache and deletes all outdated entries (entries, which are older than the CacheTime).

Apache::AuthDBI->setCleanupTime(-1);

This configures the minimum time in seconds between two successive runs of the CleanupHandler, which deletes all outdated entries from the cache. The default is -1, which disables the CleanupHandler. Setting the interval to 0 runs the CleanupHandler after every request. For a heavily loaded server this should be set to a value, which reflects a compromise between scanning a large cache possibly containing many outdated entries and between running many times the CleanupHandler on a cache containing only few entries.

Apache::AuthDBI->setProjID(1);

This configures the project ID used to create a semaphore ID for shared memory. It can be set to any integer 1 to 255 or it will default to a value of 1.

NOTE: This must be set prior to calling initIPC.

If you are running multiple instances of Apache on the same server\ (for example, Apache1 and Apache2), you may not want (or be able) to use shared memory between them. In this case, use a different project ID on each server.

If you are reading this because you suspect you have a permission issue or a collision with a semaphore, use 'ipcs -s' to list semaphores and look for the Semaphore ID from the apache error log. If found, shutdown Apache (all of them) and use 'ipcrm sem <semaphore key>' to remove the colliding (and hopefully unused) semaphore.

You may also want to remove any orphaned shared memory segments by using 'ipcs -m' and removing the orphans with ipcrm shm <shared memory id>.

Apache::AuthDBI->initIPC(50000);

This enables the usage of shared memory for the cache. Instead of every server maintaining it's own cache, all servers have access to a common cache. This should minimize the database load considerably for sites running many servers. The number indicates the size of the shared memory segment in bytes. This size is fixed, there is no dynamic allocation of more segments. As a rule of thumb multiply the estimated maximum number of simultaneously cached users by 100 to get a rough estimate of the needed size. Values below 500 will be overwritten with the default 50000.

To enable debugging the variable $Apache::AuthDBI::DEBUG must be set. This can either be done in startup.pl or in the user script. Setting the variable to 1, just reports about a cache miss. Setting the variable to 2 enables full debug output.

PREREQUISITES

MOD_PERL 2.0

Apache::DBI version 0.96 and should work under mod_perl 2.0 RC5 and later with httpd 2.0.49 and later.

Apache::DBI versions less than 1.00 are NO longer supported. Additionally, mod_perl versions less then 2.0.0 are NO longer supported.

MOD_PERL 1.0

Note that this module needs mod_perl-1.08 or higher, apache_1.3.0 or higher and that mod_perl needs to be configured with the appropriate call-back hooks:

PERL_AUTHEN=1 PERL_AUTHZ=1 PERL_CLEANUP=1 PERL_STACKED_HANDLERS=1

Apache::DBI v0.94 was the last version before dual mod_perl 2.x support was begun. It still recommened that you use the latest version of Apache::DBI because Apache::DBI versions less than 1.00 are NO longer supported.

SECURITY

In some cases it is more secure not to put the username and the password in the .htaccess file. The following example shows a solution to this problem:

httpd.conf:

<Perl>
my($uid,$pwd) = My::dbi_pwd_fetch();
$Location{'/foo/bar'}->{PerlSetVar} = [
    [ Auth_DBI_username  => $uid ],
    [ Auth_DBI_password  => $pwd ],
];
</Perl>

SEE ALSO

Apache, mod_perl, DBI

AUTHORS

  • Apache::AuthDBI by Edmund Mergl; now maintained and supported by the modperl mailinglist, subscribe by sending mail to modperl-subscribe@perl.apache.org.

  • mod_perl by Doug MacEachern.

  • DBI by Tim Bunce <dbi-users-subscribe@perl.org>

COPYRIGHT

The Apache::AuthDBI module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.