Question

Securing a Perl login script

Asked by: BrianPap22

I'm not an expert in Perl by any means, but here I went ahead and wrote a tiny login script.  I would like to make the script as secure as possible, both from a malicious user entering in bogus data, and from my own dumb self :)

Standard CGI/Perl stuff here.  Later on I'm going to implement some timing checks against brute force attacks, but I'm not too worried about such a thing, honestly.  I'm also not incredibly concerned with efficiency, but if there is some *major* noob mistake I have made, feel free to point it out and I'll make sure you get some points. Point out as little or as much things as you'd like that is wrong with this script, and I will split the points accordingly.

So without further ado, here it is (I apologize for the poor use of style. I'll get better as I go along). Thank you for your time.


#!/usr/bin/perl

use strict;
use Crypt::PasswdMD5;
use CGI 'param','header';

$CGI::POST_MAX = 128;
$CGI::DISABLE_UPLOADS = 1;

open PWFILE, 'passwords'      # Each line is of "user:MD5" style.
  or die "can't open it";
my @pwfile = <PWFILE>;      # Slurpie it! - not a terribly large file, so no worries.
close PWFILE;

my $user = lc(param("user"));
my $pass = param("pass");

print header( {-type=>'text/plain',-expires=>'now'} );

for (@pwfile) {
     if (
          m/
               ^$user:               # Line begins with "$user:".
               (\$1\$.{8}\$)     # Backreference 1: 12 character salt value: "$1$xxxxxxxx$".
               (.{22})               # Backreference 2: 22 character encrypted password.
               $                    # Line ends.
          /ox
          && $1.$2 eq unix_md5_crypt($pass,$1)     # When we match $user, check the password.
     )
     {
          print "Authorized...";     # Do some quick/short stuff here.
          exit;                              # No more need to continue the search.
     }
}
print "Incorrect username or password."; # If you can read this, then we must not have found a match!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-04-06 at 02:23:20ID20944860
Tags

login

,

perl

,

script

Topic

CGI Scripting

Participating Experts
5
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Upload gif/jpg file in cgi\perl
    Hi, I need a cgi in perl that recive from client (by HTML form) uploaded gif/jpg file and save it on the server. As a resule,the cgi file will show the client HTML with the gif/jpg picture.
  2. Perl, If Then
    I'm new to Perl and I need to validate a script. Here's the deal. I have a variable named $Institution which will have the user enter one of two values ASU or MCG . If Institution's value = ASU I need it to pull up one web page (www.aug.edu/~ASA) and if it =MCG I need it t...
  3. Perl Simple Login Script
    Hi, im making a perl login script... i want it to check a file... and each line of the file will look like this: username, password anyways i enter the right username and password and it always says its wrong or right even if the user is right and password is right ... or us...
  4. How to maintain data in CGI Perl
    Hi, How can I maintain data inputed by user (i.e. username) throughout the session? I'm a java programmer and I'm just starting to program CGI Perl and I just wanted to know if there's something like session object in Perl that I could keep my data. Thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: BrianPap22Posted on 2004-04-06 at 16:14:55ID: 10770586

Should I take the lack of responses as a sign that I did something right for once? I find that hard to believe for this, my second Perl script ever.

Would a working prototype help someone? If so, just let me know and I can throw one up on some webspace.

OK, new policy... I won't split the points.  500 points per valid suggestion (I'll just create a new award question). If this is not acceptable under the ToS of EE, then a moderator may kindly let me know, and I will not do that. Otherwise, I have unlimited question points and I'm itchin' to use them :)

 

by: TintinPosted on 2004-04-06 at 17:16:14ID: 10770872

That's a damm good effort for a Perl newbie (I suspect you must have other programming experience).

There's no glaring holes.  Just a couple of comments:

1.  You should add a check to see if $user and/or $pass are not specified, otherwise there's no point in proceeding.  So before the open, do a:

die "No username supplied\n" unless $user;
die "No password supplied\n" unless $pass;

