Speedfreak has asked for the wisdom of the Perl Monks concerning the following question:

Hej All,

I'm in the middle of finishing up a CGI script but I'd like to prevent it from being called from other sites.

I'l like to check the name of the page that called the script and the hostname of the computer it was run from and prevent everything except my form and my host from using it.

Anyone got any sample code?

- Jed

  • Comment on Checking where my CGI is bing called from.

Replies are listed 'Best First'.
Re: Checking where my CGI is bing called from.
by turnstep (Parson) on Apr 19, 2000 at 16:17 UTC
    You can use these environment variables, which are in %ENV:
    • REMOTE_HOST (host name, may not be implemented on your system)
    • REMOTE_ADDR (dotted decimal IP of the browser)
    • HTTP_REFERER (the page they came from)
    These are the main ones to use, although the last is not as reliable as the first two and can be easily faked. However, a simple check should keep out 99.9% of the people:
    unless ($ENV{'HTTP_REFERER'} eq "$mypage") { print "Access forbidden. Goodbye.\n"; exit; }
    P.S. Yes, 'referer' is spelled wrong, but that's now the official way. :)
Matt's Approach
by BBQ (Curate) on Apr 19, 2000 at 20:52 UTC
    If I remember correctly, Matt's Script Archive had another approach.

    He also uses $ENV{'HTTP_REFERER'} but instead of comparing to 1 URL, he sets a few @friends. Something along the lines of
    my @friends = ( 'www.mysite.com', 'www.yoursite.com', 'www.hissite.com/mypage/' 'www.hersite.com/herpage/' ); foreach $site (@friends) { if ($ENV{'HTTP_REFERER'} =~ m/$site/i) { $isafriend = 1; } } if (!$isafriend) { # do the stuff here, Location, html, etc. }
    Although this provides a way to compare a few sites, there is a major security flaw (that I feel can be easily fixed) by allowing just $ENV{HTTP_REFERER} to match 'www.mysite.com'... You see, I might as well have an URL like "http://badsite.com/www.mysite.com/" and it would pass!

    Am I rambling already? Ok, I'll shutup.

    #!/home/bbq/bin/perl
    # Trust no1!
Re: Checking where my CGI is bing called from.
by comatose (Monk) on Apr 19, 2000 at 19:51 UTC

    And to make sure, it's clear, $mypage in turnstep's example would be the URL for your form. In other words, if the URL for your form was:

    http://www.mydomain.com/pages/myform.html
    you would want to set $mypage equal to that. Also, to make sure it exits gracefully if someone just goes directly to the script, I would put the following early on in it:
    $errorURL = 'http://www.mydomain.com/mypage.html'; if (!defined $ENV{HTTP_REFERER}) { print "Location: $errorURL\n\n"; exit; }
    This will send them back to $errorURL if they try to go to the script directly rather than giving a possible 500 error.