Return-Path: Mailing-List: contact apache-docs-help@apache.org; run by ezmlm Delivered-To: mailing list apache-docs@apache.org Received: (qmail 57003 invoked from network); 11 Jan 2001 16:51:23 -0000 Received: from unknown (HELO rhiannon.rcbowen.com) (63.170.130.18) by h31.sny.collab.net with SMTP; 11 Jan 2001 16:51:23 -0000 Received: from rcbowen.com (rbowen@localhost [127.0.0.1]) by rhiannon.rcbowen.com (8.10.2/8.10.2) with ESMTP id f0BGnXT08904 for ; Thu, 11 Jan 2001 11:49:34 -0500 Sender: rbowen@rhiannon.rcbowen.com Message-ID: <3A5DE41D.B3E39A0B@rcbowen.com> Date: Thu, 11 Jan 2001 11:49:33 -0500 From: Rich Bowen Organization: RCBowen.com X-Mailer: Mozilla 4.72 [en] (X11; U; Linux 2.2.16 i686) X-Accept-Language: en MIME-Version: 1.0 To: apache-docs@apache.org Subject: Re: Authentication howto References: Content-Type: multipart/mixed; boundary="------------BA52C38A9A28411CBA090DF5" X-Spam-Rating: h31.sny.collab.net 1.6.2 0/1000/N --------------BA52C38A9A28411CBA090DF5 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Joshua Slive wrote: > > On Thu, 11 Jan 2001, Rich Bowen wrote: > > > One the "tutorials" page - > > http://httpd.apache.org/docs/misc/tutorials.html - under security, is > > listed an Authentication 4-part tutorial. That has gone past it's 90 day > > period as the property of ApacheToday/Internet.com, and I'd like to > > donate it to the Apache documentation project. This content can be > > either downloaded directly from Apache today, or, if desired, I can send > > the HTML or POD to anyone that wants to take on the task of making it > > fit into the Apache docs. > > If its not too much trouble, why don't you send the HTML version to the > list. Hopefully someone can clean it up and commit it. There are 4 attachments, because the article was in 4 parts. What needs to be done is to remove the stuff that makes it sounds like a weekly column ("in my last column", "in next week's column ") and, of course, the header and footer stuff and formatting. Hopefully, this will be valuable to someone. -- Rich Bowen -- Director of Web Application Development http://www.cre8tivegroup.com/ -- rich@cre8tivegroup.com Have trouble remembering things? http://www.idforgetmyhead.com/ --------------BA52C38A9A28411CBA090DF5 Content-Type: text/html; charset=us-ascii; name="auth1.html" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="auth1.html" Authentication, part 1

Authentication, part 1

Authentication is any process by which you verify that someone is who they claim they are. Authorization is any process by which someone is allowed to be where they want to go, or to have information that they want to have.

Introduction

If you have information on your web site that is sensitive or intended for only a small group of people, the techniques in this article will help you make sure that the people that see those pages are the people that you wanted to see them.

This is the first in a 2-part series. In this article, I'm going to cover the ``standard'' way of protecting parts of your web site that most of you are going to use. In the other part I'll talk about using databases, rather than text files, to contain your user and group information. Somewhere in here I'll talk about using things other than usernames and passwords to protect your web site from ``intruders'' - such as the IP address of the visitor.

The prerequisites