2. Also your for loop could probably be written to be a little more readable (although there's nothing really wrong with it). As I can figure, the password file has entries along the lines of:

username:xxxxxxxxxxxxzzzzzzzzzzzzzzzzzzzzzz

Where x is the salt and z is the encrypted password?  

for (@pwfile) {
  if (/^$user:/) {
      my ($salt,$encpass) = /:(.{12})(.{22})/;
       if ($salt$encpass eq unix_md5_crypt($pass,$salt) {
           print "Authorized\n";
           exit;
       }
  }
}

print "Incorrect username or password\n";    

 

by: BrianPap22Posted on 2004-04-06 at 18:28:42ID: 10771223

An example line in the pass file would look like this (bogus of course :)

brian:$1$CuRbwNsF$ibVNqwFpWc9o5fJxwziTFT

$1$CuRbwNsF$ is the salt. The rest is the encoded password. The salt is actually 8 characters, but it always begins with "$1$" and ends with "$".  When you encrypt the plaintext password together with the salt value, it returns the salt value as part of the return (odd that it does it that way, but that's just the way it is).

When I wrote the for() loop, I knew I was going to ask for advice, and I thought the way I did it would actually be the most readable. Of course, that was just my opinion.  But you suspect correctly; I do have other experience. PHP mostly, but I'm a little new to that, also.  I originally wrote this script in PHP, but all of a sudden my needs changed, and I needed it in Perl.

Funny that I forgot to check for empty values. I was trying to keep it as simple as possible for readability.

 

by: TintinPosted on 2004-04-06 at 18:43:33ID: 10771286

In that case, change my regex to

my ($salt,$encpass) = /:\$1\$(.{8})\$(.{22})/;

 

by: ozoPosted on 2004-04-06 at 21:07:08ID: 10771744

if (/^$user:/) { #beware of user=.*|

 

by: BrianPap22Posted on 2004-04-07 at 00:09:01ID: 10772423

I completely missed that, ozo. I think I'll take the pro-active way and limit their accounts to just letters, numbers, dash and underscore, and that will be that.

 

by: ahoffmannPosted on 2004-04-07 at 12:25:48ID: 10777752

> $CGI::POST_MAX = 128;
is more or less useless, unfortunately, but its good to be there anyway ;-)
Reason:  when perl gets called, the web-server already collected all data

As ozo already pointed out: you need to clean all incomming variables ($user, $pass)
Don't know what
  unix_md5_crypt($pass,$1)
does, but if it calls system commands somehow, then I'd try to give as password:
   ';/bin/rm -rf *.*
or:
  |/bin/rm -rf *.*

So please check all parameters using white lists, like:
   $user =~ s#[^a-zA-Z0-9.-]##g;
   $pass =~ s#[^a-zA-Z0-9.-]##g;
take care when adding more characters for the password.

 

by: BrianPap22Posted on 2004-04-08 at 06:46:36ID: 10783462

It does not appear to me that unix_md5_crypt() calls system commands.

Read about it here:
http://search.cpan.org/~luismunoz/Crypt-PasswdMD5-1.3/PasswdMD5.pm
"Crypt::PasswdMD5 - Provides interoperable MD5-based crypt() functions"

 

by: ahoffmannPosted on 2004-04-08 at 09:42:55ID: 10785024

>  It does not appear to me ..
you know for shure, or not?
Are you shure that underlaying systems (like Digest::MD5) behave this way in future too?
If not, make shure your parameters won't harm.
That's my message, you asked for security .. ;-)

 

by: BrianPap22Posted on 2004-04-08 at 14:26:06ID: 10787343

I understand what you're saying.  It probably won't change in the future, but I suppose it won't hurt to prepare for the worst.

I know it's better to use "white lists" instead of "black lists."  So my list of "approved characters" so far is as follows:

a-z
A-Z
0-9
,.<>[]{}?_+
~!@#$%^&*()_+

This should exclude [space], backtick [`], [/\] forward and backslash, pipe [|], colon and semi-colon [;:], and everything else I can't think of.

My user's need to be able to enter in as sophisticated a password as possible, so I don't want to go overkill with this.

You know, I'm starting to get the feeling that I shouldn't be using regular expressions at all. If I set up a for() loop to run through each line and used ($uname,$hash) = split(/:/), then I could just match 'if $uname eq $user'  ... etc.

Might that be safer? Worse?  No difference?  Remember, efficiency is not a priority.

 

by: ozoPosted on 2004-04-08 at 14:41:05ID: 10787451

eq $user is more efficient, but otherwise equivalent to =~ m/^\Q$user\E\z/ which are of course safer and more forgiving than m/$user/

 

by: ahoffmannPosted on 2004-04-09 at 01:35:32ID: 10789798

with %  you pass over URL encoded charaters
with !  you may access shell commands
with &  you can combine shell commands
with $  you can access variables in shell
with @  you may access functions in M$ SQL
with %_ you have wild cards in SQL
and so on ...

My pedantic filter for a username is:
   a-zA-Z0-9.-
for the password, it needs to be more, I agree

 

by: mishagalePosted on 2004-04-15 at 11:35:42ID: 10835799

I'll join Tintin on contratulating you for such a nifty first script, and there is only one nit I want to pick:
After your if (regex) { } you have nothing to handle the exception that the format of the password file is invalid (the regex itself is not matched). This is not  actually insecure, as this case would still result in failed authorization, but it is confusing for a user, and hard for an admin to debug, if their correctly typed password should fail due to a corrupted file.

 

by: mastallamaPosted on 2005-03-05 at 10:38:12ID: 13466763

your script is awesome!

MastaLlama

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...