Everything from here on assumes that your web server permits .htaccess files. This is something that your server administrator (assuming that's not you) should easily be able to tell you, and set up for you. The relevant directive is the AllowOverride directive.

And you'll need to know a little bit about the directory structure of your server, in order to know where some files are kept. This should not be terribly difficult, and I'll try to make this clear when we come to that point.

Getting it working.

Here's the basics of password protecting a directory on your server.

You'll need to create a password file. This file should be placed somewhere outside of your document directory. This is so that folks cannot download the password file. For example, if your documents are served out of /usr/local/apache/htdocs you might want to put the password file(s) in /usr/local/apache/passwd.

To create the file, use the htpasswd utility that came with Apache. This be located in the bin directory of wherever you installed Apache. To create the file, type:

        htpasswd -c /usr/local/apache/passwd/password rbowen

htpasswd will ask you for the password, and then ask you to type it again to confirm it:

        # htpasswd -c /usr/local/apache/passwd/passwords rbowen
        New password: mypassword
        Re-type new password: mypassword
        Adding password for user rbowen

If htpasswd is not in your path, of course you'll have to type the full path to the file to get it to run. On my server, it's located at /usr/local/apache/bin/htpasswd

Next, you'll need to create a file in the directory you want to protect. This file is usually called .htaccess, although on Windows it's called htaccess (without the leading period.) .htaccess needs to contain the following lines:

        AuthType Basic
        AuthName "By Invitation Only"
        AuthUserFile /usr/local/apache/passwd/passwords
        AuthGroupFile /dev/null
        require user rbowen

The next time that you load a file from that directory, you should see the familiar username/password dialog box pop up. If you don't chances are pretty good that you are not permitted to use .htaccess files in the directory in question.

Letting more than one person in

The directives above only let one person (specifically someone with a username of rbowen) into the directory. In most cases, you'll want to let more than one person in. This is where the AuthGroupFile comes in. In the example above, we've pointed AuthGroupFile to /dev/null, which is Unix-speak for ``nowhere'', or ``off into space.'' (The Windows NT equivalent of this is nul.)

If you want to let more than one person in, you'll need to create a group file that associates group names with a list of users in that group. The format of this file is pretty simple, and you can create it with your favorite editor. The contents of the file will look like this:

        GroupName: rbowen dpitts sungo rshersey

That's just a list of the members of the group in a long line separated by spaces.

To add a user to your already existing password file, type:

        htpasswd /usr/local/apache/passwd/password dpitts

You'll get the same response as before, but it will be appended to the existing file, rather than creating a new file. (It's the -c that makes it create a new password file.

Now, you need to modify your .htaccess file to look like the following:

        AuthType Basic
        AuthName "By Invitation Only"
        AuthUserFile /usr/local/apache/passwd/passwords
        AuthGroupFile /usr/local/apache/passwd/groups
        require group GroupName

Now, anyone that is listed in the group GroupName, and has an entry in the password file, will be let in, if they type the correct password.

There's another way to let multiple users in that is less specific. Rather than creating a group file, you can just use the following directive:

        require valid-user

Using that rather than the require user rbowen line will allow anyone in that is listed in the password file, and who correctly enters their password. You can even emulate the group behavior here, by just keeping a separate password file for each group. The advantage of this approach is that Apache only has to check one file, rather than two. The disadvantage is that you have to maintain a bunch of password files, and remember to reference th right one in the AuthUserFile directive.

Possible problems

Because of the way that Basic authentication is specified, your username and password must be verified every time you request a document from the server. This is even if you're reloading the same page, and for every image on the page (if they come from a protected directory). As you can imagine, this slows things down a little. The amount that it slows things down is proportional to the size of the password file, because it has to open up that file, and go down the list of users until it gets to your name. And it has to do this every time a page is loaded.

A consequence of this is that there's a limit to how many users you can put in one password file. I don't exactly know what that limit is, but I've experienced problems when I've put more than about 1500 users in one file. People are denied access, even though you know that they have a valid username and password. It appears that what's happening is that it just takes too long to look up the password, and in the meantime, access is denied.

In the next article, we'll look at one possible solution to this problem.

Managing your password files with Perl

This may seem a little random, but it looked like a good time to throw this in.

There are two sets of Perl modules available for managing your password files, and group files, with Perl.

The first one, which is probably the recommended one, is the HTTPD-User-Manage package, which you can obtain from CPAN (http://www.cpan.org/modules/by-module/HTTPD/), allows you to manage a variety of authentication files on a variety of web servers. It is extremely full-featured, and lets you do all the sorts of things that you expect to be able to do. These modules were written by Lincoln Stein and Doug MacEachern.

The other set of modules I really only mention as shameless self-promotion. Apache::Htpasswd, by Kevin Meltzer, and Apache::Htgroup, by me, provide a simpler interface to managing password and group files specifically for Apache. These modules are also available on CPAN.

What other neat stuff can I do?

Authentication by username and password is only part of the story. Frequently you want to let people in based on something other than who they are. Something such as where they are coming from.

The allow and deny directives let you allow and deny access based on the host name, or host address, of the machine requesting a document. The directive goes hand-in-hand with these is the order directive, which tells Apache in which order to apply the filters.

The usage of these directives is:

        allow from address

where address is an IP address (or a partial IP address) or a fully qualified domain name (or a partial domain name).

For example, if you have someone spamming your message board, and you want to keep them out, you could do the following:

        deny from 205.252.46.165

Visitors coming from that address will not be able to see the content behind this directive. If, instead, you have a machine name, rather than an IP address, you can use that.

        deny from dc.numbersusa.com

And, if you'd like to block access from an entire domain, you can specify just part of an address or domain name:

        deny from 192.101.205
        deny from cyberthugs.com
        deny from ke

Using order will let you be sure that you are actually restricting things to the group that you want to let in, by combining a deny and an allow directive:

        order deny,allow
        deny from all
        allow from dev.rcbowen.com

Listing just the allow directive would not do what you want, because it will let folks from that host in, in addition to letting everyone in. What you want is to let only those folks in.

More information

You should also read the documentation for mod_auth (http://www.apache.org/docs/mod/mod_auth.html), which contains some more information about how this all works. And the FAQ on the Apache site has some good stuff about authentication, starting at http://www.apache.org/docs/misc/FAQ.html#dnsauth

Next week

Next week, I'll talk about mod_auth_dbm and mod_auth_mysql, which are two ways to authenticate against a database, rather than against a text-file password list. This is much faster.

--------------BA52C38A9A28411CBA090DF5 Content-Type: text/html; charset=us-ascii; name="auth2.html" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="auth2.html" Authentication, part II

Authentication, part II

In this article, I'll talk about using databases for authentication, rather than the standard text-file htpasswd files.

Why use a database?

There are basically three reasons to use a database, rather than a text file, to store data.

The first reason is speed. Accessing data stored in a database is much faster than accessing data stored in a text file. A database is designed for rapid location of information. A text file, you have to read through each record until you find what you are looking for.

The second reason is ease of data retrieval. A database - at least, a decent database - provides you with a language (usually SQL) for querying the database for specific information.

The third reason is data integrity. Since a database handles a lot of things for you, which you would have to handle for yourself when using a text file, you are less likely to screw up your data, and lose information, when using a real database.

Why use a database for authentication?

All of the above three reasons are important when selecting a method of authentication on your Apache server. If you're running a site with a very small number of user accounts, it may not be worth the hassle to try to use a database for your authentication. But, as your list of users grows, these things will become real assets.

As your list of users grows, it takes proportionately longer to find a given user in the password file. Past a certain number of people (about 2000 in my experience) the look-up just takes too long. Users that are listed at the bottom of the file will just be denied access, because Apache gives up looking for them before it can get that far in the file.

Managing the user lists is easier also. Rather than trying to open a large text file, and scroll through it looking for a name, you can use database queries to find the user you're looking for, and change their password, or remove them, or add a new user.

If you let your users change their password, then you are at risk of corrupting your data. Consider the situation where two users try to exit their password at nearly the same time. User A loads the file into memory, and changes their password, and starts to write the file back to disk. At that moment, user B loads the file into memory to look for their password. Oops. The file has not been written back to disk yet, so user B only gets part of the file. When they write the file back to disk, most of the users mysteriously disappear. Actually, you'll (hopefully) implement some kind of file locking to avoid this completely, but using a database removes the concern completely.

OK, so how do I do this?

There are several Apache modules that let you use a database for your authentication. I'm going to talk about just two of them: mod_auth_db and mod_auth_mysql. I'll talk about mod_auth_db this week, and leave mod_auth_mysql for next week, since there's a little more to say about it.

mod_auth_db

mod_auth_db lets you keep your usernames and passwords in DB files.

If you compiled Apache with mod_so enabled, enabling mod_auth_db should be just a matter of editing your httpd.conf file and un-commenting the line that refers to mod_auth_db. This should look something like:

        LoadModule db_auth_module     libexec/mod_auth_db.so

and, then ...

        AddModule mod_auth_db.c

Otherwise (if you don't have mod_so) you'll need to recompile Apache, and enable mod_auth_db. Since we talked about this in an earlier article, I'll not cover that here.

Wait a second ... what's a DB file?

Berkeley DB files are just one type of database files. They (usually) contain just key/value pairs, and so are rather limited in how much ``real'' database functionality you can get out of them (although there are some pretty slick extensions to them) but for HTTP authentication, a key/value pair is exactly what you want to store.

If you want to read more about DB files, you should look at the Sleepycat Software web site, at http://www.sleepycat.com/ Sleepycat maintains the DB library, and has some documentation about DB.

Protecting a directory

Once you have compiled the mod_auth_db module, and loaded it into your web server, you'll find that there's very little difference between using regular authentication and using mod_auth_db authentication. In your .htaccess file, you'll need something like:

        AuthName        "Members Only"
        AuthType        Basic
        AuthDBUserFile  /usr/local/apache/passwd/passwords.dat
        AuthDBGroupFile /usr/local/apache/passwd/passwords.dat
        require user rbowen

Now, users accessing the directory will be required to authenticate against the list of valid users who are in /usr/local/apache/passwd/passwords.dat.

A few caveats

Well, there are a few different ways to get usernames/passwords in the DB file. And a few caveats are necessary here.

First, there are several different implementations of DB, with slightly different names. While I won't go into the gory details here (mostly because I don't know them all) suffice it to say that you may need to experiment some in order to get things working the way that you think they should. It's worth the effort, but be warned.

Secondly, just to confuse things a little further (at least in my mind) on Linux, two of the implementations (DB and DBM) which are usually different on other platforms, are the same.

Third, you'll find, as part of the standard Apache distribution, another module, called mod_auth_dbm, which works with DBM files, rather than DB files. Perhaps you see why I get confused sometimes.

And, finally, because there is so much platform dependency in these DB implementations, you'll find that a DB file (or DBM file) generated on one system may or may not work on another.

So, after all those caveats, you may be wondering if this is really worth it? Well, it is. These are things that might happen, but in practice (at least in my experience) seldom do.

How do I get users into the file?

Well, there's a tool that comes with Apache, called dbmmanage. You'll find it in the bin directory of wherever you installed Apache. (or, if you installed with a package manager, wherever it thought was a good place to put it. It might even be in your path.)

You'll find full documentation for dbmmanage by typing man dbmmanage, or various places online, like http://www.rt.com/man/dbmmanage.1.html It's simple to use, and you can use it to add or remove users from your password file one at a time.

If you are going to be doing more with these files, you will probably want something a little easier to automate. Perhaps the best tool for this will be Perl, using the DB_File module. The technique that is used with this module is a tied hash, which, simplified, means that the module causes the file to act like a hash, so that modifying the hash directly changes the DB file. Pretty cool.

The following Perl code, for example, will add a user 'rbowen', with password 'mypassword', to your password file:

        use DB_File;
        tie %database, 'DB_File', "passwords.dat"
                or die "Can't initialize database: $!\n";
        $username = 'rbowen';
        $password = 'mypassword';
        @chars=(0..9,'a'..'z');
        $salt = '', map { $chars[int rand @chars] } (0..1);
        $crypt = crypt($password, $salt);
        $database{$username} = $crypt;
        untie %database;

Passwords are stored in Unix crypt format, just as they were in the ``regular'' password files. The 'salt' that is created in the middle there is part of the process, cenerating a random starting point for that encryption. If enough people care, I'll explain this Perl code in a little more detail. Otherwise, just trust me, it works. I copied it from a web site that actually works. Of course, in the real world, the username and password are read from a web form, or something like that.

What about groups?

In last week's article, we talked about putting users into groups and requiring a particular group of users. You can do the same thing with mod_auth_db, it just works a little differently. You'll notice that in my sample configuration, above, I had the following lines:

        AuthDBUserFile  /usr/local/apache/passwd/passwords.dat
        AuthDBGroupFile /usr/local/apache/passwd/passwords.dat

The user file and group file are pointing at the same location. What's up with that? It turns out that mod_auth_db stores both types of information in the same file.

Because DB files, as I mentioned early on in this article, just store a key/value pair, something has to be done to work around this limitation. What the authors of mod_auth_db decided to to was to put the group name in as part of the value, separated from the password by a colon.

So, if you were still using the Perl code above, you'd replace the line:

        $database{$username} = $crypt;

with

        $database{$username} = "$crypt:$group";

or something to that effect. You can specify more than one group by listing the groups, separated by commas.

I'm not aware of any nice way to do this with dbmmanage.

Once you have your passwords and groups in the file, you can require a group in the regular way:

        require group administrators

This is not the only way to do this, it's just the way that I do it. You can also have a separate group file, just like you do with regular text file authentication. If you ahve a separate group file, it would contain a list of username:group pairs. Again, you can have more than one group per username: just list them as a comma-separated list. And, as with the other method, I'm not aware of any nice way to do this with dbmmanage.

What about Microsoft Windows?

I actually don't know the answer to this one. I know that there are Windows implementations of DB files, so I don't know of any particular reason for it not to work. But I've never tried it myself. I'd love to hear from one of you telling me that you have it working on Windows, and telling me what you did to get it working.

Summary

mod_auth_db allows you to keep your users, passwords, and groups, in DB files rather than text files. You get all the usual benefits of using a database rather than a text file - faster access and better data reliability, and consequently, you can have larger user lists than you could support with a text file of users.

Future columns

Please let me know if there are other topics that you'd like for me to talk about in future columns. You can send your suggestions to me at ApacheToday@rcbowen.com And please let me know what you think of my columns, at that same address. Many thanks for reading down this far!

--Rich

--------------BA52C38A9A28411CBA090DF5 Content-Type: text/html; charset=us-ascii; name="auth3.html" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="auth3.html" Authentication, part 3 - mod_auth_mysql

Authentication, part 3 - mod_auth_mysql

In my last article, I talked about using databases for authentication, and I introduced mod_auth_dbm as a possible way to do that.

This week, we'll look at MySQL, a very popular database server, and using mod_auth_mysql to use MySQL to store your authentication information.

A little about MySQL

MySQL is a wonderful database server, which is distributed under the GPL, and is available from http://www.mysql.com/ MySQL is lightweight and fast. It lacks some of the features of larger, more expensive database servers, such as stored procedures, triggers, and various other things, but it contains most of the functionality needed for most small to medium projects. And, it contains some cool stuff like a regular expression language that can be used in SQL statements.

Because MySQL is free, and because it is just such a great database, it is the favorite database in use by folks on *nix operating systems - particularly folks with small budgets. And it also runs on Windows.

mod_auth_mysql

mod_auth_mysql lets you put your usernames and passwords in a MySQL database, and authenticate directly against that. There are a number of advantages to this, in addition to the obvious one of speed of data access. If, for example, you are already storing user information in a database table, it would be irritating to have to store the username and password in another location (the htpasswd file). You would have to maintain the data in two places, and if you let them get out of sync, users would be unable to log in. With mod_auth_mysq, however, you can authenticate directly against the databsae, and keep your authentication information just one place. Usernames and passwords can be updated with a SQL query, with no messing around in text files. And users' group membership can be easily altered.

Installation and configuration

You can get mod_auth_mysql, and learn more about it, at http://bourbon.netvision.net.il/mod_auth_mysql/

mod_auth_mysql can be compiled as a DSO (Dynamic Shared Object), and then included in the server with a configuration directive. For more details on this, please see earlier articles in which we discuss DSOs.

To configure mod_auth_mysql, you need to tell it what database you want to authenticate against, and what fields in which table contain the relevant information.

The following are the configuration directives that you'll need to know about:

Auth_MySQL_Info [host] [user] [password]

This directive tells where your server is running, and what username and password are necessary to get data from the database. This directive is only necessary if the server is running somewhere other than localhost, or if access is via some user other than the httpd user.

If all of your authentication will be done against the same database, you'll probably want to set the following directive:

Auth_MySQL_General_DB [database_name]

If you'll be authenticating different directories or files against different databases, you can leave this out, and set the database in the various directories.

The following directives can appear either in your httpd.conf configuration file, or in the various directories in .htaccess files. (See Ken Coar's article about .htaccess files from a week or two ago.)

Note that you'll be using the usual directives to set up password protection on the directory:

        AuthType Basic
        AuthName "Members Only"
        require group admin

Auth_MySQL_DB [database_name] - Tells which database you are authenticating against.

Auth_MySQL_Password_Table [password_table_name] - Tells which table in that database contains the password information. Unless you specify, it is assumed that the username is contained in the field 'username', and the password is contained in a field 'password'. You can change this. (See below.)

Auth_MySQL_Group_Table [group_table_name] - Ordinarily, you'll probably just want to store the group field in the same table as the usernames and passwords, but if you need to store it in a different table, this is where you'll specify where that is.

Auth_MySQL_Username_Field [username_field_name] - If your username is a field other than 'username', you can specify that with this directive.

Auth_MySQL_Password_Field [password_field_name] - If your password is a field other than 'password', you can specify that with this directive.

Auth_MySQL_Group_Field [group_field_name] - If your group name is a field other than 'groups', you can specify that with this directive.

Auth_MySQL_Encrypted_Passwords on/off - Tells mod_auth_mysql whether the passwords are in the database encrypted, or plain-text. This is on by default - that is, it is assumed that your passwords are stored encrypted.

There are several other directives, but these are the main ones that you will be using most of the time. The following is an example .htaccess file that works for me:

        Auth_MySQL_Info localhost db_user db_password
        Auth_MySQL_DB   authentication
        Auth_Mysql_Password_Table       passwords
        AuthType Basic
        AuthName "Members Only"
        require valid-user

The above assumes that the username is in a field 'username', and the password is encrypted, and is stored in the field 'password',

Now what?

Once you have your .htaccess file set up as described above, you will get the password dialog as normal. There will be no difference to the user.

You can maintain your user and password lists via whatever database management tool you are used to using. There's no handy tool like dbmmanage for managing these accounts from the command line, but I'm working on one.

You can use Perl and DBI to talk to your database. In my next column, I'll be talking at greater length about using Perl to manage your password files. There are a plethora of ways to do this, so it really merits its own article.

Summary

mod_auth_mysql allows you to keep your users, passwords, and groups, in a MySQL database. MySQL is a lightweight, fast, free database server which is available for most popular operating systems.

Future columns

Please let me know if there are other topics that you'd like for me to talk about in future columns. You can send your suggestions to me at ApacheToday@rcbowen.com And please let me know what you think of my columns, at that same address. Many thanks for reading down this far!

--Rich

--------------BA52C38A9A28411CBA090DF5 Content-Type: text/html; charset=us-ascii; name="auth4.html" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="auth4.html" Authentication, Part IV - Managing your authentication files with Perl

Authentication, Part IV - Managing your authentication files with Perl

In the last three articles, I've talked about authentication on Apache - asking the user for a username and password to get at your stuff. This week I'll cover some techniques for automating the maintenance of your password lists with Perl. Doing it all by hand can be a real drag.

Warning: This article assumes that you already have a grasp on the basics of Perl.

Perl

In case you don't know what Perl is, it's a programming language. It's a very popular programming language, favored by folks for doing tasks that require text manipulation, sockets communication, orchestrating various applications in some way, and a plethora of other tasks. It is reputed to be very popular as a CGI programming language also, but that's only a smidgen of the whole story, and tends to sell Perl short by people who think ``Oh, that's just a CGI language.''

Encrypting a password

One of the things that is going to come in very handy in managing user and password lists is the ability to encrypt a password. The good news is that Perl has a built-in function to do just this. It's called crypt. In order to use it, you need to understand a few things.

First, as mentioned in an earlier article, Apache stores passwords in what's know as ``Unix crypt'' format. Perl's crypt function produces this same format. To encrypt a string, you need something called the ``salt.'' The salt is a two (or more) character string that is used to get the encryption started. The salt is usually generated randomly, and so the string will end up being encrypted differently depending on the salt that was picked.

To call the crypt function in Perl, you'd do the following:

        $encrypted = crypt ($password, $salt);

In the above code example, $password is assumed to have been supplied by the user in some fashion, and $salt is assumed to have been generated in some fashion. More on this later.

Crypt is a one-way encryption algorithm. What that means is that once you have encrypted a string, there's no way to decrypt it - to get it back to it's original format. This means that the only way to tell if a particular password is the same as the original is to encrypt that password, and see if you get the same thing. Of course, you have to encrypt it with the same string. Conveniently, crypt leaves the salt in the first two characters of the encrypted string, so you just have to do something like this:

        $guess_encrypted = crypt ($guess, $encrypted);
        if ($guess_encrypted eq $encrypted)     {
                print "You guessed right.\n";
        }
        else {
                print "Wrong password, try again.\n";
        }

When you specify a particular string as the salt, Perl knows to just use the first two characters of that string.

By the way, to generate a salt yourself, you can use something like this:

        @a=(0..9,'a'..'z');
        $pass = join '', map { $a[int rand @a] } (0..1);

That just generates a 2-character string composed of random numbers and letters. And, as always in Perl, there's more than one way to do it.

Adding a password to a password file

We've talked about three ways to store your usernames and passwords. First, three weeks ago, we talked about using plain text files. Two weeks ago, we talked about using DBM files. And last week, we talked about using a MySQL database.

There are several ways to handle putting passwords into each type of storage mechanism. In each case, you can do things ``by hand'', or you can use one of the existing CPAN modules to do a lot of the work for you.

The CPAN module to look for is HTTPD::UserManage. It was written by Lincoln Stein and Doug MacEachern, and allows you to manage multiple types of authentication mechanisms, on multiple server-types (Apache, Netscape, etc) via one interface.

You can get HTTPD::UserManage from your favorite CPAN mirror. It also comes with a CGI application that, when correctly installed, lets you manage your authentication files from the web. Pretty cool stuff.

There are also a couple of other modules - Apache::Htpasswd and Apache::Htgroup, that give a simple, Apache-only interface for managing your authentication files.

Adding a password to a text password file

If you want to add a password to a text 'htpasswd' type password file, without the benefit of modules, here's how you'd do it:

        open PASSWD, '>>/path/to/.htpasswd';
        print PASSWD "$username:$encrypted\n";
        close PASSWD;

Well, you say to yourself, that's pretty darned simple. Why would I want to use a module to do that? Three reasons. One, if you're going to be doing this hundreds or thousands of times, you'll find it much easier to be able to call one function, passing in the username and desired password, than encrypting the password yourself and running the above code. Secondly, the modules provide you with a lot of other functionality, such as verifying a password, and deleting a user. Thirdly, if you're using HTTPD::UserManage, and you decide a year from now to change to using mod_auth_mysql instead of htpasswd files, you don't have to change any code. That third one is a big win, because some day you will want to change your authentication method, and you don't want to be stuck with changing code a dozen places, and potentially missing a few. Trust me. I missed a few.

Passwords in DBM files

DBM files are the fun ones, because they let me use a pretty cool feature of Perl. Perl has a key work called tie. As the name suggests, it lets you tie one thing to another. In this case, it lets you tie a variable (in particular, a hash) to a DBM file. So, when you modify the hash, the DBM file automatically gets modified for you. Very cool stuff.

This looks like the following:

        use DB_File;
        my %database;
        tie %database, 'DB_File', "passwords.dat"
            or die "Can't initialize database: $!\n";
    $crypt = crypt($password, $salt);
        $database{$username} = $crypt;
        untie %database;

And, voila, you have an entry in the password file associating user $username with their password.

Note that you should, of course, not put your password file inside your web root, where someone can download it and crack it at their leisure. The above code is just an example.

Passwords in MySQL databases

This is the most obvious one. In fact, most often when you use mod_auth_mysql, it's beacase you already have user information in a database, and want to use if for authentication.

Information can be updated in the database with regular SQL statements, and DBI:

        use DBI;
        my $dbh = DBI->connect('DBI:mysql:database', 'username',
     'password'); # 'password' is the database password.
        my $sth = $dbh->prepare("update passwords
                set passwd = '$crypt' where username = '$username'");
        $sth->execute;
        $sth->finish;
        $dbh->disconnect;

Summary

This was a lightning-overview of how one might use Perl to manage your password lists, in any of the three storage mechanisms that we've talked about over the last three weeks.

--------------BA52C38A9A28411CBA090DF5--