3 # (configure the first line to contain YOUR path to perl 5.000+)
11 # perl 5.0 or higher (see: "http://www.perl.org/")
15 if(grep(/\-\-help/i, @ARGV))
17 print << 'ENDOFPREHELPTEXT1';
18 # CGIscriptor.pl is a Perl program will run on any WWW server that
19 # runs Perl scripts, just add a line like the following to your
20 # httpd.conf file (Apache example):
22 # ScriptAlias /SHTML/ "/real-path/CGIscriptor.pl/"
24 # URL's that refer to http://www.your.address/SHTML/... will now be handled
25 # by CGIscriptor.pl, which can use a private directory tree (default is the
26 # DOCUMENT_ROOT directory tree, but it can be anywhere, see below).
27 # NOTE: if you cannot use a ScriptAlias, there is a way to use .htaccess
30 # This file contains all documentation as comments. These comments
31 # can be removed to speed up loading (e.g., `egrep -v '^#' CGIscriptor.pl` >
32 # leanScriptor.pl). A bare bones version of CGIscriptor.pl, lacking
33 # documentation, most comments, access control, example functions etc.
34 # (but still with the copyright notice and some minimal documentation)
35 # can be obtained by calling CGIscriptor.pl with the '-slim'
36 # command line argument, e.g.,
37 # >CGIscriptor.pl -slim >slimCGIscriptor.pl
39 # CGIscriptor.pl can be run from the command line as
40 # `CGIscriptor.pl <path> <query>`, inside a perl script with
41 # 'do CGIscriptor.pl' after setting $ENV{PATH_INFO} and $ENV{QUERY_STRING},
42 # or CGIscriptor.pl can be loaded with 'require "/real-path/CGIscriptor.pl"'.
43 # In the latter case, requests are processed by 'Handle_Request();'
44 # (again after setting $ENV{PATH_INFO} and $ENV{QUERY_STRING}).
46 # The --help command line switch will print the manual.
48 # Running demo's and more information can be found at
49 # http://www.fon.hum.uva.nl/rob/OSS/OSS.html
51 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site
52 # or CPAN that can use CGIscriptor.pl as the base of a µWWW server and
53 # demonstrates its use.
58 # Configuration, copyright notice, and user manual follow the next
61 ############################################################################
63 # Changes (document ALL changes with date, name and email here):
64 # 10 Feb 2014 - Added use of FAT fs and spaces in filenames
65 # 06 Feb 2014 - Corrected behavior of ACCEPT.lis and REJECT.lis
66 # 05 Apr 2013 - Renamed COOKIE_JAR to HTTP_COOKIE, added support for
67 # CGI::Cookie in case $ENV{HTTP_COOKIE} is undefined (untested)
68 # 31 Mar 2013 - Added support for Digest::SHA
69 # 13 Mar 2013 - Changed password hash
70 # 10 Jul 2012 - Version 2.4
71 # 11 Jun 2012 - Securing CGIvariable setting. Made
72 # 'if($ENV{QUERY_STRING} =~ /$name/)' into elsif in
73 # defineCGIvariable/List/Hash to give precedence to ENV{$name}
74 # This was a very old security bug. Added ProtectCGIvariable($name).
75 # 06 Jun 2012 - Added IP only session types after login.
76 # 31 May 2012 - Session ticket system added for handling login sessions.
77 # 29 May 2012 - CGIsafeFileName does not accept filenames starting with '.'
78 # 29 May 2012 - Added CGIscriptor::BrowseAllDirs to handle browsing directories
80 # 22 May 2012 - Added Access control with Session Tickets linked to
81 # IP Address and PATH_INFO.
82 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
83 # Will link to current base URL when the HTTP server is '.' or '~'
84 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
85 # CGIsafeFileName does not accept filenames starting with '-'
86 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
87 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
88 # 28 Jan 2005 - Added a file selector to performTranslation.
89 # Changed %TranslationTable to @TranslationTable
90 # and patterns to lists.
91 # 27 Jan 2005 - Added a %TranslationTable with associated
92 # performTranslation(\$text) function to allow
93 # run changes in the web pages. Say, to translate
94 # legacy pages with <%=...%> delimiters to the new
95 # <SCRIPT TYPE=..></SCRIPT> format.
96 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
97 # Other Languages Code.
98 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
99 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
101 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
102 # 20 May 2003 - Added a --help switch to print the manual.
103 # 06 Mar 2003 - Adapted the blurb at the end of the file.
104 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
105 # "die" calls. Also "enhanced" the STDERR printout.
106 # 10 Feb 2003 - Split off the reading of the POST part of a query
107 # from Initialize_output. This was suggested by Gerd Franke
108 # to allow for the catching of the file_path using a
109 # POST based lookup. That is, he needed the POST part
110 # to change the file_path.
111 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
112 # 03 Feb 2003 - \1 better written as $1 in
113 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
114 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
116 # $ServerScriptContentClass = "ssperl";
117 # changed in ProcessFile():
118 # unless(($CurrentContentType =~
119 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
120 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
121 # Update comments and documentation.
122 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
124 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
125 # Also added a note that RawFilePattern can be a
126 # complete file name.
127 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
128 # switch to prepending or to appending the content
129 # of the SRC attribute. Default is prefixing. You
130 # can add as many of these switches as you like.
131 # 13 Mar 2002 - Do not search for tag content if a tag closes with
132 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
133 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
135 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
136 # (i.o. a list context). This is necessary for binary results.
137 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
138 # changed the order of if/elsif to allow removing these
139 # conditions in systems with broken -T functions.
140 # (I also removed a spurious ')' bracket)
141 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
142 # to support binary files.
143 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
144 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
145 # stipped from the path.
146 # 15 Jan 2002 - Version 2.2
147 # 15 Jan 2002 - Debugged and completed URL support (including
148 # CGIscriptor::read_url() function)
149 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
150 # with the main::GET_URL function. Uses wget -O underlying.
151 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
152 # (i.e., my $NewDirective = "";) to clear old output
153 # (this was a realy anoying bug).
154 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
155 # tags that assign the body text as-is (literally)
156 # to $varname. Allows standard HTML-tools to handle
157 # Cascading Style Sheet templates. This implements a
158 # design by Gerd Franke (franke@roo.de).
159 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
160 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
161 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
162 # detect unwanted indexing of TAR files by webcrawlers.
163 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
164 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
165 # processed file type. Was processed via BinaryMapFile.
166 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
167 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
168 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
169 # be manipulated to achieve a "Sub Root".
170 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
171 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
172 # and debugging (it now works).
173 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
174 # hashes,instead of replacing existing hashes.
175 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
176 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
177 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
178 # CGIparseValueHash (used with structured parameters).
179 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
180 # Will collect all <CGI-partial-name><key>=value pairs in
181 # $<CGI-partial-name>{<key>} = value;
182 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
183 # 09 Aug 2000 - Added support for non-filesystem input by way of
184 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
185 # environment variables.
186 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
187 # This allows CGIscriptor to be used in pipes.
188 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
189 # in an HTTP request (i.e., in a web server).
190 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
191 # is not HTTP or another protocol. Changed the default
192 # source directory to DOCUMENT_ROOT (i.o. the incorrect
194 # 24 Jul 2000 - -slim Command-line argument added to remove all
195 # comments, security, etc.. Updated documentation.
196 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
197 # execution of all <META> and <SCRIPT> code
199 # 05 Jul 2000 - Rewrote and isolated the code for extracting
200 # quoted items from CGI and SRC attributes.
201 # Now all attributes expect the same set of
202 # quotes: '', "", ``, (), {}, [] and the same
203 # preceded by a \, e.g., "\((aap)\)" will be
204 # extracted as "(aap)".
205 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
206 # name-space (i.o. by evaluation) from
207 # CGI attributes to prevent interference with
208 # the processing for non perl scripts.
209 # Changed CGIparseValueList to prevent runaway
211 # 16 Jun 2000 - Added a direct (interpolated) display mode
212 # (text/ssdisplay) and a user log mode
214 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
215 # allow large string output.
216 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
217 # remove all control characters. Changed Interpreter
218 # initialization to shrub interpolated CGI parameters.
219 # Added 'text/ssmailto' interpreter script.
220 # 22 May 2000 - Changed some of the comments
221 # 09 May 2000 - Added list extraction for CGI parameters with
222 # CGIparseValueList (used with multiple selections).
223 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
224 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
225 # 27 Apr 2000 - Updated documentation to reflect changes.
226 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
228 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
229 # 27 Apr 2000 - Gprolog, M4 support added.
230 # 26 Apr 2000 - Lisp (rep) support added.
231 # 20 Apr 2000 - Use of external interpreters now functional.
232 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
233 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
234 # the use of $#foo, i.e., I changed
235 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
237 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
238 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
239 # things like, e.g., CVS information in CVS subtrees
240 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
241 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
242 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
243 # over a "burried" BinaryMapFile.
244 # 04 Oct 1999 - Added two functions to check file names and email addresses
245 # (CGIscriptor::CGIsafeFileName and
246 # CGIscriptor::CGIsafeEmailAddress)
247 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
248 # to allow LONG posts.
249 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
250 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
251 # this directory exists.
252 # 07 June 1999 - Limit file-pattern matching to LAST extension
253 # 04 June 1999 - Default text/html content type is printed only once.
254 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
255 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
256 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
257 # Changed the processing of the Accept and Reject file.
258 # Added a full expression evaluation to Access Control.
259 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
260 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
261 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
262 # Requests are serviced by "Handle_Request()". CGIscriptor
263 # can still be called as a isolated perl script and a shell
265 # Changed the "factory default setting" so that it will run
266 # from the DOCUMENT_ROOT directory.
267 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
268 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
269 # to subroutines to change CGIscriptor into a module.
270 # Added mapping to process unsupported file types (e.g., binary
271 # pictures). See $BinaryMapFile.
272 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
273 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@gmail.com)
274 # Removed a double setting of filepatterns and maximum query
275 # size. Changed email address. Removed some typos from the
277 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
278 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@gmail.com)
279 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
280 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
286 # It is not possible to use operators or variables to construct variable names,
287 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
288 # will indeed work. If someone could tell me why, I would be obliged.
291 ############################################################################
293 # OBLIGATORY USER CONFIGURATION
295 # Configure the directories where all user files can be found (this
296 # is the equivalent of the server root directory of a WWW-server).
297 # These directories can be located ANYWHERE. For security reasons, it is
298 # better to locate them outside the WWW-tree of your HTTP server, unless
299 # CGIscripter handles ALL requests.
301 # For convenience, the defaults are set to the root of the WWW server.
302 # However, this might not be safe!
305 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
306 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
307 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
309 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
310 $ENV{'DOCUMENT_ROOT'} =~ s@
/CGIscriptor
.*$@
@ig;
313 # Just enter your own directory path here
314 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
316 # ./ script files (recommended to be different from the previous)
317 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
318 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
320 # End of obligatory user configuration
321 # (note: there is more non-essential user configuration below)
323 ############################################################################
325 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
327 # Script content-types: TYPE="Content-type" (user defined mime-type)
328 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
329 # CSS require a simple class
330 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
331 $' : "ssperl"; # Server Side Perl CSS classes
333 $ShellScriptContentType = "text/osshell"; # OS shell scripts
334 # # (Server Side perl ``-execution)
336 # Run from FAT file systems (Windows) based on environment variable
337 $useFAT = $ENV{'USEFAT
'};
338 # Accessible file patterns, block any request that doesn't match
.
339 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
340 # (\. is used in regexp)
341 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
342 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt|.js|.css";
344 # The table with the content type MIME types
345 # (allows to differentiate MIME types, if needed)
348 '.html' => 'text/html',
349 '.shtml' => 'text/html',
350 '.htm' => 'text/html',
351 '.xml' => 'text/xml',
352 '.txt' => 'text/plain',
353 '.js' => 'text/plain',
354 '.css' => 'text/plain'
358 # File pattern post-processing
359 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
361 # SHAsum command needed for Authorization and Login
362 # (note, these have to be accessible in the HTML pages, ie, the CGIexecute environment)
363 my $shasum = "shasum -a 256";
364 if(qx{uname
} =~ /Darwin/)
366 $shasum = "shasum-5.12 -a 256" unless `which shasum`;
368 my $SHASUMCMD = $shasum.' |cut -f 1 -d" "';
369 $ENV{"SHASUMCMD"} = $SHASUMCMD;
370 my $RANDOMHASHCMD = 'dd bs=1 count=64 if=/dev/urandom 2>/dev/null | '.$shasum.' -b |cut -f 1 -d" "';
371 $ENV{"RANDOMHASHCMD"} = $RANDOMHASHCMD;
373 # Hash a string, return hex of hash
374 sub hash_string_cmd
# ($string) -> hex_hash
376 my $string = shift || "";
377 # Catch nasty \'-quotes, embed them in '..'"'"'..'
378 $string =~ s/\'/\'\"\'\"\'/isg;
379 my $hash = `printf '%s' '$string'| $ENV{"SHASUMCMD"}`;
384 # Note that you CANNOT replace $RANDOMHASHCMD with a call using hash_string_cmd
385 # as the output of /dev/urandom breaks string handling in Perl.
386 # Generate random hex hash
387 sub get_random_hex_cmd
# () -> hex
389 # Create Random Hash Salt
390 open(URANDOM
, "$RANDOMHASHCMD |") || die "URANDOM; $RANDOMHASHCMD | $!\n";
391 my $RANDOMSALT= <URANDOM
>;
399 # You can use Digest::SHA (SHA.pm), you need sha256_hex
400 # See http://search.cpan.org/~mshelor/Digest-SHA-5.84/lib/Digest/SHA.pm
401 # > sudo CPAN -i Digest
403 # The following code will check whether Digest::SHA is available and then
404 # use the appropriate function calls.
406 $shaDigestLoaded = (eval("require Digest::SHA;1;") eq "1") ?
1 : 0;
408 sub hash_string_Digest
# ($string) -> hex_hash
410 my $string = shift || "";
411 my $digest = Digest
::SHA
::sha256_hex
($string);
416 sub get_random_hex_Digest
# () -> hex
418 my $randomstring = "";
419 # Create Random Hash Salt
420 open(URANDOM
, "</dev/urandom") || die "/dev/urandom: $!\n";
421 read URANDOM
, $randomstring, 64 || die "No random bytes read: $!\n";
423 my $RANDOMSALT= hash_string_Digest
($randomstring);
428 # The final functions
429 sub hash_string
# ($string) -> hex_hash
432 { return hash_string_Digest
(@_) }
434 { return hash_string_cmd
(@_);};
437 sub get_random_hex
# () -> hex
440 { return get_random_hex_Digest
() }
442 { return get_random_hex_cmd
();};
445 ######################################################################
447 # File patterns of files which are handled by session tickets.
448 %TicketRequiredPatterns = (
449 '^/Private(/|$)' => "Private/.Sessions\tPrivate/.Passwords\t/Private/Login.html\t+36000"
451 # Used to set cookies, only session cookies supported
452 my %SETCOOKIELIST = ();
453 my %CGI_Cookies = ();
454 # Parse the cookies if $ENV{'HTTP_COOKIE'} is defined, else use CGI::Cookie
458 $ENV{'HTTP_COOKIE'} = $ENV{'Cookie'} if defined($ENV{'Cookie'}) && !defined($ENV{'HTTP_COOKIE'});
460 if(defined($ENV{'HTTP_COOKIE'}))
462 my @CookieList = split(/[\;\s]+/, $ENV{'HTTP_COOKIE'});
463 foreach my $CookieEntry (@CookieList)
465 my ($k, $v) = split(/\=/, $CookieEntry);
466 # Add new cookie only if it does not already exist
467 $CGI_Cookies{$k} = $v unless exists($CGI_Cookies{$k}) && ($v eq "" || $v eq "-");
468 ($k, $v, $CookieEntry) = (0, 0, 0);
471 $ENV{'Cookie'} = "" if defined($ENV{'Cookie'})
475 my $cookiesLoaded = (eval("require CGI::Cookie;1;") eq "1") ?
1 : 0;
478 %CGI_Cookies = fetch CGI
::Cookie
;
484 # Session Ticket Directory: Private/.Sessions
485 # Password Directory: Private/.Passwords
486 # Login page (url path): /Private/Login.html
487 # Expiration time (s): +3600
488 # +<seconds> = relative time <seconds> is absolute date-time
491 # Set up a valid ticket from a given text file
492 # Use from command line. DO NOT USE ONLINE
493 # Watch out for passwords that get stored in the history file
495 # perl CGIscriptor.pl --managelogin [options] [files]
497 # salt={file or saltvalue}
498 # masterkey={file or plaintext}
499 # newmasterkey={file or plaintext}
500 # password={file or palintext}
502 # Followed by one or more file names.
503 # Options can be interspersed between filenames,
504 # e.g., password='plaintext'
505 # Note that passwords are only used once!
507 if($ARGV[0] =~ /^\-\-managelogin/i)
509 my @arguments = @ARGV;
511 setup_ticket_file
(@arguments);
512 # Should be run on the command line
518 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
519 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
520 $RawFilePattern = ".xmr";
521 # (In principle, this could contain a full file specification, e.g.,
522 # ".xmr|relocated.html")
524 # Raw File pattern post-processing
525 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
527 # Server protocols for which "Content-type: text/html\n\n" should be printed
528 # (you should not bother with these, except for HTTP, they are mostly imaginary)
529 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
531 # Block access to all (sub-) paths and directories that match the
532 # following (URL) path (is used as:
533 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
534 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
536 # All (blocked) other file-types can be mapped to a single "binary-file"
537 # processor (a kind of pseudo-file path). This can either be an error
538 # message (e.g., "illegal file") or contain a script that serves binary
540 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
541 $BinaryMapFile = "/BinaryMapFile.xmr";
542 # Allow for the addition of a CGIscriptor directory
543 # Note that a BinaryMapFile in the root "~/" directory has precedence
544 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
545 if ! -e
"$YOUR_HTML_FILES".$BinaryMapFile
546 && -e
"$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
549 # List of all characters that are allowed in file names and paths.
550 # All requests containing illegal characters are blocked. This
551 # blocks most tricks (e.g., adding "\000", "\n", or other control
552 # characters, also blocks URI's using %FF)
553 # THIS IS A SECURITY FEATURE
554 # (this is also used to parse filenames in SRC= features, note the
555 # '-quotes, they are essential)
556 $FileAllowedChars = '\w\.\~\/\:\*\?\-\ '; # Covers Unix and Mac, including spaces
558 # Maximum size of the Query (number of characters clients can send
559 # covers both GET & POST combined)
560 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
563 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
564 # (returns a string with the PERL code to transfer the URL contents, e.g.,
565 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
566 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
567 # Be sure to handle <BASE HREF='URL'> and allow BOTH
568 # direct printing GET_URL($URL [, 0]) and extracting the content of
569 # the $URL for post-processing GET_URL($URL, 1).
570 # You get the WHOLE file, including HTML header.
571 # The shell command Use $URL where the URL should go
572 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
573 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
574 #my $GET_URL_shell_command = 'snarf $URL -';
575 #my $GET_URL_shell_command = 'curl $URL';
577 sub GET_URL
# ($URL, $ValueNotPrint) -> content_of_url
579 my $URL = shift || return;
580 my $ValueNotPrint = shift || 0;
582 # Check URL for illegal characters
583 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
585 # Include URL in final command
586 my $CurrentCommand = $GET_URL_shell_command;
587 $CurrentCommand =~ s/\$URL/$URL/g;
589 # Print to STDOUT or return a value
590 my $BlockPrint = "print STDOUT ";
591 $BlockPrint = "" if $ValueNotPrint;
593 my $Commands = <<"GETURLCODE";
598 # Simple, using shell command
599 \$Page = SAFEqx('$CurrentCommand');
601 # Add a BASE tage to the header
602 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
604 # Print the URL value, or return it as a value
611 # As files can get rather large (and binary), you might want to use
612 # some more intelligent reading procedure, e.g.,
614 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
615 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
616 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
618 # while(sysread(URLHANDLE,\$text, 1024) > 0)
622 # close(URLHANDLE) || die "\$!";
623 # However, this doesn't work with the CGIexecute->evaluate() function.
624 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
626 # You can forget the next two variables, they are only needed when
627 # you don't want to use a regular file system (i.e., with open)
628 # but use some kind of database/RAM image for accessing (generating)
631 # Name of the environment variable that contains the file contents
632 # when reading directly from Database/RAM. When this environment variable,
633 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
634 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
635 # Uncomment the following if you want to force the use of the data access code
636 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
638 # Name of the environment variable that contains the RAM access perl
639 # code needed to read additional "files", i.e.,
640 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
641 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
642 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
644 # You can, of course, fill this yourself, e.g.,
645 # $ENV{$CGI_DATA_ACCESS_CODE} =
646 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
651 # Suppress error messages, this can be changed for debugging or error-logging
652 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
654 # SPECIAL: Remove Comments, security, etc. if the command line is
655 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
656 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
658 # If CGIscriptor is used from the command line, the command line
659 # arguments are interpreted as the file (1st) and the Query String (rest).
661 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
662 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
665 # Handle bail-outs in a user definable way.
666 # Catch Die and replace it with your own function.
667 # Ends with a call to "die $_[0];"
669 sub dieHandler
# ($ErrorCode, "Message", @_) -> DEAD
671 my $ErrorCode = shift;
672 my $ErrorMessage = shift;
674 # Place your own reporting functions here
676 # Now, kill everything (default)
677 print STDERR
"$ErrorCode: $ErrorMessage\n";
682 # End of optional user configuration
683 # (note: there is more non-essential user configuration below)
685 if(grep(/\-\-help/i, @ARGV))
687 print << 'ENDOFPREHELPTEXT2';
689 ###############################################################################
691 # Author and Copyright (c):
692 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
695 # Institute of Phonetic Sciences & IFOTT/ACLS
696 # University of Amsterdam
697 # Email: R.J.J.H.vanSon@gmail.com
698 # Email: R.J.J.H.vanSon@gmail.com
699 # WWW : http://www.fon.hum.uva.nl/rob/
701 # License for use and disclaimers
703 # CGIscriptor merges plain ASCII HTML files transparantly
704 # with CGI variables, in-line PERL code, shell commands,
705 # and executable scripts in other scripting languages.
707 # This program is free software; you can redistribute it and/or
708 # modify it under the terms of the GNU General Public License
709 # as published by the Free Software Foundation; either version 2
710 # of the License, or (at your option) any later version.
712 # This program is distributed in the hope that it will be useful,
713 # but WITHOUT ANY WARRANTY; without even the implied warranty of
714 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
715 # GNU General Public License for more details.
717 # You should have received a copy of the GNU General Public License
718 # along with this program; if not, write to the Free Software
719 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
723 # Rob van Son (R.J.J.H.vanSon@gmail.com)
724 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
726 #######################################################
729 #######################################################>>>>>>>>>>Start Remove
731 # You can skip the following code, it is an auto-splice
734 # Construct a slimmed down version of CGIscriptor
735 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
737 if($TrimDownCGIscriptor)
739 open(CGISCRIPTOR
, "<CGIscriptor.pl")
740 || dieHandler
(1, "<CGIscriptor.pl not slimmed down: $!\n");
742 my $SKIPComments = 0;
751 $SKIPtext = 1 if /[\>]{10}Start Remove/;
752 $SKIPComments = 1 if $SKIPtext == 1;
755 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
757 ++$PrintCount unless $SKIPline;
759 print STDOUT
$_ unless $SKIPline;
762 $SKIPtext = 0 if /[\<]{10}End Remove/;
765 print STDERR
"\# Printed $PrintCount out of $LineCount lines\n";
769 #######################################################
771 if(grep(/\-\-help/i, @ARGV))
773 print << 'ENDOFHELPTEXT';
777 # CGIscriptor merges plain ASCII HTML files transparantly and safely
778 # with CGI variables, in-line PERL code, shell commands, and executable
779 # scripts in many languages (on-line and real-time). It combines the
780 # "ease of use" of HTML files with the versatillity of specialized
781 # scripts and PERL programs. It hides all the specifics and
782 # idiosyncrasies of correct output and CGI coding and naming. Scripts
783 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
784 # files can be ignorant of scripts and the associated values. CGIscriptor
785 # complies with the W3C HTML 4.0 recommendations.
786 # In addition to its use as a WWW embeded CGI processor, it can
787 # be used as a command-line document preprocessor (text-filter).
789 # THIS IS HOW IT WORKS
791 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
792 # using any required CGIparameters and environment variables. It
793 # is optimized to transparantly process HTML files inside a WWW server.
794 # The native language is Perl, but many other scripting languages
797 # CGIscriptor reads text files from the requested input file (i.e., from
798 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
799 # client requesting the service) preceded by the obligatory
800 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
801 # (except for "raw" files which supply their own Content-type message
802 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
804 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
806 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
812 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
816 # construct (anything between []-brackets is optional, other MIME-types
817 # and scripting languages are supported), the embedded script is removed
818 # and both the contents of the source file (i.e., "do 'ScriptSource'")
819 # AND the script are evaluated as a PERL program (i.e., by eval()),
820 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
821 # interpreter. The output of the eval() function takes the place of the
822 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
823 # parameters declared by the CGI attribute are available as simple perl
824 # variables, and can subsequently be made available as variables to other
825 # scripting languages (e.g., bash, python, or lisp).
827 # Example: printing "Hello World"
828 # <HTML><HEAD><TITLE>Hello World</TITLE>
830 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
833 # Save this in a file, hello.html, in the directory you indicated with
834 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
835 # (or to whatever name you use as an alias for CGIscriptor.pl).
836 # This is realy ALL you need to do to get going.
838 # You can use any values that are delivered in CGI-compliant form (i.e.,
839 # the "?name=value" type URL additions) transparently as "$name" variables
840 # in your scripts IFF you have declared them in the CGI attribute of
841 # a META or SCRIPT tag before e.g.:
842 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
843 # [SRC='ScriptSource']">
845 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
846 # [SRC='ScriptSource']>
847 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
848 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
849 # The CGIscriptor script allows you to write ordinary HTML files which will
850 # include dynamic CGI aware (run time) features, such as on-line answers
851 # to specific CGI requests, queries, or the results of calculations.
853 # For example, if you wanted to answer questions of clients, you could write
854 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
855 # that prints out the answer to requests given as arguments. You then write
856 # an HTML page "Respond.html" containing the following fragment:
859 # The Answer to your question
860 # <META CONTENT="text/ssperl; CGI='$Question'">
861 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
863 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
864 # AnswerQuestion($Question);
867 # <FORM ACTION=Respond.html METHOD=GET>
868 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
869 # <INPUT TYPE=SUBMIT VALUE="Ask">
872 # The output could look like the following (in HTML-speak):
875 # The Answer to your question
876 # <h3>What is the capital of the Netherlands?</h3>
880 # <FORM ACTION=Respond.html METHOD=GET>
881 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
882 # <INPUT TYPE=SUBMIT VALUE="Ask">
884 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
885 # it just prints out answers to arguments. Likewise, the text has no
886 # provisions for scripts or CGI like constructs. Also, it is completely
887 # trivial to extend this "program" to use the "Answer" later in the page
888 # to call up other information or pictures/sounds. The final text never
889 # shows any cue as to what the original "source" looked like, i.e.,
890 # where you store your scripts and how they are called.
892 # There are some extra's. The argument of the files called in a SRC= tag
893 # can access the CGI variables declared in the preceding META tag from
894 # the @ARGV array. Executable files are called as:
895 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
896 # The files called from SRC can even be (CGIscriptor) html files which are
897 # processed in-line. Furthermore, the SRC= tag can contain a perl block
898 # that is evaluated. That is,
899 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
900 # will result in the evaluation of "print do {$Question};" and the VALUE
901 # of $Question will be printed. Note that these "SRC-blocks" can be
902 # preceded and followed by other file names, but only a single block is
903 # allowed in a SRC= tag.
905 # One of the major hassles of dynamic WWW pages is the fact that several
906 # mutually incompatible browsers and platforms must be supported. For example,
907 # the way sound is played automatically is different for Netscape and
908 # Internet Explorer, and for each browser it is different again on
909 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
910 # (form-) values to construct email addresses, file names, or database
911 # queries. All Apache WWW-server exploits reported in the media are
912 # based on faulty CGI-scripts that didn't check their user-data properly.
914 # There is no panacee for these problems, but a lot of work and problems
915 # can be saved by allowing easy and transparent control over which
916 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
917 # supplies such a method in the form of a pair of attributes:
918 # IF='...condition..' and UNLESS='...condition...'. When added to a
919 # script tag, the whole block (including the SRC attribute) will be
920 # ignored if the condition is false (IF) or true (UNLESS).
921 # For example, the following block will NOT be evaluated if the value
922 # of the CGI variable FILENAME is NOT a valid filename:
924 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
925 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
929 # (the function CGIsafeFileName(String) returns an empty string ("")
930 # if the String argument is not a valid filename).
931 # The UNLESS attribute is the mirror image of IF.
933 # A user manual follows the HTML 4 and security paragraphs below.
935 ##########################################################################
939 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
940 # the W3C. This means that any software to manage Web sites will be able
941 # to handle CGIscriptor files, as will web agents.
943 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
944 # script type is indicated with TYPE="mime-type", the LANGUAGE
945 # feature is ignored, and a SRC feature is implemented. All CGI specific
946 # features are delegated to the CGI attribute.
948 # However, the behavior deviates from the W3C recommendations at some
949 # points. Most notably:
950 # 0- The scripts are executed at the server side, invissible to the
951 # client (i.e., the browser)
952 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
953 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
954 # when a SRC feature is present.
955 # 3- The SRC attribute reads a list of files.
956 # 4- The files in a SRC attribute are processed according to file type.
957 # 5- The SRC attribute evaluates inline Perl code.
958 # 6- Processed META, DIV, INS tags are removed from the output
960 # 7- All attributes of the processed META tags, except CONTENT, are ignored
961 # (i.e., deleted from the output).
962 # 8- META tags can be placed ANYWHERE in the document.
963 # 9- Through the SRC feature, META tags can have visible output in the
965 # 10- The CGI attribute that declares CGI parameters, can be used
966 # inside the <SCRIPT> tag.
967 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
968 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
970 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
971 # 13- <DIV> tags cannot be nested, DIV tags are not
972 # rendered with new-lines.
973 # 14- The XML style <TAG .... /> is recognized and handled correctly.
974 # (i.e., no content is processed)
976 # The reasons for these choices are:
977 # You can still write completely HTML4 compliant documents. CGIscriptor
978 # will not force you to write "deviant" code. However, it allows you to
979 # do so (which is, in fact, just as bad). The prime design principle
980 # was to allow users to include plain Perl code. The code itself should
981 # be "enhancement free". Therefore, extra features were needed to
982 # supply easy access to CGI and Web site components. For security
983 # reasons these have to be declared explicitly. The SRC feature
984 # transparently manages access to external files, especially the safe
985 # use of executable files.
986 # The CGI attribute handles the declarations of external (CGI) variables
987 # in the SCRIPT and META tag's.
988 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
989 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
991 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
992 # evaluation) were build into the META and SCRIPT tags is part laziness,
993 # part security. The SRC blocks allows more compact documents and easier
994 # debugging. The values of the CGI variables can be immediately screened
995 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
996 # email addresses and file names), and a few commands can be called
997 # without having to add another Perl TAG pair. This is especially important
998 # for documents that require the use of other (more restricted) "scripting"
999 # languages and facilities that lag transparent control structures.
1001 ##########################################################################
1005 # Your WWW site is a few keystrokes away from a few hundred million internet
1006 # users. A fair percentage of these users knows more about your computer
1007 # than you do. And some of these just might have bad intentions.
1009 # To ensure uncompromized operation of your server and platform, several
1010 # features are incorporated in CGIscriptor.pl to enhance security.
1011 # First of all, you should check the source of this program. No security
1012 # measures will help you when you download programs from anonymous sources.
1013 # If you want to use THIS file, please make sure that it is uncompromized.
1014 # The best way to do this is to contact the source and try to determine
1015 # whether s/he is reliable (and accountable).
1017 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
1018 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
1020 # I would like to ask any user who finds bugs that could compromise
1021 # security to report them to me (and any other bug too,
1022 # Email: R.J.J.H.vanSon@gmail.com or ifa@hum.uva.nl).
1027 # The inner workings of the HTML source files are completely hidden
1028 # from the client. Only the HTTP header and the ever changing content
1029 # of the output distinguish it from the output of a plain, fixed HTML
1030 # file. Names, structures, and arguments of the "embedded" scripts
1031 # are invisible to the client. Error output is suppressed except
1032 # during debugging (user configurable).
1034 # 2 Separate directory trees
1035 # Directories containing Inline text and script files can reside on
1036 # separate trees, distinct from those of the HTTP server. This means
1037 # that NEITHER the text files, NOR the script files can be read by
1038 # clients other than through CGIscriptor.pl, UNLESS they are
1039 # EXPLICITELY made available.
1041 # 3 Requests are NEVER "evaluated"
1042 # All client supplied values are used as literal values (''-quoted).
1043 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
1044 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
1045 # supply executable commands. Be sure to AVOID scripts like:
1047 # <META CONTENT="text/ssperl; CGI='$UserValue'">
1048 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
1050 # These are a recipe for disaster. However, the following quoted
1051 # form should be save (but is still not adviced):
1053 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
1055 # A special function, SAFEqx(), will automatically do exactly this,
1056 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
1057 # with $UserValue interpolated. I recommend to use SAFEqx() instead
1058 # of backticks whenever you can. The OS shell scripts inside
1060 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
1062 # are handeld by SAFEqx and automatically ''-quoted.
1064 # 4 Logging of requests
1065 # All requests can be logged separate from the Host server. The level of
1066 # detail is user configurable: Including or excluding the actual queries.
1067 # This allows for the inspection of (im-) proper use.
1069 # 5 Access control: Clients
1070 # The Remote addresses can be checked against a list of authorized
1071 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
1072 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
1073 # HOST name can be (in-) excluded by their IP-address. Client patterns
1074 # containing all numbers and dots are considered IP-addresses, all others
1075 # domain names. No wild-cards or regexp's are allowed, only partial
1077 # Matching of names is done from the back to the front (domain first,
1078 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
1079 # accept or reject all clients from the domain EDU. Matching of
1080 # IP-addresses is done from the front to the back (domain first, i.e.,
1081 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
1082 # exclude all clients whose IP-address starts with 128.
1083 # There are two special symbols: "-" matches HOSTs with no name and "*"
1084 # matches ALL HOSTS/clients.
1085 # For those needing more expressional power, lines starting with
1086 # "-e" are evaluated by the perl eval() function. E.g.,
1087 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
1090 # 6 Access control: Files
1091 # In principle, CGIscriptor could read ANY file in the directory
1092 # tree as discussed in 1. However, for security reasons this is
1093 # restricted to text files. It can be made more restricted by entering
1094 # a global file pattern (e.g., ".html"). This is done by default.
1095 # For each client requesting access, the file pattern(s) can be made
1096 # more restrictive than the global pattern by entering client specific
1097 # file patterns in the Access Control files (see 5).
1098 # For example: if the ACCEPT file contained the lines
1102 # Then all clients could request paths containing "DEMO" or "demo", e.g.
1103 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
1104 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
1105 # "/my/let/file.html", and clients from the local cluster
1106 # 145.18.230.[0-9]+ could access ALL files.
1107 # Again, for those needing more expressional power, lines starting with
1108 # "-e" are evaluated. For instance:
1109 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
1110 # will accept/reject requests for files from the directory "/demo/" from
1111 # clients from the domain '.edu'.
1112 # Path selections starting with ! or 'not' will be inverted. That is:
1114 # Will match all file and path names that do NOT contain '.wav'
1116 # 7 Access control: Server side session tickets
1117 # Specific paths can be controlled by Session Tickets which must be
1118 # present as a SESSIONTICKET=<value> CGI variable in the request. These paths
1119 # are defined in %TicketRequiredPatterns as pairs of:
1120 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html\tExpiration').
1121 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
1122 # "Private/.Session") as files with the exact same name of the SESSIONTICKET
1123 # CGI. The following is an example:
1125 # IPaddress: 127.0.0.1
1126 # AllowedPaths: ^/Private/Name/
1130 # Other content can follow.
1132 # It is adviced that Session Tickets should be deleted
1133 # after some (idle) time. The IP address should be the IP number at login, and
1134 # the SESSIONTICKET will be rejected if it is presented from another IP address.
1135 # AllowedPaths and DeniedPaths are perl regexps. Be careful how they match. Make sure to delimit
1136 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
1137 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
1138 # time the ticket will remain valid after creation (file ctime). Time can be given
1139 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
1140 # None of these need be present, but the Ticket must have a non-zero size.
1142 # Next to Session Tickets, there are two other type of ticket files:
1143 # - LOGIN tickets store information about a current login request
1144 # - PASSWORD ticket store account information to authorize login requests
1146 # 8 Query length limiting
1147 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
1148 # than this limit, the request is rejected. The combined length of the
1149 # Query string and the POST input is checked before any processing is done.
1150 # This will prevent clients from overloading the scripts.
1151 # The actual, combined, Query Size is accessible as a variable through
1152 # $CGI_Content_Length.
1154 # 9 Illegal filenames, paths, and protected directories
1155 # One of the primary security concerns in handling CGI-scripts is the
1156 # use of "funny" characters in the requests that con scripts in executing
1157 # malicious commands. Examples are inserting ';', null bytes, or <newline>
1158 # characters in URL's and filenames, followed by executable commands. A
1159 # special variable $FileAllowedChars stores a string of all allowed
1160 # characters. Any request that translates to a filename with a character
1161 # OUTSIDE this set will be rejected.
1162 # In general, all (readable files) in the DocumentRoot tree are accessible.
1163 # This might not be what you want. For instance, your DocumentRoot directory
1164 # might be the working directory of a CVS project and contain sensitive
1165 # information (e.g., the password to get to the repository). You can block
1166 # access to these subdirectories by adding the corresponding patterns to
1167 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
1168 # will block any request that contains '/CVS/' or:
1169 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
1171 #10 The execution of code blocks can be controlled in a transparent way
1172 # by adding IF or UNLESS conditions in the tags themselves. That is,
1173 # a simple check of the validity of filenames or email addresses can
1174 # be done before any code is executed.
1176 ###############################################################################
1178 # USER MANUAL (sort of)
1180 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1181 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1182 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1183 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1184 # the necessary code is already available in the TAG itself (e.g.,
1185 # using external files). The contents of the directive are executed by
1186 # the PERL eval() and `` functions (in a separate name space). The
1187 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1188 # in the output file. You can use the values that are delivered in
1189 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1190 # transparently as "$name" variables in your directives after they are
1191 # defined in a <META> or <SCRIPT> tag.
1192 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1193 # subsequent <SCRIPT> and <META> results (including the defining
1194 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1195 # behaves like any other, ordinary list and can be manipulated.
1197 # Both GET and POST requests are accepted. These two methods are treated
1198 # equal. Variables, i.e., those values that are determined when a file is
1199 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1200 # in which <name> is the name of the variable and <default> is the value
1201 # used when there is NO current CGI value for <name> (you can use
1202 # white-spaces in $<name>=<default> but really DO make sure that the
1203 # default value is followed by white space or is quoted). Names can contain
1204 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1205 # If the Content-type: is 'multipart/*', the input is treated as a
1206 # MIME multipart message and automatically delimited. CGI variables get
1207 # the "raw" (i.e., undecoded) body of the corresponding message part.
1209 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1210 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1211 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1212 # query string), CGI_Content_Length (the length of the decoded query
1213 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1216 # All these are available when defined in a CGI attribute. All environment
1217 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1218 # and the REMOTE_USER, use, e.g.:
1220 # <SCRIPT TYPE='text/ssperl'>
1221 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1224 # (This will print a "-" if REMOTE_HOST is not known)
1225 # Another way to do this is:
1227 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1228 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1230 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1231 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1233 # This is possible because ALL environment variables are available as
1234 # CGI variables. The environment variables take precedence over CGI
1235 # names in case of a "name clash". For instance:
1236 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1237 # Will print the current HOME directory (environment) irrespective whether
1238 # there is a CGI variable from the query
1239 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1240 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1241 # the values of defined environment variables (e.g., by supplying
1242 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1243 # it would make the use of declared variables insecure. You can still
1244 # access CGI variables after a name clash with
1245 # CGIscriptor::CGIparseValue(<name>).
1247 # Some CGI variables are present several times in the query string
1248 # (e.g., from multiple selections). These should be defined as
1249 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1250 # will contain ALL VARIABLENAME values from the query, or a single
1251 # default value. If there is an ENVIRONMENT variable of the
1252 # same name, it will be used instead of the default AND the query
1253 # values. The corresponding function is
1254 # CGIscriptor::CGIparseValueList(<name>)
1256 # CGI variables collected in a @VARIABLENAME list are unordered.
1257 # When more structured variables are needed, a hash table can be used.
1258 # A variable defined as %VARIABLE=default will collect all
1259 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1260 # the remainder of the name as a key. For instance, %PERSON will
1261 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1262 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1263 # equals 'Alice'. Any default value or environment value will be stored
1264 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1265 # it will be used instead of the default AND the query values. The
1266 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1268 # This method of first declaring your environment and CGI variables
1269 # before being able to use them in the scripts might seem somewhat
1270 # clumsy, but it protects you from inadvertedly printing out the values of
1271 # system environment variables when their names coincide with those used
1272 # in the CGI forms. It also prevents "clients" from supplying CGI
1273 # parameter values for your private variables.
1274 # THIS IS A SECURITY FEATURE!
1277 # NON-HTML CONTENT TYPES
1279 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1280 # message before anything is printed. This has been extended to include
1281 # plain text (.txt) files, for which the Content-type (MIME type)
1282 # 'text/plain' is printed. In all other respects, text files are treated
1283 # as HTML files (this can be switched off by removing '.txt' from the
1284 # $FilePattern variable) . When the content type should be something else,
1285 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1286 # item). CGIscriptor will not print a Content-type message for this file
1287 # type (which must supply its OWN Content-type message). Raw files must
1288 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1293 # CGIscriptor is intended to process HTML and text files only. You can
1294 # create documents of any mime-type on-the-fly using "raw" text files,
1295 # e.g., with the .xmr extension. However, CGIscriptor will not process
1296 # binary files of any type, e.g., pictures or sounds. Given the sheer
1297 # number of formats, I do not have any intention to do so. However,
1298 # an escape route has been provided. You can construct a genuine raw
1299 # (.xmr) text file that contains the perl code to service any file type
1300 # you want. If the global $BinaryMapFile variable contains the path to
1301 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1302 # whenever an unsupported (non-HTML) file type is requested. The path
1303 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1304 # and can be used like any other CGI-variable. Servicing binary files
1305 # then becomes supplying the correct Content-type (e.g., print
1306 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1307 # to STDOUT (e.g., using sysread() and syswrite()).
1312 # All attributes of a META tag are ignored, except the
1313 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1314 # inside the quotes following the CONTENT= indication (white-space is
1315 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1316 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1317 # text/osshell) and a comma or semicolon.
1318 # The quoted string following CGI= contains a white-space separated list
1319 # of declarations of the CGI (and Environment) values and default values
1320 # used when no CGI values are supplied by the query string.
1322 # If the default value is a longer string containing special characters,
1323 # possibly spanning several lines, the string must be enclosed in quotes.
1324 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1325 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1326 # is different from (...)). The outermost pair will always be used and any
1327 # other quotes inside the string are considered to be part of the string
1332 # will result in $Value getting the default value: ['this'
1334 # (NOTE that the newline is part of the default value!).
1336 # Internally, for defining and initializing CGI (ENV) values, the META
1337 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1338 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1339 # These functions can be used inside scripts as
1340 # "CGIscriptor::defineCGIvariable($name, $default)" and
1341 # "CGIscriptor::defineCGIvariableList($name, $default)".
1342 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1344 # The CGI attribute will be processed exactly identical when used inside
1345 # the <SCRIPT> tag. However, this use is not according to the
1346 # HTML 4.0 specifications of the W3C.
1351 # There is a problem when constructing html files containing
1352 # server-side perl scripts with standard HTML tools. These
1353 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1354 # tags. This is quite annoying when you want to use large
1355 # HTML templates where you will fill in values.
1357 # For this purpose, CGIscriptor will read the neutral
1358 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1359 # <INS CLASS="ssperl" ID="varname"></INS>
1360 # tag (in Cascading Style Sheet manner) Note that
1361 # "varname" has NO '$' before it, it is a bare name.
1362 # Any text between these <DIV ...></DIV> or
1363 # <INS ...></INS>tags will be assigned to '$varname'
1364 # as is (e.g., as a literal).
1365 # No processing or interpolation will be performed.
1366 # There is also NO nesting possible. Do NOT nest a
1367 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1368 # DIV tags do ensure a block structure in the final
1369 # rendering (i.e., no empty lines).
1371 # Note that <DIV CLASS="ssperl" ID="varname"/>
1372 # is handled the XML way. No content is processed,
1373 # but varname is defined, and any SRC directives are
1376 # You can use $varname like any other variable name.
1377 # However, $varname is NOT a CGI variable and will be
1378 # completely internal to your script. There is NO
1379 # interaction between $varname and the outside world.
1381 # To interpolate a DIV derived text, you can use:
1382 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1383 # $varname = eval("qq[$varname]"); # Interpolate all values
1385 # The DIV tags will process IF, UNLESS, CGI and
1386 # SRC attributes. The SRC files will be pre-pended to the
1387 # body text of the tag. SRC blocks are NOT executed.
1389 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1391 # It is often necessary to include code-blocks that should be executed
1392 # conditionally, e.g., only for certain browsers or operating system.
1393 # Furthermore, quite often sanity and security checks are necessary
1394 # before user (form) data can be processed, e.g., with respect to
1395 # email addresses and filenames.
1397 # Checks added to the code are often difficult to find, interpret or
1398 # maintain and in general mess up the code flow. This kind of confussion
1400 # Also, for many of the supported "foreign" scripting languages, adding
1401 # these checks is cumbersome or even impossible.
1403 # As a uniform method for asserting the correctness of "context", two
1404 # attributes are added to all supported tags: IF and UNLESS.
1405 # They both evaluate their value and block execution when the
1406 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1407 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1408 # the backslash in the '\>' is removed and only used to differentiate
1409 # this conditional '>' from the tag-closing '>'. For symmetry, the
1410 # backslash in '\<' is also removed. Inside these conditionals,
1411 # ~/ and ./ are expanded to their respective directory root paths.
1413 # For example, the following tag will be ignored when the filename is
1416 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1417 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1421 # The IF and UNLESS values must be quoted. The same quotes are supported
1422 # as with the other attributes. The SRC attribute is ignored when IF and
1423 # UNLESS block execution.
1425 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1428 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1430 # The SRC attribute inside tags accepts a list of filenames and URL's
1431 # separated by "," comma's (or ";" semicolons).
1432 # ALL the variable values defined in the CGI attribute are available
1433 # in @ARGV as if the file or block was executed from the command line,
1434 # in the exact order in which they were declared in the preceding CGI
1437 # First, a SRC={}-block will be evaluated as if the code inside the
1438 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1439 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1440 # Only a single block is evaluated. Note that this is processed less
1441 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1442 # depends on the content-type: Perl for text/ssperl and OS shell for
1443 # text/osshell. For other mime types (scripting languages), anything in
1444 # the source block is put in front of the code block "inside" the tag.
1446 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1447 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1448 # That is, you can actually call executables savely from the SRC tag.
1450 # Third, text files that match the file pattern, used by CGIscriptor to
1451 # check whether files should be processed ($FilePattern), are
1452 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1453 # was inserted in the original source file. Recursions, i.e., calling
1454 # a file inside itself, are blocked. If you need them, you have to code
1455 # them explicitely using "main::ProcessFile($file_path)".
1457 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1458 # "do FileName;'';".
1460 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1461 # 'TELNET://', 'WHOIS://' etc.) are loaded
1462 # and printed. The loading and handling of <BASE> and document header
1463 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1464 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1466 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1467 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1468 # content of the tag to appending the code after the content of the tag
1469 # (POSTFIX). The switches are done in the order in which the PREFIX and
1470 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1471 # in any order with the SRC files. Note that the ORDER of file execution
1472 # is determined for prefixed and postfixed files seperately.
1474 # File paths can be preceded by the URL protocol prefix "file://". This
1475 # is simply STRIPPED from the name.
1479 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1480 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1481 # With QUERY_STRING = "positive=8&negative=22"
1483 # on encountering the lines:
1484 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1485 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1488 # This line will be processed as:
1489 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1491 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1492 # This line will end up printed as:
1493 # "<b>p <= 0.0161</b><p>"
1495 # Note that the META tag itself will never be printed, and is invisible to
1496 # the outside world.
1498 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1499 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1500 # need any content, you can use the <DIV...../> format.
1503 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1505 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1506 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1507 # public directories can be accessed without direct reference to the
1508 # actual paths. Filepaths starting with "./" are replaced by
1509 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1511 # Note: this replacement can seriously affect Perl scripts. Watch
1512 # out for constructs like $a =~ s/aap\./noot./g, use
1513 # $a =~ s@aap\.@noot.@g instead.
1515 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1516 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1517 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1519 # Values not preceded by $, ~/, or ./ are used as literals
1522 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1524 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1525 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1526 # interpolate the script and replace all user-supplied CGI-variables by
1527 # their ''-quoted values (actually, all variables defined in CGI attributes
1528 # are quoted). Other Perl variables are interpolated in a simple fasion,
1529 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1530 # their name=value pairs. Complex references, e.g., @$variable, are all
1531 # evaluated in a scalar context. Quotes should be used with care.
1532 # NOTE: the results of the shell script evaluation will appear in the
1533 # @CGIscriptorResults stack just as any other result.
1534 # All occurrences of $@% that should NOT be interpolated must be
1535 # preceeded by a "\". Interpolation can be switched off completely by
1536 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1537 # (set to 0 or undef to switch interpolation on again)
1539 # <SCRIPT TYPE="text/ssperl">
1540 # $CGIscriptor::NoShellScriptInterpolation = 1;
1544 # RUN TIME TRANSLATION OF INPUT FILES
1546 # Allows general and global conversions of files using Regular Expressions.
1547 # Very handy (but costly) to rewrite legacy pages to a new format.
1548 # Select files to use it on with
1549 # my $TranslationPaths = 'filepattern';
1550 # This is costly. For efficiency, define:
1551 # $TranslationPaths = ''; when not using translations.
1552 # Accepts general regular expressions: [$pattern, $replacement]
1555 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1557 # push(@TranslationTable, ['pattern', 'replacement']);
1558 # e.g. (for Ruby Rails):
1559 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1560 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1563 # my $currentRegExp;
1564 # foreach $currentRegExp (@TranslationTable)
1566 # my ($pattern, $replacement) = @$currentRegExp;
1567 # $$text =~ s!$pattern!$replacement!msg;
1571 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1573 # Adding a MIME-type and an interpreter command to
1574 # %ScriptingLanguages automatically will catch any other
1575 # scripting language in the standard
1576 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1577 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1578 # will actually execute the folowing code in an HTML page
1579 # (ignore 'REMOTE_HOST' for the moment):
1580 # <SCRIPT TYPE="text/sspython">
1582 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1583 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1586 # The script code is NOT interpolated by perl, EXCEPT for those
1587 # interpreters that cannot handle variables themselves.
1588 # Currently, several interpreters are pre-installed:
1590 # Perl test - "text/testperl" => 'perl',
1591 # Python - "text/sspython" => 'python',
1592 # Ruby - "text/ssruby" => 'ruby',
1593 # Tcl - "text/sstcl" => 'tcl',
1594 # Awk - "text/ssawk" => 'awk -f-',
1595 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1596 # "| egrep -v '> |^rep. |^nil\\\$'",
1597 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1598 # "| egrep -v '> \\\$|^NIL'",
1599 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1600 # M4 macro's- "text/ssm4" => 'm4',
1601 # Born shell- "text/sh" => 'sh',
1602 # Bash - "text/bash" => 'bash',
1603 # C-shell - "text/csh" => 'csh',
1604 # Korn shell- "text/ksh" => 'ksh',
1605 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1606 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1607 # REBOL - "text/ssrebol" =>
1608 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1609 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1612 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1613 # that reads Standard Input and writes to standard output. Any extra
1614 # output of interactive interpreters (banners, echo's, prompts)
1615 # should be removed by piping the output through 'tail', 'grep',
1616 # 'sed', or even 'awk' or 'perl'.
1618 # For access to CGI variables there is a special hashtable:
1619 # %ScriptingCGIvariables.
1620 # CGI variables can be accessed in three ways.
1621 # 1. If the mime type is not present in %ScriptingCGIvariables,
1622 # nothing is done and the script itself should parse the relevant
1623 # environment variables.
1624 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1625 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1626 # the script text is interpolated by perl. That is, all $var, @array,
1627 # %hash, and \-slashes are replaced by their respective values.
1628 # 3. In all other cases, the CGI and environment variables are added
1629 # in front of the script according to the format stored in
1630 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1631 # executed for each CGI- or Environment variable defined in the CGI-tag:
1632 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1634 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1635 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1636 # (note that these definitions are not save, the real ones contain '-quotes).
1638 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1641 # The $CGI_VALUE parameters are "shrubed" of all control characters
1642 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1643 # Control characters are replaced by \0<octal ascii value> (the exception
1644 # is \015, the newline, which is replaced by \n) and quotes
1645 # and backslashes by their HTML character
1646 # value (' -> ' ` -> ` " -> " \ -> \ & -> &er;).
1648 # if a client would supply the string value (in standard perl, e.g.,
1649 # \n means <newline>)
1650 # "/dev/null';\nrm -rf *;\necho '"
1651 # it would be processed as
1652 # '/dev/null';\nrm -rf *;\necho ''
1653 # (e.g., sh or bash would process the latter more according to your
1655 # If your intepreter requires different protection measures, you will
1656 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1657 # e.g., $SHRUBcharacterTR{"\'"} = "'";
1659 # Currently, the following definitions are used:
1660 # %ScriptingCGIvariables = (
1661 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1662 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1663 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1664 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1665 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1666 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1667 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1668 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1669 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1670 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1671 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1672 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1673 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1674 # "text/sspraat" => '', # Praat (interpolation)
1675 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1676 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1677 # "text/postgresql" => '', # PostgreSQL (interpolation)
1681 # Four tables allow fine-tuning of interpreter with code that should be
1682 # added before and after each code block:
1684 # Code added before each script block
1685 # %ScriptingPrefix = (
1686 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1687 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1689 # Code added at the end of each script block
1690 # %ScriptingPostfix = (
1691 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1692 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1694 # Initialization code, inserted directly after opening (NEVER interpolated)
1695 # %ScriptingInitialization = (
1696 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1697 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1698 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1699 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1700 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1702 # Cleanup code, inserted before closing (NEVER interpolated)
1703 # %ScriptingCleanup = (
1704 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1705 # "text/sspraat" => 'Quit',
1706 # "text/ssawk" => '};', # Server Side awk scripts
1707 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1708 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1709 # "text/postgresql" => '\q',
1713 # The SRC attribute is NOT magical for these interpreters. In short,
1714 # all code inside a source file or {} block is written verbattim
1715 # to the interpreter. No (pre-)processing or executional magic is done.
1717 # A serious shortcomming of the described mechanism for handling other
1718 # (scripting) languages, with respect to standard perl scripts
1719 # (i.e., 'text/ssperl'), is that the code is only executed when
1720 # the pipe to the interpreter is closed. So the pipe has to be
1721 # closed at the end of each block. This means that the state of the
1722 # interpreter (e.g., all variable values) is lost after the closing of
1723 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1724 # all values and definitions.
1726 # APPLICATION MIME TYPES
1728 # To ease some important auxilliary functions from within the
1729 # html pages I have added them as MIME types. This uses
1730 # the mechanism that is also used for the evaluation of
1731 # other scripting languages, with interpolation of CGI
1732 # parameters (and perl-variables). Actually, these are
1733 # defined exactly like any other "scripting language".
1735 # text/ssdisplay: display some (HTML) text with interpolated
1736 # variables (uses `cat`).
1737 # text/sslogfile: write (append) the interpolated block to the file
1738 # mentioned on the first, non-empty line
1739 # (the filename can be preceded by 'File: ',
1740 # note the space after the ':',
1741 # uses `awk .... >> <filename>`).
1742 # text/ssmailto: send email directly from within the script block.
1743 # The first line of the body must contain
1744 # To:Name@Valid.Email.Address
1745 # (note: NO space between 'To:' and the email adres)
1746 # For other options see the mailto man pages.
1747 # It works by directly sending the (interpolated)
1748 # content of the text block to a pipe into the
1749 # Linux program 'mailto'.
1751 # In these script blocks, all Perl variables will be
1752 # replaced by their values. All CGI variables are cleaned before
1753 # they are used. These CGI variables must be redefined with a
1754 # CGI attribute to restore their original values.
1755 # In general, this will be more secure than constructing
1756 # e.g., your own email command lines. For instance, Mailto will
1757 # not execute any odd (forged) email addres, but just stops
1758 # when the email address is invalid and awk will construct
1759 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1760 # as a "valid" UNIX filename). Note that it will also gladly
1761 # store this file anywhere (/../../../etc/passwd will work!).
1762 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1765 # SHELL SCRIPT PIPING
1767 # If a shell script starts with the UNIX style "#! <shell command> \n"
1768 # line, the rest of the shell script is piped into the indicated command,
1770 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1772 # In many ways this is equivalent to the MIME-type profiling for
1773 # evaluating other scripting languages as discussed above. The
1774 # difference breaks down to convenience. Shell script piping is a
1775 # "raw" implementation. It allows you to control all aspects of
1776 # execution. Using the MIME-type profiling is easier, but has a
1777 # lot of defaults built in that might get in the way. Another
1778 # difference is that shell script piping uses the SAFEqx() function,
1779 # and MIME-type profiling does not.
1781 # Execution of shell scripts is under the control of the Perl Script blocks
1782 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1783 # blocks can be simulated easily. You can switch to a different shell,
1784 # e.g. tcl, completely by executing the following Perl commands inside
1787 # <SCRIPT TYPE="text/ssperl">
1788 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1789 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1790 # $CGIscriptor::NoShellScriptInterpolation = 1;
1793 # After this script is executed, CGIscriptor will parse scripts of
1794 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1795 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1796 # The crucial function is :
1797 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1798 # After executing this function, all shell scripts AND all
1799 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1800 # of RedirectShellScript is empty, e.g., '', the original (default)
1803 # The standard output, STDOUT, of any pipe is send to the client.
1804 # Currently, you should be carefull with quotes in such a piped script.
1805 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1806 # As a result, you do not have access to the output of any piped (#!)
1807 # process! If you want such access, execute
1808 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1810 # <SCRIPT TYPE="text/ssperl">
1811 # $resultvar = SAFEqx('echo "script"|command');
1814 # Safety is never complete. Although SAFEqx() prevents some of the
1815 # most obvious forms of attacks and security slips, it cannot prevent
1816 # them all. Especially, complex combinations of quotes and intricate
1817 # variable references cannot be handled safely by SAFEqx. So be on
1821 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1823 # All PERL scripts are evaluated inside a PERL package. This package
1824 # has a separate name space. This isolated name space protects the
1825 # CGIscriptor.pl program against interference from user code. However,
1826 # some variables, e.g., $_, are global and cannot be protected. You are
1827 # advised NOT to use such global variable names. You CAN write
1828 # directives that directly access the variables in the main program.
1829 # You do so at your own risk (there is definitely enough rope available
1830 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1831 # you change its private variables during run time. The PERL code
1832 # directives are used as in:
1833 # $Result = eval($directive); print $Result;'';
1834 # ($directive contains all text between <SCRIPT></SCRIPT>).
1835 # That is, the <directive> is treated as ''-quoted string and
1836 # the result is treated as a scalar. To prevent the VALUE of the code
1837 # block from appearing on the client's screen, end the directive with
1838 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1839 # eval(), blocks, and subroutines, but only as a scalar.
1841 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1842 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1843 # (e.g., for "my $var;" declarations). This means that values assigned
1844 # to a PERL variable can be used throughout the document unless they
1845 # were declared with "my". The following will actually work as intended
1846 # (note that the ``-quotes in this example are NOT evaluated, but used
1847 # as simple quotes):
1849 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1851 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1853 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1855 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1856 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1857 # construct will print the elements of $String separated by commas, leaving
1858 # out the first element, i.e., $List[0].
1860 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1861 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1862 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1863 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1864 # s@<regexp>.@<replacement>.@g instead.
1867 # SERVER SIDE SESSIONS AND ACCESS CONTROL (LOGIN)
1869 # An infrastructure for user acount authorization and file access control
1870 # is available. Each request is matched against a list of URL path patterns.
1871 # If the request matches, a Session Ticket is required to access the URL.
1872 # This Session Ticket should be present as a CGI parameter or Cookie, eg:
1874 # CGI: SESSIONTICKET=<value>
1875 # Cookie: CGIscriptorSESSION=<value>
1877 # The example implementation stores Session Tickets as files in a local
1878 # directory. To create Session Tickets, a Login request must be given
1879 # with a LOGIN=<value> CGI parameter, a user name and a (doubly hashed)
1880 # password. The user name and (singly hashed) password are stored in a
1881 # PASSWORD ticket with the same name as the user account (name cleaned up
1884 # The example session model implements 4 functions:
1886 # The password is hashed with the user name and server side salt, and then
1887 # hashed with the REMOTE_HOST and a random salt. Client and Server both
1888 # perform these actions and the Server only grants access if restults are
1889 # the same. The server side only stores the password hashed with the user
1890 # name and server side salt. Neither the plain password, nor the hashed
1891 # password is ever exchanged. Only values hashed with the one-time salt
1894 # For every access to a restricted URL, the Session Ticket is checked before
1895 # access is granted. There are three session modes. The first uses a fixed
1896 # Session Ticket that is stored as a cookie value in the browser (actually,
1897 # as a sessionStorage value). The second uses only the IP address at login
1898 # to authenticate requests. The third
1899 # is a Challenge mode, where the client has to calculate the value of the
1900 # next one-time Session Ticket from a value derived from the password and
1903 # A new password is hashed with the user name and server side salt, and
1904 # then encrypted (XORed)
1905 # with the old password hashed with the user name and salt. That value is
1906 # exchanged and XORed with the stored old hashed(password+username+salt).
1907 # Again, the stored password value is never exchanged unencrypted.
1909 # The text of a new account (Type: PASSWORD) file is constructed from
1910 # the new username (CGI: NEWUSERNAME, converted to lowercase) and
1911 # hashed new password (CGI: NEWPASSWORD). The same process is used to encrypt
1912 # the new password as is used for the Password Change function.
1913 # Again, the stored password value is never exchanged unencrypted.
1914 # Some default setting are encoded. For display in the browser, the new password
1915 # is reencrypted (XORed) with a special key, the old password hash
1916 # hashed with a session specific random hex value sent initially with the
1917 # session login ticket ($RANDOMSALT).
1918 # For example for user "NewUser" and password "NewPassword" with filename
1923 # Password: 19afeadfba8d5dcd252e157fafd3010859f8762b87682b6b6cdb3e565194fa91
1924 # IPaddress: 127\.0\.0\.1
1925 # AllowedPaths: ^/Private/[\w\-]+\.html?
1926 # AllowedPaths: ^/Private/newuser/
1927 # Salt: e93cf858a1d5626bf095ea5c25df990dfa969ff5a5dc908b22c9a5229b525f65
1929 # Date: Fri Jun 29 12:46:22 2012
1931 # Signature: 676c35d3aa63540293ea5442f12872bfb0a22665b504f58f804582493b6ef04e
1933 # The password is created with the commands:
1935 # printf '%s' 'NewPasswordnewuser970e68017413fb0ea84d7fe3c463077636dd6d53486910d4a53c693dd4109b1a'|shasum -a 256
1937 # If the CPAN mudule Digest is installed, it is used instead of the commands.
1938 # However, the password account files are protected against unauthorized change.
1939 # To obtain a valid Password account, the following command should be given:
1941 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
1942 # masterkey='Sherlock investigates oleander curry in Bath' \
1943 # password='NewPassword' \
1944 # Private/.Passwords/newuser
1949 # The session authentication mechanism is based on the exchange of ticket
1950 # identifiers. A ticket identifier is just a string of characters, a name
1951 # or a random 64 character hexadecimal string. Authentication is based
1952 # on a (password derived) shared secret and the ability to calculate ticket
1953 # identifiers from this shared secret. Ticket identifiers should be
1954 # "safe" filenames (except user names). There are four types of tickets:
1955 # PASSWORD: User account descriptors, including a user name and password
1956 # LOGIN: Temporary anonymous tickets used during login
1957 # IPADDRESS: Authentication tokens that allow access based on the IP address of the request
1958 # SESSION: Reusable authentication tokens
1959 # CHALLENGE: One-time authentication tokens
1960 # All tickets can have an expiration date in the form of a time duration
1961 # from creation, in seconds, minutes, hours, or days (+duration[smhd]).
1962 # An absolute time can be given in seconds since the epoch of the server host.
1963 # Note that expiration times of CHALLENGE authentication tokens are calculated
1964 # from the last access time. Accounts can include a maximal lifetime
1965 # for session tickets (MaxLifetime).
1967 # A Login page should create a LOGIN ticket file locally and send a
1968 # server specific salt, a Random salt, and a LOGIN ticket
1969 # identifier. The server side compares the username and hashed password,
1970 # actually hashed(hashed(password+serversalt)+Random salt) from the client with
1971 # the values it calculates from the stored Random salt from the LOGIN
1972 # ticket and the hashed(password+serversalt) from the PASSWORD ticket. If
1973 # successful, a new SESSION ticket is generated as a (double) hash sum of the stored
1974 # password and the LOGIN ticket, i.e.
1975 # LoginTicket = hashed(hashed(password+serversalt)+REMOTE_HOST + Random salt) and
1976 # SessionTicket = hashed(hashed(LoginTicket).LoginTicket). This SESSION
1977 # ticket should also be generated by the client and stored as
1978 # sessionStorage and cookie values as needed. The Username, IP address
1979 # and Path are available as $LoginUsername, $LoginIPaddress, and
1980 # $LoginPath, respectively.
1982 # The CHALLENGE protocol stores the single hashed version of the SESSION tickets.
1983 # However, this value is not exchanged, but kept secret in the JavaScript
1984 # sessionStorage object. Instead, every page returned from the
1985 # server will contain a one-time Challenge value ($CHALLENGETICKET) which
1986 # has to be hashed with the stored value to return the current ticket
1989 # In the current example implementation, all random values are created as
1990 # full, 256 bit SHA256 hash values (Hex strings) of 64 bytes read from
1996 # A limited level of authorization tuning is build into the login system.
1997 # Each account file (PASSWORD ticket file) can contain a number of
1998 # Capabilities lines. These control special priveliges. The
1999 # Capabilities can be checked inside the HTML pages as part of the
2000 # ticket information. Two privileges are handled internally:
2001 # CreateUser and VariableREMOTE_ADDR.
2002 # CreateUser allows the logged in user to create a new user account.
2003 # With VariableREMOTE_ADDR, the session of the logged in user is
2004 # not limited to the Remote IP address from which the inital log-in took
2005 # place. Sessions can hop from one apparant (proxy) IP address to another,
2006 # e.g., when using Tor. Any IPaddress patterns given in the PASSWORD
2007 # ticket file remain in effect during the session. For security reasons,
2008 # the VariableREMOTE_ADDR capability is only effective if the session
2009 # type is CHALLENGE.
2012 # Security considerations with Session tickets
2014 # For strong security, please use end-to-end encryption. This can be
2015 # achieved using a VPN (Virtual Private Network), SSH tunnel, or a HTTPS
2016 # capable server with OpenSSL. The session ticket system of CGIscriptor.pl
2017 # is intended to be used as a simple authentication mechanism WITHOUT
2018 # END-TO-END ENCRYPTION. The authenticating mechanism tries to use some
2019 # simple means to protect the authentication process from eavesdropping.
2020 # For this it uses a secure hash function, SHA256. For all practial purposes,
2021 # it is impossible to "decrypt" a SHA256 sum. But this login scheme is
2022 # only as secure as your browser. Which, in general, is not very secure.
2024 # One fundamental weakness of the implemented procedure is that the Client
2025 # obtains the code to encrypt the passwords from the server. It is the JavaScript
2026 # code in the HTML pages. An attacker who could place himself between Server
2027 # and Client, a man in the middle attack (MITM), could change the code to
2028 # reveal the plaintext password and other information. There is no
2029 # real protection against this attack without end-to-end encryption and
2030 # authentication. A simple, but rather cumbersome, way to check for such
2031 # attacks would be to store known good copys of the pages (downloaded
2032 # with a browser or automatically with curl or wget) and
2033 # then use other tools to download new pages at random intervals and compare
2034 # them to the old pages. For instance, the following line would remove
2035 # the variable ticket codes and give a fixed SHA256 sum for the original
2036 # Login.html page+code:
2037 # curl http://localhost:8080/Private/index.html | \
2038 # sed 's/=\"[a-z0-9]\{64\}\"/=""/g' | shasum -a 256
2039 # A simple diff command between old and new files should give only
2040 # differences in half a dozen lines, where only hexadecimal salt values
2041 # will actually differ.
2043 # A sort of solution for the MITM attack problem that might protect at
2044 # least the plaintext password would be to run a trusted web
2045 # page from local storage to handle password input. The solution would be
2046 # to add a hidden iFrame tag loading the untrusted page from the URL and
2047 # extract the needed ticket and salt values. Then run the stored, trusted,
2048 # code with these values. It is not (yet) possible to set the
2049 # required session storage inside the browser, so this method only works
2050 # for IPADDRESS sessions and plain SESSION tickets. There are many
2051 # security problems with this "solution".
2053 # If you are able to ascertain the integrity of the login page using any
2054 # of the above methods, you can check whether the IP address seen by the
2055 # login server is indeed the IP address of your computer. The IP address
2056 # of the REMOTE_HOST (your visible IP address) is part of the login
2057 # "password". It is stored in the login page as a CLIENTIPADDRESS. It can
2058 # can be inspected by clicking the "Check IP address" box. Provided the
2059 # MitM attacker cannot spoof your IP address, you can ensure that the login
2060 # server sees your IP address and not that of an attacker.
2062 # Humans tend to reuse passwords. A compromise of a site running
2063 # CGIscriptor.pl could therefore lead to a compromise of user accounts at
2064 # other sites. Therefore, plain text passwords are never stored, used, or
2065 # exchanged. Instead, the plain password and user name are "encrypted" with
2066 # a server site salt value. Actually, all are concatenated and hashed
2067 # with a one-way secure hash function (SHA256) into a single string.
2068 # Whenever the word "password" is used, this hash sum is meant. Note that
2069 # the salts are generated from /dev/urandom. You should check whether the
2070 # implementation of /dev/urandom on your platform is secure before
2071 # relying on it. This might be a problem when running CGIscriptor under
2072 # Cygwin on MS Windows.
2073 # Note: no attempt is made to slow down the password hash, so bad
2074 # passwords can be cracked by brute force
2076 # As the (hashed) passwords are all that is needed to identify at the site,
2077 # these should not be stored in this form. A site specific passphrase
2078 # can be entered as an environment variable ($ENV{'CGIMasterKey'}). This
2079 # phrase is hashed with the server site salt and the result is hashed with
2080 # the user name and then XORed with the password when it is stored. Also, to
2081 # detect changes to the account (PASSWORD) and session tickets, a
2082 # (HMAC) hash of some of the contents of the ticket with the server salt and
2083 # CGIMasterKey is stored in each ticket.
2085 # Creating a valid (hashed) password, encrypt it with the CGIMasterKey and
2086 # construct a signature of the ticket are non-trivial. This has to be redone
2087 # with every change of the ticket file or CGIMasterKey change. CGIscriptor
2088 # can do this from the command line with the command:
2090 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
2091 # masterkey='Sherlock investigates oleander curry in Bath' \
2092 # password='There is no password like more password' \
2095 # CGIscriptor will exit after this command with the first option being
2096 # --managelogin. Options have the form:
2098 # salt=[file or string]
2099 # Server salt value to use io the value
2100 # stored in the ticket file. Will replace the stored value if a new
2101 # password is given. If you change the server salt, you have to
2102 # reset all the passwords. There is absolutely no procedure known
2103 # to recover plaintext passwords, except asking the account holders.
2104 # You are strongly adviced to make a backup before you apply such a change
2105 # masterkey=[file or string]
2106 # CGIMasterKey used to read and decrypt the ticket
2107 # newmasterkey=[file or string]
2108 # CGIMasterKey used to encrypt, sign,
2109 # and write the ticket. Defaults to the masterkey. If you change
2110 # the masterkey, you will have to reset all the accounts. You are strongly
2111 # adviced to make a backup before you apply such a change
2112 # password=[file or string]
2113 # New plaintext password
2115 # When the value of an option is a existing file path, the first line of
2116 # that file is used. Options are followed by one or more paths plus names
2117 # of existing ticket files. Each password option is only used for a single
2118 # ticket file. It is most definitely a bad idea to use a password that is
2119 # identical to an existing filepath, as the file will be read instead. Be
2120 # aware that the name of the file should be a cleaned up version of the
2121 # Username. This will not be checked.
2123 # For the authentication and a change of password, the (old) password
2124 # is used to "encrypt" a random one-time token or the new password,
2125 # respectively. For authentication, decryption is not needed, so a secure
2126 # hash function (SHA256) is used to create a one-way hash sum "encryption".
2127 # A new password must be decrypted. New passwords are encryped by XORing
2128 # them with the old password.
2130 # Strong Passwords: It is so easy
2131 # If you only could see what you are typing
2133 # Your password might be vulnerable to brute force guessing
2134 # (https://en.wikipedia.org/wiki/Brute_force_attack).
2135 # Protections against such attacks are costly in terms of code
2136 # complexity, bugs, and execution time. However, there is a very
2137 # simple and secure counter measure. See the XKCD comic
2138 # (http://xkcd.com/936/). The phrase, "There is no password like more
2139 # password" would be both much easier to remember, and still stronger
2140 # than "h4]D%@m:49", at least before this phrase was pasted as an
2141 # example on the Internet.
2143 # For the procedures used at this site, a basic computer setup can
2144 # check in the order of a billion passwords per second. You need a
2145 # password (or phrase) strength in the order of 56 bits to be a
2146 # little secure (one year on a single computer). Please be so kind
2147 # and add the name of your favorite flower, dish, fictional
2148 # character, or small town to your password. Say, Oleander, Curry,
2149 # Sherlock, or Bath, UK (each adds ~12 bits) or even the phrase "Sherlock
2150 # investigates oleander curry in Bath" (adds > 56 bits, note that
2151 # oleander is poisonous, so do not try this curry at home). That
2152 # would be more effective than adding a thousand rounds of encryption.
2153 # Typing long passwords without seeing what you are typing is
2154 # problematic. So a button should be included to make password
2160 # Client side JavaScript code definitions. Variable names starting with '$'
2161 # are CGIscriptor CGI variables. Some of the hashes could be strengthened
2162 # by switching to HMAC signatures. However, the security issues of
2163 # maintaining parallel functions for HMAC in both Perl and Javascript seem
2164 # to be more serious than the attack vectors against the hashes. But HMAC
2165 # is indeed used for the ticket signatures.
2168 # HashPlaintextPassword() {
2169 # var plaintextpassword = document.getElementById('PASSWORD');
2170 # var serversalt = document.getElementById('SERVERSALT');
2171 # var username = document.getElementById('CGIUSERNAME');
2172 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2174 # var randomsalt = $RANDOMSALT; // From CGIscriptor
2175 # var loginticket = $LOGINTICKET; // From CGIscriptor
2176 # // Hash plaintext password
2177 # var password = HashPlaintextPassword();
2178 # // Authorize login
2179 # var hashedpassword = hex_sha256(randomsalt+password);
2181 # var sessionticket = hex_sha256(loginticket+password);
2182 # sessionStorage.setItem("CGIscriptorPRIVATE", sessionticket);
2183 # // Secretkey for encrypting new passwords, acts like a one-time pad
2184 # // Is set anew with every login, ie, also whith password changes
2185 # // and for each create new user request
2186 # var secretkey = hex_sha256(password+loginticket+randomsalt);
2187 # sessionStorage.setItem("CGIscriptorSECRET", secretkey);
2189 # // For a SESSION type request
2190 # sessionticket = hex_sha256(sessionStorage.getItem("CGIscriptorPRIVATE"));
2191 # createCookie("CGIscriptorSESSION",sessionticket, 0, "");
2193 // For a CHALLENGE type request
2194 # var sessionset = "$CHALLENGETICKET"; // From CGIscriptor
2195 # var sessionkey = sessionStorage.getItem("CGIscriptorPRIVATE");
2196 # sessionticket = hex_sha256(sessionset+sessionkey);
2197 # createCookie("CGIscriptorCHALLENGE",sessionticket, 0, "");
2199 # // For transmitting a new password
2200 # HashPlaintextNewPassword() {
2201 # var plaintextpassword = document.getElementById('NEWPASSWORD');
2202 # var serversalt = document.getElementById('SERVERSALT');
2203 # var username = document.getElementById('NEWUSERNAME');
2204 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2207 # var newpassword = document.getElementById('NEWPASSWORD');
2208 # var newpasswordrep = document.getElementById('NEWPASSWORDREP');
2209 # // Hash plaintext password
2210 # newpassword.value = HashPlaintextNewPassword();
2211 # var secretkey = sessionStorage.getItem("CGIscriptorSECRET");
2213 # var encrypted = XOR_hex_strings(secretkey, newpassword.value);
2214 # newpassword.value = encrypted;
2215 # newpasswordrep.value = encrypted;
2217 # // XOR of hexadecimal strings of equal length
2218 # function XOR_hex_strings(hex1, hex2) {
2219 # var resultHex = "";
2220 # var maxlength = Math.max(hex1.length, hex2.length);
2222 # for(var i=0; i < maxlength; ++i) {
2223 # var h1 = hex1.charAt(i);
2225 # var h2 = hex2.charAt(i);
2227 # var d1 = parseInt(h1,16);
2228 # var d2 = parseInt(h2,16);
2229 # var resultD = d1^d2;
2230 # resultHex = resultHex+resultD.toString(16);
2235 # Password encryption based on $ENV{'CGIMasterKey'}.
2236 # Server side Perl code:
2238 # # Password encryption
2239 # my $masterkey = $ENV{'CGIMasterKey'}
2240 # my $hash1 = hash_string($masterkey.$serversalt);
2241 # my $CryptKey = hash_string($username.$hash1);
2242 # $password = XOR_hex_strings($CryptKey,$password);
2244 # # Key for HMAC signing
2245 # my $hash1 = hash_string($masterkey.$serversalt);
2246 # my $HMACKey = hash_string($username.$hash1);
2252 # A CGIscriptor package is attached to the bottom of this file. With
2253 # this package you can personalize your version of CGIscriptor by
2254 # including often used perl routines. These subroutines can be
2255 # accessed by prefixing their names with CGIscriptor::, e.g.,
2256 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
2257 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
2259 # It already contains some useful subroutines for Document Management.
2260 # As it is a separate package, it has its own namespace, isolated from
2261 # both the evaluator and the main program. To access variables from
2262 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
2264 # Currently, the following functions are implemented
2265 # (precede them with CGIscriptor::, see below for more information)
2266 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
2267 # Is used by text/osshell Shell scripts. Protects all CGI
2268 # (client-supplied) values with single quotes before executing the
2269 # commands (one of the few functions that also works WITHOUT CGIscriptor::
2271 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
2272 # Is used by the META tag to define and initialize CGI and ENV
2273 # name/value pairs. Tries to obtain an initializing value from (in order):
2276 # The default value given (if any)
2277 # (one of the few functions that also works WITHOUT CGIscriptor::
2279 # - CGIsafeFileName (FileName) -> FileName or ""
2280 # Check a string against the Allowed File Characters (and ../ /..).
2281 # Returns an empty string for unsafe filenames.
2282 # - CGIsafeEmailAddress (Email) -> Email or ""
2283 # Check a string against correct email address pattern.
2284 # Returns an empty string for unsafe addresses.
2285 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
2286 # Open a named PIPE for SAFEqx to receive ALL shell scripts
2287 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
2288 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
2289 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
2290 # Extract the value of a CGI variable from the global or a private
2291 # URL-encoded query (multipart POST raw, NOT decoded)
2292 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
2293 # -> List of decoded values
2294 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
2295 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
2296 # Extract the header of a multipart CGI variable from the global or a private
2297 # URL-encoded query ("" when not a multipart variable or absent)
2298 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
2299 # Decode the complete global URL-encoded query or a private
2301 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
2302 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
2303 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
2304 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
2305 # all documents, e.g., ListDocs("/*", "dl");.
2306 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
2307 # local links starting from a given document, e.g.,
2308 # HTMLdocTree("/Welcome.html", "dl");
2311 # THE RESULTS STACK: @CGISCRIPTORRESULTS
2313 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
2314 # META tag, all subsequent SCRIPT and META results are pushed
2315 # on the @CGIscriptorResults stack. This list is just another
2316 # Perl variable and can be used and manipulated like any other list.
2317 # $CGIscriptorResults[-1] is always the last result.
2318 # This is only of limited use, e.g., to use the results of an OS shell
2319 # script inside a Perl script. Will NOT contain the results of Pipes
2320 # or code from MIME-profiling.
2323 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
2325 # $CGI_HOME - The DocumentRoot directory
2326 # $CGI_Decoded_QS - The complete decoded Query String
2327 # $CGI_Content_Length - The ACTUAL length of the Query String
2328 # $CGI_Date - Current date and time
2329 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
2330 # $CGI_Time - Current Time
2331 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
2333 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
2334 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
2337 # USEFULL CGI ENVIRONMENT VARIABLES
2339 # Variables accessible (in APACHE) as $ENV{<name>}
2340 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
2342 # QUERY_STRING - The query part of URL, that is, everything that follows the
2344 # PATH_INFO - Extra path information given after the script name
2345 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
2346 # (This doesn't always make sense.)
2347 # REMOTE_USER - If the server supports user authentication, and the script is
2348 # protected, this is the username they have authenticated as.
2349 # REMOTE_HOST - The hostname making the request. If the server does not have
2350 # this information, it should set REMOTE_ADDR and leave this unset
2351 # REMOTE_ADDR - The IP address of the remote host making the request.
2352 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
2353 # variable will be set to the remote user name retrieved from
2354 # the server. Usage of this variable should be limited to logging
2356 # AUTH_TYPE - If the server supports user authentication, and the script
2357 # is protected, this is the protocol-specific authentication
2358 # method used to validate the user.
2359 # CONTENT_TYPE - For queries which have attached information, such as HTTP
2360 # POST and PUT, this is the content type of the data.
2361 # CONTENT_LENGTH - The length of the said content as given by the client.
2362 # SERVER_SOFTWARE - The name and version of the information server software
2363 # answering the request (and running the gateway).
2364 # Format: name/version
2365 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
2366 # would appear in self-referencing URLs
2367 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
2368 # server complies. Format: CGI/revision
2369 # SERVER_PROTOCOL - The name and revision of the information protocol this
2370 # request came in with. Format: protocol/revision
2371 # SERVER_PORT - The port number to which the request was sent.
2372 # REQUEST_METHOD - The method with which the request was made. For HTTP,
2373 # this is "GET", "HEAD", "POST", etc.
2374 # SCRIPT_NAME - A virtual path to the script being executed, used for
2375 # self-referencing URLs.
2376 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
2377 # HTTP headers. Other protocols may need to get this
2378 # information from elsewhere. Each item in this list should
2379 # be separated by commas as per the HTTP spec.
2380 # Format: type/subtype, type/subtype
2381 # HTTP_USER_AGENT - The browser the client is using to send the request.
2382 # General format: software/version library/version.
2385 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
2387 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
2388 # a line like the following to your srm.conf file (Apache example):
2390 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
2392 # URL's that refer to http://www.your.address/SHTML/... will now be handled
2393 # by CGIscriptor.pl, which can use a private directory tree (default is the
2394 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
2396 # If your hosting ISP won't let you add ScriptAlias lines you can use
2397 # the following "rewrite"-based "scriptalias" in .htaccess
2398 # (from Gerd Franke)
2402 # RewriteCond %{REQUEST_FILENAME} .html$
2403 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
2404 # RewriteCond %{REQUEST_FILENAME} -f
2405 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
2407 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
2408 # in the url and where the file "path/filename.html" exists is redirected
2409 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
2410 # The user configuration should get the same path-level as the
2413 # # Just enter your own directory path here
2414 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
2415 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
2417 # If this .htaccess goes in a specific directory, the path to this
2418 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
2420 # The CGIscriptor file contains all documentation as comments. These
2421 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
2422 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
2423 # CGIscriptor.pl, lacking documentation, most comments, access control,
2424 # example functions etc. (but still with the copyright notice and some
2425 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
2426 # command line with the '-slim' command line argument, e.g.,
2428 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
2430 # CGIscriptor.pl can be run from the command line with <path> and <query> as
2431 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
2432 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
2433 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
2434 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
2435 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
2436 # $ENV{QUERY_STRING}).
2438 # Using the command line execution option, CGIscriptor.pl can be used as a
2439 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
2442 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
2444 # This command line will produce a STATIC file with the DYNAMIC content of
2445 # MyDocument.html "interpolated".
2447 # This option would be very dangerous when available over the internet.
2448 # If someone could sneak a 'http://www.your.domain/-' URL past your
2449 # server, CGIscriptor could EXECUTE any POSTED contend.
2450 # Therefore, for security reasons, STDIN will NOT be read
2451 # if ANY of the HTTP server environment variables is set (e.g.,
2452 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
2453 # HTTP_USER_AGENT, REMOTE_ADDR).
2454 # This block on processing STDIN on HTTP requests can be lifted by setting
2455 # $BLOCK_STDIN_HTTP_REQUEST = 0;
2456 # In the security configuration. Butbe carefull when doing this.
2457 # It can be very dangerous.
2459 # Running demo's and more information can be found at
2460 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
2462 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
2463 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
2464 # demonstrates its use.
2467 # PROCESSING NON-FILESYSTEM DATA
2469 # Normally, HTTP (WWW) requests map onto file that can be accessed
2470 # using the perl open() function. That is, the web server runs on top of
2471 # some directory structure. However, we can envission (and put to good
2472 # use) other systems that do not use a normal file system. The whole CGI
2473 # was developed to make dynamic document generation possible.
2475 # A special case is where we want to have it both: A normal web server
2476 # with normal "file data", but not a normal files system. For instance,
2477 # we want or normal Web Site to run directly from a RAM hash table or
2478 # other database, instead of from disk. But we do NOT want to code the
2479 # whole site structure in CGI.
2481 # CGIscriptor can do this. If the web server fills an environment variable
2482 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
2483 # of this variable is processed instead of opening a file. If this environment
2484 # variable has the value '-', the content of another environment variable,
2485 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
2486 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
2487 # and the result is processed as if it was the content of the requested
2489 # (actually, the names of the environment variables are user configurable,
2490 # they are stored in the local variables $CGI_FILE_CONTENT and
2491 # $CGI_DATA_ACCESS_CODE)
2493 # When using this mechanism, the SRC attribute mechanism will only partially work.
2494 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
2495 # will work, the automagical execution of SRC files won't. (In this case,
2496 # the SRC attribute won't work either for other scripting languages)
2499 # NON-UNIX PLATFORMS
2501 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2502 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2503 # CGIscriptor did run under MacPerl (with command line options). But only
2504 # as an independend script, not as part of a HTTP server. I have used it
2505 # under Apache in Windows XP.
2510 ###############################################################################
2512 # SECURITY CONFIGURATION
2514 # Special configurations related to SECURITY
2515 # (i.e., optional, see also environment variables below)
2518 # Log Clients and the requested paths (Redundant when loging Queries)
2520 $ClientLog = "./Client.log"; # (uncomment for use)
2522 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2523 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2525 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2526 # to log queries. If you log Queries, the loging of Clients is redundant
2527 # (note that queries can be quite long, so this might not be a good idea)
2529 #$QueryLog = "./Query.log"; # (uncomment for use)
2532 # the Access files should contain Hostnames or IP addresses,
2533 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2534 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2535 # Matching is done "domain first". For example ".edu" matches all
2536 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2537 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2538 # (both matchings are done case-insensitive).
2539 # The name special symbol "-" matches ALL clients who do not supply a
2540 # REMOTE_HOST name, "*" matches all clients.
2541 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2542 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2543 # lines are evaluated in the program's own name-space. So DO NOT assign to
2546 # Accept the following users (remove comment # and adapt filename)
2547 $CGI_Accept = -s
"$YOUR_SCRIPTS/ACCEPT.lis" ?
"$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2549 # Reject requests from the following users (remove comment # and
2550 # adapt filename, this is only of limited use)
2551 $CGI_Reject = -s
"$YOUR_SCRIPTS/REJECT.lis" ?
"$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2553 # Empty lines or comment lines starting with '#' are ignored in both
2554 # $CGI_Accept and $CGI_Reject.
2556 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2557 # Comment this out if you realy want to use STDIN in an on-line web server
2558 $BLOCK_STDIN_HTTP_REQUEST = 1;
2561 # End of security configuration
2563 ##################################################<<<<<<<<<<End Remove
2565 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2567 # The CGI parse commands. These commands extract the values of the
2568 # CGI variables from the URL encoded Query String.
2569 # If you want to use your own CGI decoders, you can call them here
2570 # instead, using your own PATH and commenting/uncommenting the
2573 # CGI parse command for individual values
2574 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2575 sub YOUR_CGIPARSE
# ($Name [, $List]) -> Decoded value
2578 my $List = shift || 0;
2579 # Use one of the following by uncommenting
2580 if(!$List) # Simple value
2582 return CGIscriptor
::CGIparseValue
($Name) ;
2584 elsif($List < 0) # Hash tables
2586 return CGIscriptor
::CGIparseValueHash
($Name); # Defined in CGIscriptor below
2590 return CGIscriptor
::CGIparseValueList
($Name); # Defined in CGIscriptor below
2593 # return `/PATH/cgiparse -value $Name`; # Shell commands
2594 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2597 sub YOUR_CGIQUERYDECODE
2599 # Use one of the following by uncommenting
2600 return CGIscriptor
::CGIparseForm
(); # Defined in CGIscriptor below
2601 # return `/PATH/cgiparse -form`; # Shell commands
2602 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2605 # End of configuration
2607 #######################################################################
2609 # Translating input files.
2610 # Allows general and global conversions of files using Regular Expressions
2611 # Translations are applied in the order of definition.
2614 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2616 # push(@TranslationTable, ['pattern', 'replacement']);
2617 # e.g. (for Ruby Rails):
2618 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2619 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2622 # my $currentRegExp;
2623 # foreach $currentRegExp (keys(%TranslationTable))
2625 # my $currentRegExp;
2626 # foreach $currentRegExp (@TranslationTable)
2628 # my ($pattern, $replacement) = @$currentRegExp;
2629 # $$text =~ s!$pattern!$replacement!msg;
2633 # Configuration section
2635 #######################################################################
2637 # The file paths on which to apply the translation
2638 my $TranslationPaths = ''; # NO files
2639 #$TranslationPaths = '.'; # ANY file
2640 # $TranslationPaths = '\.html'; # HTML files
2642 my @TranslationTable = ();
2644 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2646 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2647 push(@TranslationTable, ['%>', '</SCRIPT>']);
2649 sub performTranslation
# (\$text)
2651 my $text = shift || return;
2652 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2655 foreach $currentRegExp (@TranslationTable)
2657 my ($pattern, $replacement) = @
$currentRegExp;
2658 $$text =~ s!$pattern!$replacement!msg;
2663 #######################################################################
2665 # Seamless access to other (Scripting) Languages
2666 # TYPE='text/ss<interpreter>'
2668 # Configuration section
2670 #######################################################################
2672 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2673 # Yes, it realy is this simple! (unbelievable, isn't it)
2674 # NOTE: Some interpreters require some filtering to obtain "clean" output
2676 %ScriptingLanguages = (
2677 "text/testperl" => 'perl', # Perl for testing
2678 "text/sspython" => 'python', # Python
2679 "text/ssruby" => 'ruby', # Ruby
2680 "text/sstcl" => 'tcl', # TCL
2681 "text/ssawk" => 'awk -f-', # Awk
2682 "text/sslisp" => # lisp (rep, GNU)
2683 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2684 "text/xlispstat" => # xlispstat
2685 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2686 "text/ssprolog" => # Prolog (GNU)
2687 "gprolog | tail +4 | sed 's/^| ?- //'",
2688 "text/ssm4" => 'm4', # M4 macro's
2689 "text/sh" => 'sh', # Born shell
2690 "text/bash" => 'bash', # Born again shell
2691 "text/csh" => 'csh', # C shell
2692 "text/ksh" => 'ksh', # Korn shell
2693 "text/sspraat" => # Praat (sound/speech analysis)
2694 "praat - | sed 's/Praat > //g'",
2696 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2697 "text/ssrebol" => # REBOL
2698 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2699 "text/postgresql" => 'psql 2>/dev/null',
2701 # Not real scripting, but the use of other applications
2702 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2703 "text/ssdisplay" => 'cat', # Display, (interpolation)
2704 "text/sslogfile" => # Log to file, (interpolation)
2705 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2710 # To be able to access the CGI variables in your script, they
2711 # should be passed to the scripting language in a readable form
2712 # Here you can enter how they should be printed (the first %s
2713 # is replaced by the NAME of the CGI variable as it apears in the
2714 # META tag, the second by its VALUE).
2715 # For Perl this would be:
2716 # "text/testperl" => '$%s = "%s";',
2717 # which would be executed as
2718 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2720 # If the hash table value doesn't exist, nothing is done
2721 # (you have to parse the Environment variables yourself).
2722 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2723 # Perl string interpolation of variables (i.e., $var, @array,
2724 # %hash) is performed. This means that $@%\ must be protected
2727 %ScriptingCGIvariables = (
2728 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2729 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2730 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2731 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2732 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2733 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2734 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2735 "text/ssprolog" => '', # Gnu prolog (interpolated)
2736 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2737 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2738 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2739 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2740 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2742 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2743 "text/sspraat" => '', # Praat (interpolation)
2744 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2745 "text/postgresql" => '', # PostgreSQL (interpolation)
2747 # Not real scripting, but the use of other applications
2748 "text/ssmailto" => '', # MAILTO, (interpolation)
2749 "text/ssdisplay" => '', # Display, (interpolation)
2750 "text/sslogfile" => '', # Log to file, (interpolation)
2755 # If you want something added in front or at the back of each script
2756 # block as send to the interpreter add it here.
2757 # mime => "string", e.g., "text/sspython" => "python commands"
2758 %ScriptingPrefix = (
2759 "text/testperl" => "\# Prefix Code;", # Perl script testing
2760 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2764 # If you want something added at the end of each script block
2765 %ScriptingPostfix = (
2766 "text/testperl" => "\# Postfix Code;", # Perl script testing
2767 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2771 # If you need initialization code, directly after opening
2772 %ScriptingInitialization = (
2773 "text/testperl" => "\# Initialization Code;", # Perl script testing
2774 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2775 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2776 "text/xlispstat" => '(prog1 nil ', # xlispstat
2777 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2781 # If you need cleanup code before closing
2782 %ScriptingCleanup = (
2783 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2784 "text/sspraat" => 'Quit',
2785 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2786 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2787 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2788 "text/postgresql" => '\q', # quit psql
2789 "text/ssdisplay" => "", # close cat
2794 # End of configuration for foreign scripting languages
2796 ###############################################################################
2798 # Initialization Code
2801 sub Initialize_Request
2803 ###############################################################################
2805 # ENVIRONMENT VARIABLES
2807 # Use environment variables to configure CGIscriptor on a temporary basis.
2808 # If you define any of the configurable variables as environment variables,
2809 # these are used instead of the "hard coded" values above.
2811 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2812 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2815 # Substitution strings, these are used internally to handle the
2816 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2817 $HOME_SUB = $SS_PUB;
2818 $SCRIPT_SUB = $SS_SCRIPT;
2821 # Make sure all script are reliably loaded
2822 push(@INC, $SS_SCRIPT);
2825 # Add the directory separator to the "home" directories.
2826 # (This is required for ~/ and ./ substitution)
2827 $HOME_SUB .= '/' if $HOME_SUB;
2828 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2830 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2831 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2832 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2833 $default_values{'CGI_HOME'} = $CGI_HOME;
2834 $ENV{'HOME'} = $CGI_HOME;
2835 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2837 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2838 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2840 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2841 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2842 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2843 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2844 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2845 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2848 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2849 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2850 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2851 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2853 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2854 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2855 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2856 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2858 @CGIscriptorResults = (); # A stack of results
2860 # end of Environment variables
2862 #############################################################################
2864 # Define and Store "standard" values
2866 # BEFORE doing ANYTHING check the size of Query String
2867 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2869 # The Translated Query String and the Actual length of the (decoded)
2871 if($ENV{'QUERY_STRING'})
2873 # If this can contain '`"-quotes, be carefull to use it QUOTED
2874 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2875 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2878 # Get the current Date and time and store them as default variables
2881 $LocalTime = localtime;
2883 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2884 # CGI_Hour CGI_Minutes CGI_Seconds
2886 $default_values{CGI_Date} = $LocalTime;
2887 ($default_values{CGI_WeekDay},
2888 $default_values{CGI_Month},
2889 $default_values{CGI_Day},
2890 $default_values{CGI_Time},
2891 $default_values{CGI_Year}) = split(' ', $LocalTime);
2892 ($default_values{CGI_Hour},
2893 $default_values{CGI_Minutes},
2894 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2897 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2898 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2900 ($default_values{CGI_GMTSeconds},
2901 $default_values{CGI_GMTMinutes},
2902 $default_values{CGI_GMTHour},
2903 $default_values{CGI_GMTDay},
2904 $default_values{CGI_GMTMonth},
2905 $default_values{CGI_GMTYear},
2906 $default_values{CGI_GMTWeekDay},
2907 $default_values{CGI_GMTYearDay},
2908 $default_values{CGI_GMTisdst}) = gmtime;
2912 # End of Initialize Request
2914 ###################################################################
2916 # SECURITY: ACCESS CONTROL
2918 # Check the credentials of each client (use pattern matching, domain first).
2919 # This subroutine will kill-off (die) the current process whenever access
2924 # >>>>>>>>>>Start Remove
2928 # Only accept clients which are authorized, reject all unnamed clients
2929 # if REMOTE_HOST is given.
2930 # If file patterns are given, check whether the user is authorized for
2934 # Use local variables, REMOTE_HOST becomes '-' if undefined
2935 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2936 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2937 my $PATH_INFO = $ENV{'PATH_INFO'};
2939 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2943 next unless /\S/; # Skip empty lines
2944 next if /^\s*\#/; # Skip comments
2950 my $Accept = $'; # Get the expression
2951 $NoAccess &&= eval($Accept); # evaluate the expresion
2953 elsif($PATH_INFO ne "")
2955 my ($Accept, @FilePatternList) = split;
2956 if($Accept eq '*' # Always match
2957 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2959 $Accept =~ /^[0-9\.]+$/
2960 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2964 if($FilePatternList[0])
2967 if($FilePatternList[0] eq "!" or $FilePatternList[0] eq "not")
2970 shift(@FilePatternList);
2972 foreach $Pattern (@FilePatternList)
2974 # Check whether this patterns is accepted
2975 my $value = ($PATH_INFO !~ m@\Q$Pattern\E@is);
2976 $value = not $value if $invert;
2977 $NoAccess &&= $value;
2982 $NoAccess = 0; # No file patterns -> Accepted
2987 last unless $NoAccess;
2990 if($NoAccess && $PATH_INFO ne "")
2992 dieHandler(4, "No Access
: $PATH_INFO\n");
2993 $ENV{'PATH_INFO'} = "";
3000 # Reject named clients, accept all unnamed clients
3003 # Use local variables, REMOTE_HOST becomes '-' if undefined
3004 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
3005 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3006 my $PATH_INFO = $ENV{'PATH_INFO'};
3008 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
3012 next unless /\S/; # Skip empty lines
3013 next if /^\s*\#/; # Skip comments
3019 my $Reject = $'; # Get the expression
3020 $NoAccess ||= eval($Reject); # evaluate the expresion
3022 elsif($PATH_INFO ne "")
3024 my ($Reject, @FilePatternList) = split;
3025 if($Reject eq '*' # Always match
3026 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
3027 ||($Reject =~ /^[0-9\.]+$/
3028 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
3032 if($FilePatternList[0])
3035 if($FilePatternList[0] eq "!" or $FilePatternList[0] eq "not")
3038 shift(@FilePatternList);
3040 foreach $Pattern (@FilePatternList)
3042 my $value = ($PATH_INFO =~ m@\Q$Pattern\E@is);
3043 $value = not $value if $invert;
3044 $NoAccess ||= $value;
3049 $NoAccess = 1; # No file patterns -> Rejected
3056 if($NoAccess && $PATH_INFO ne "")
3058 dieHandler(4, "Request rejected
: $PATH_INFO\n");
3059 $ENV{'PATH_INFO'} = "";
3063 ##########################################################<<<<<<<<<<End Remove
3068 # Does the filename contain any illegal characters (e.g., |, >, or <)
3069 dieHandler(7, "Illegal request
: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
3070 # Does the pathname contain an illegal (blocked) "directory
"
3071 dieHandler(8, "Illegal request
: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
3072 # Does the pathname contain a direct referencer to BinaryMapFile
3073 dieHandler(9, "Illegal request
: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
3075 # SECURITY: Is PATH_INFO allowed?
3076 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
3077 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
3079 # Unsupported file types can be processed by a special raw-file
3082 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
3083 $ENV{'PATH_INFO'} = $BinaryMapFile;
3087 dieHandler(10, "Illegal file
\n");
3093 # End of Security Access Control
3096 ############################################################################
3098 # Get the POST part of the query and add it to the QUERY_STRING.
3101 sub Get_POST_part_of_query
3104 # If POST, Read data from stdin to QUERY_STRING
3105 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
3107 # SECURITY: Check size of Query String
3108 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler
(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
3110 my $SystemRead = $ENV{'CONTENT_LENGTH'};
3111 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
3112 while($SystemRead > 0)
3114 $QueryRead = sysread(STDIN
, $Post, $SystemRead); # Limit length
3115 $ENV{'QUERY_STRING'} .= $Post;
3116 $SystemRead -= $QueryRead;
3118 # Update decoded Query String
3119 $default_values{CGI_Decoded_QS
} = YOUR_CGIQUERYDECODE
();
3120 $default_values{CGI_Content_Length
} =
3121 length($default_values{CGI_Decoded_QS
});
3125 # End of getting POST part of query
3128 ############################################################################
3130 # Start (HTML) output and logging
3131 # (if there are irregularities, it can kill the current process)
3134 sub Initialize_output
3136 # Construct the REAL file path (except for STDIN on the command line)
3137 my $file_path = $ENV{'PATH_INFO'} ne '-' ?
$SS_PUB . $ENV{'PATH_INFO'} : '-';
3138 $file_path =~ s/\?.*$//; # Remove query
3139 # This is only necessary if your server does not catch ../ directives
3140 $file_path !~ m@\
.\
./@ || dieHandler(12, "Illegal ../ Construct
\n"); # SECURITY: Do not allow ../ constructs
3142 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
3143 if($file_path eq '-')
3145 dieHandler(13, "STDIN request
in On Line
system\n") if $BLOCK_STDIN_HTTP_REQUEST
3146 && ($ENV{'SERVER_SOFTWARE'}
3147 || $ENV{'SERVER_NAME'}
3148 || $ENV{'GATEWAY_INTERFACE'}
3149 || $ENV{'SERVER_PROTOCOL'}
3150 || $ENV{'SERVER_PORT'}
3151 || $ENV{'REMOTE_ADDR'}
3152 || $ENV{'HTTP_USER_AGENT'});
3159 open(ClientLog, ">>$ClientLog");
3160 print ClientLog "$LocalTime | ",
3161 ($ENV{REMOTE_USER} || "-"), " ",
3162 ($ENV{REMOTE_IDENT} || "-"), " ",
3163 ($ENV{REMOTE_HOST} || "-"), " ",
3164 $ENV{REMOTE_ADDR}, " ",
3165 $ENV{PATH_INFO}, " ",
3166 $ENV{'CGI_BINARY_FILE'}, " ",
3167 ($default_values{CGI_Content_Length} || "-"),
3173 open(QueryLog, ">>$QueryLog");
3174 print QueryLog "$LocalTime\n",
3175 ($ENV{REMOTE_USER} || "-"), " ",
3176 ($ENV{REMOTE_IDENT} || "-"), " ",
3177 ($ENV{REMOTE_HOST} || "-"), " ",
3178 $ENV{REMOTE_ADDR}, ": ",
3179 $ENV{PATH_INFO}, " ",
3180 $ENV{'CGI_BINARY_FILE'}, "\n";
3182 # Write Query to Log file
3183 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
3187 # Return the file path
3191 # End of Initialize output
3194 ############################################################################
3196 # Handle login access
3198 # Access is based on a valid session ticket.
3199 # Session tickets should be dependend on user name
3200 # and IP address. The patterns of URLs for which a
3201 # session ticket is needed and the login URL are stored in
3202 # %TicketRequiredPatterns as:
3203 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
3206 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
3208 # No patterns, no login
3209 goto Return unless %TicketRequiredPatterns;
3211 # Get and initialize values (watch out for stuff processed by BinaryMap files)
3212 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
3213 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3214 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3215 goto Return if $REMOTE_ADDR =~ /[^0-9\.]/;
3216 # Extract TICKETs, starting with returned cookies
3217 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3218 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3219 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3221 if(length(keys(%CGI_Cookies)) > 0)
3223 ${"CGIexecute
::LOGINTICKET
"} = $CGI_Cookies{'CGIscriptorLOGIN'}
3224 if $CGI_Cookies{'CGIscriptorLOGIN'} && $CGI_Cookies{'CGIscriptorLOGIN'} ne "-";
3225 $CGI_Cookies{'CGIscriptorLOGIN'} = "-";
3226 ${"CGIexecute
::CHALLENGETICKET
"} = $CGI_Cookies{'CGIscriptorCHALLENGE'}
3227 if $CGI_Cookies{'CGIscriptorCHALLENGE'} && $CGI_Cookies{'CGIscriptorCHALLENGE'} ne "-";
3228 $CGI_Cookies{'CGIscriptorCHALLENGE'} = "-";
3229 ${"CGIexecute
::SESSIONTICKET
"} = $CGI_Cookies{'CGIscriptorSESSION'}
3230 if $CGI_Cookies{'CGIscriptorSESSION'} && $CGI_Cookies{'CGIscriptorSESSION'} ne "-";
3231 $CGI_Cookies{'CGIscriptorSESSION'} = "-";
3233 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_+.)
3234 my $LOGINTICKET = ${"CGIexecute
::LOGINTICKET
"};
3235 goto Return if ($LOGINTICKET && $LOGINTICKET =~ /[^\w\.]/isg);
3236 my $SESSIONTICKET = ${"CGIexecute
::SESSIONTICKET
"};
3237 goto Return if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
3238 my $CHALLENGETICKET = ${"CGIexecute
::CHALLENGETICKET
"};
3239 goto Return if ($CHALLENGETICKET && $CHALLENGETICKET =~ /[^\w\.]/isg);
3240 # Look for a LOGOUT message
3241 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
3242 # Username and password
3243 CGIexecute::defineCGIvariable('CGIUSERNAME', "");
3244 my $username = lc(${"CGIexecute
::CGIUSERNAME
"});
3245 goto Return if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
3246 my $userfile = lc($username);
3247 $userfile =~ s/[^\w]/_/isg;
3248 CGIexecute::defineCGIvariable('PASSWORD', "");
3249 my $password = ${"CGIexecute
::PASSWORD
"};
3250 CGIexecute::defineCGIvariable('NEWUSERNAME', "");
3251 my $newuser = lc(${"CGIexecute
::NEWUSERNAME
"});
3252 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
3253 my $newpassword = ${"CGIexecute
::NEWPASSWORD
"};
3255 foreach my $pattern (keys(%TicketRequiredPatterns))
3257 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
3258 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
3260 # Fall through a sieve of requirements
3261 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3263 # Is there a change password request?
3264 if($newuser && $LOGINTICKET && $username)
3266 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3267 goto Login unless (-s "$PasswordsPath/$userfile");
3268 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3269 goto Login unless $ticket_valid;
3270 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3271 goto Login unless $ticket_valid;
3273 my ($sessiontype, $currentticket) = ("", "");
3274 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE
", $CHALLENGETICKET);}
3275 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION
", $SESSIONTICKET);}
3276 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS
", $REMOTE_ADDR);
3280 goto Login unless (-s "$SessionPath/$currentticket");
3281 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3282 goto Login unless $ticket_valid;
3285 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath, $REMOTE_ADDR);
3286 goto Login unless $TMPTICKET;
3288 # Create a new user account
3289 CGIexecute::defineCGIvariable('NEWSESSION', "");
3290 my $newsession = ${"CGIexecute
::NEWSESSION
"};
3291 my $newaccount = create_newuser("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket",
3292 "$PasswordsPath/$userfile", $password, $newuser, $newpassword, $newsession);
3293 CGIexecute::defineCGIvariable('NEWACCOUNTTEXT', $newaccount);
3294 ${CGIexecute::NEWACCOUNTTEXT} = $newaccount;
3295 # NEWACCOUNTTEXT is NOT to be set by the query
3296 CGIexecute::ProtectCGIvariable('NEWACCOUNTTEXT');
3302 # Is there a change password request?
3303 elsif($newpassword && $LOGINTICKET && $username)
3305 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3306 goto Login unless (-s "$PasswordsPath/$userfile");
3307 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3308 goto Login unless $ticket_valid;
3309 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3310 goto Login unless $ticket_valid;
3312 my ($sessiontype, $currentticket) = ("", "");
3313 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE
", $CHALLENGETICKET);}
3314 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION
", $SESSIONTICKET);}
3315 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS
", $REMOTE_ADDR);
3319 goto Login unless (-s "$SessionPath/$currentticket");
3320 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3321 goto Login unless $ticket_valid;
3324 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket", "$PasswordsPath/$userfile", $password, $newpassword);
3325 # After a change of password, you have to login again for a CHALLENGE
3326 if($CHALLENGETICKET){$CHALLENGETICKET = "";};
3330 # Is there a login ticket of this name?
3333 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3334 goto Login unless (-s "$PasswordsPath/$userfile");
3335 my $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3336 goto Login unless $ticket_valid;
3337 $ticket_valid = check_ticket_validity("LOGIN
", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
3338 goto Login unless $ticket_valid;
3341 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath, $REMOTE_ADDR);
3344 my $authorization = read_ticket("$PasswordsPath/$userfile");
3345 goto Login unless $authorization;
3346 # Session type is read from the userfile
3347 if($authorization->{"Session
"} && $authorization->{"Session
"}->[0] eq "CHALLENGE
")
3349 # Create New Random CHALLENGETICKET
3350 $CHALLENGETICKET = $TMPTICKET;
3351 create_session_file("$SessionPath/$CHALLENGETICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3353 elsif($authorization->{"Session
"} && $authorization->{"Session
"}->[0] eq "IPADDRESS
")
3355 create_session_file("$SessionPath/$REMOTE_ADDR", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3359 # Extra hash to protect CHALLENGETICKET use
3360 $SESSIONTICKET = hash_string($TMPTICKET);
3361 $SESSIONTICKET = hash_string($SESSIONTICKET.$TMPTICKET);
3362 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3363 $SETCOOKIELIST{"CGIscriptorSESSION
"} = "-";
3364 $TMPTICKET = $SESSIONTICKET;
3367 # Login ticket file has been used, remove it
3370 # Is there a session ticket of this name?
3372 if($CHALLENGETICKET)
3374 # Do not log into a CHALLENGE account if the SESSION cookie is present
3375 # Uncomment when $SESSIONTICKET does not receive an extra hash
3376 #goto Login if $SESSIONTICKET =~ /\S/;
3377 goto Login unless (-s "$SessionPath/$CHALLENGETICKET");
3378 my $ticket_valid = check_ticket_validity("CHALLENGE
", "$SessionPath/$CHALLENGETICKET", $REMOTE_ADDR, $PATH_INFO);
3379 goto Login unless $ticket_valid;
3381 my $oldchallenge = read_ticket("$SessionPath/$CHALLENGETICKET");
3382 goto Login unless $oldchallenge;
3383 # Check whether the login still exists
3384 my $userfile = lc($oldchallenge->{"Username
"}->[0]);
3385 $userfile =~ s/[^\w]/_/isg;
3386 goto Login unless (-s "$PasswordsPath/$userfile");
3388 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3389 goto Login unless $ticket_valid;
3391 # This is a LOGOUT request, clean up (Access has already been validated)
3394 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3395 $CHALLENGETICKET = "";
3399 my $NEWCHALLENGETICKET = "";
3400 $NEWCHALLENGETICKET = copy_challenge_file("$SessionPath/$CHALLENGETICKET", "$PasswordsPath/$userfile", $SessionPath);
3401 # Sessionticket is available to scripts, do NOT set the cookie
3402 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3406 elsif(-s "$SessionPath/$REMOTE_ADDR")
3408 my $ticket_valid = check_ticket_validity("IPADDRESS
", "$SessionPath/$REMOTE_ADDR", $REMOTE_ADDR, $PATH_INFO);
3409 goto Login unless $ticket_valid;
3410 # Check whether the login still exists
3411 my $currentsessionticket = read_ticket("$SessionPath/$REMOTE_ADDR");
3412 my $userfile = lc($currentsessionticket->{"Username
"}->[0]);
3413 $userfile =~ s/[^\w]/_/isg;
3414 goto Login unless (-s "$PasswordsPath/$userfile");
3416 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3417 goto Login unless $ticket_valid;
3419 # This is a LOGOUT request, clean up (Access has already been validated)
3422 unlink "$SessionPath/$REMOTE_ADDR" if (-s "$SessionPath/$REMOTE_ADDR");
3429 elsif($SESSIONTICKET)
3431 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
3432 my $ticket_valid = check_ticket_validity("SESSION
", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
3433 goto Login unless $ticket_valid;
3435 # Check whether the login still exists
3436 my $currentsessionticket = read_ticket("$SessionPath/$SESSIONTICKET");
3437 my $userfile = lc($currentsessionticket->{"Username
"}->[0]);
3438 $userfile =~ s/[^\w]/_/isg;
3439 goto Login unless (-s "$PasswordsPath/$userfile");
3441 $ticket_valid = check_ticket_validity("PASSWORD
", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3442 goto Login unless $ticket_valid;
3444 # This is a LOGOUT request, clean up (Access has already been validated)
3447 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3448 $SESSIONTICKET = "";
3452 # Sessionticket is available to scripts
3453 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3462 # The Masterkey should NOT be accessible by the parsed files
3463 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3467 # To deter DOS attacks, do not remove valid session tickets unless the
3468 # "owner
" has accredited herself
3469 my $tickets_removed = remove_expired_tickets($SessionPath);
3470 create_login_file($PasswordsPath, $SessionPath, $REMOTE_ADDR);
3471 # Note, cookies are set only ONCE
3472 $SETCOOKIELIST{"CGIscriptorLOGIN
"} = "-";
3473 # The Masterkey should NOT be accessible by the parsed files
3474 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3475 return "$YOUR_HTML_FILES/$Login";
3478 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath, $IPaddress) => SESSIONTICKET First two arguments are file paths
3480 my $loginfile = shift || "";
3481 my $authorizationfile = shift || "";
3482 my $password = shift || "";
3483 my $SessionPath = shift || "";
3484 my $RemoteIPaddress = shift || "";
3486 # Get Login session ticket
3487 my $loginticket = read_ticket($loginfile);
3488 return 0 unless $loginticket;
3489 # Get User credentials for authorization
3490 my $authorization = read_ticket($authorizationfile);
3491 return 0 unless $authorization;
3494 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3495 return "" unless $Randomsalt;
3497 my $storedpassword = $authorization->{'Password'}->[0];
3498 return "" unless $storedpassword;
3499 my $Hashedpassword = hash_string($storedpassword.$RemoteIPaddress.$Randomsalt);
3500 return "" unless $password eq $Hashedpassword;
3502 # Extract Session Ticket
3503 my $loginsession = $loginticket->{'Session'}->[0];
3504 my $sessionticket = hash_string($storedpassword.$loginsession);
3505 chomp($sessionticket);
3506 $sessionticket = "" if -x "$SessionPath/$sessionticket";
3508 # No lingering password variables
3509 $Hashedpassword = $Randomsalt;
3510 $password = $Randomsalt;
3511 $authorization->{'Password'}->[0] = $Randomsalt;
3513 return $sessionticket;
3516 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First three arguments are file paths
3518 my $loginfile = shift || "";
3519 my $sessionfile = shift || "";
3520 my $authorizationfile = shift || "";
3521 my $password = shift || "";
3522 my $newpassword = shift || "";
3523 # Get Login session ticket
3524 my $loginticket = read_ticket($loginfile);
3525 return "" unless $loginticket;
3526 # Login ticket file has been used, remove it
3529 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3530 return "" unless $Randomsalt;
3531 my $LoginID = $loginticket->{'Session'}->[0];
3532 return "" unless $LoginID;
3534 # Get session ticket
3535 my $sessionticket = read_ticket($sessionfile);
3536 return "" unless $sessionticket;
3538 # Get User credentials for authorization
3539 my $authorization = read_ticket($authorizationfile);
3540 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3542 my $storedpassword = $authorization->{'Password'}->[0];
3543 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3544 return "" unless $password eq $Hashedpassword;
3545 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3547 # Decrypt the $newpassword
3548 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3549 return "" unless $decryptedPassword;
3550 # Authorization succeeded, change password
3551 $authorization->{'Password'}->[0] = $decryptedPassword;
3553 write_ticket($authorizationfile, $authorization, $authorization->{'Salt'}->[0]);
3555 # No lingering password variables
3556 $decryptedPassword = $Randomsalt;
3557 $secretkey = $Randomsalt;
3558 $storedpassword = $Randomsalt;
3559 $Hashedpassword = $Randomsalt;
3560 $authorization->{'Password'}->[0] = $Randomsalt;
3562 return $newpassword;
3564 # First three arguments are file paths
3565 sub create_newuser # ($loginfile, $sessionfile, $authorizationfile, $password, $newuser, $newpassword, $newsession) -> account text
3567 my $loginfile = shift || "";
3568 my $sessionfile = shift || "";
3569 my $authorizationfile = shift || "";
3570 my $password = shift || "";
3571 my $newuser = shift || "";
3572 my $newpassword = shift || "";
3573 my $newsession = shift || "";
3575 # Get Login session ticket
3576 my $loginticket = read_ticket($loginfile);
3577 return "" unless $loginticket;
3578 # Login ticket file has been used, remove it
3581 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3582 return "" unless $Randomsalt;
3583 my $LoginID = $loginticket->{'Session'}->[0];
3584 return "" unless $LoginID;
3586 # Get session ticket
3587 my $sessionticket = read_ticket($sessionfile);
3588 return "" unless $sessionticket;
3589 # Get User credentials for authorization
3590 my $authorization = read_ticket($authorizationfile);
3591 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3592 my $sessionkey = $sessionticket->{'Key'}->[0];
3593 my $serversalt = $authorization->{'Salt'}->[0];
3594 return "" unless $serversalt;
3596 my $storedpassword = $authorization->{'Password'}->[0];
3597 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3598 return "" unless $password eq $Hashedpassword;
3599 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3601 # Decrypt the $newpassword
3602 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3603 return "" unless $decryptedPassword;
3605 # Authorization succeeded, create new account
3606 my $newaccount = {};
3607 $newaccount->{'Type'} = ['PASSWORD'];
3608 $newaccount->{'Username'} = [$newuser];
3609 $newaccount->{'Password'} = [$decryptedPassword];
3610 $newaccount->{'Salt'} = [$serversalt];
3611 $newaccount->{'Session'} = ['SESSION'];
3612 if($newsession eq 'IPADDRESS'){$newaccount->{'Session'} = ['IPADDRESS'];};
3613 if($newsession eq 'CHALLENGE'){$newaccount->{'Session'} = ['CHALLENGE'];};
3614 my $timesec = time();
3615 my $gmt_date = gmtime();
3616 $newaccount->{'Time'} = [$timesec];
3617 $newaccount->{'Date'} = [$gmt_date];
3620 my $NewAllowedPaths = "";
3621 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3622 my $currentRoot = "";
3623 $currentRoot = $1 if $PATH_INFO =~ m!^([\w\-\. /]+)!isg;
3624 $currentRoot =~ s![^/]+$!!isg;
3627 $currentRoot .= '/' unless $currentRoot =~ m!/$!;
3628 my $newpath = "^".${currentRoot}.'[\w\-]+\.html?';
3629 $NewAllowedPaths .= 'AllowedPaths: ^'.${currentRoot}.'[\w\-]+\.html?'."\n";
3630 $newaccount->{'AllowedPaths'} = [$newpath];
3634 # Tricky PATH_INFO, deny all
3635 $NewAllowedPaths .= "DeniedPaths
: ^/\n";
3636 $newaccount->{'DeniedPaths'} = ["DeniedPaths
: ^/\n"];
3639 # Construct home directory path
3640 my $FullHomeDirectoryPath = "";
3641 my $currentHome = lc($newuser);
3642 if($currentHome && $currentHome !~ /^\s*\#/)
3644 $currentHome =~ s![^\w]!_!isg;
3645 my $newpath = "^${currentRoot
}$currentHome/";
3646 push(@{$newaccount->{'AllowedPaths'}}, $newpath);
3647 # Create home directory
3648 $FullHomeDirectoryPath = $ENV{'HOME'}.${currentRoot}.$currentHome;
3652 CGIexecute::defineCGIvariable('ALLOWEDPATHS', "");
3653 my $allowedpaths = ${"CGIexecute
::ALLOWEDPATHS
"};
3654 if($allowedpaths && $allowedpaths !~ /^\s*\#/)
3656 $allowedpaths =~ s!\#.*$!!isg;
3657 $allowedpaths =~ s![^\^\w\./\;\+\*\?\[\]\$]!!isg;
3658 my @pathlist = split(/\;/, $allowedpaths);
3659 foreach my $entry (@pathlist)
3661 push(@{$newaccount->{'AllowedPaths'}}, "^".${currentRoot}.$entry);
3665 # Allowed IP addresses
3666 CGIexecute::defineCGIvariable('IPADDRESS', "");
3667 my $ipaddress = ${"CGIexecute
::IPADDRESS
"};
3668 if($ipaddress && $ipaddress !~ /^\s*\#/)
3670 $ipaddress =~ s!\#.*$!!isg;
3671 $ipaddress =~ s![^\d\.\;]!!isg;
3672 my @iplist = split(/\;/, $ipaddress);
3673 foreach my $entry (@iplist)
3675 next unless $entry =~ /\d/;
3676 next if $entry =~ /^\s*\#/;
3677 $entry =~ s/\./\\./g;
3678 push(@{$newaccount->{'IPaddress'}}, $entry);
3683 CGIexecute::defineCGIvariable('NEWCAPABILITIES', "");
3684 my $capabilities = ${"CGIexecute
::NEWCAPABILITIES
"};
3685 if($capabilities && $capabilities !~ /^\W*\#/)
3687 $capabilities =~ s!\#.*$!!isg;
3688 $capabilities =~ s![^\w\s]!!isg;
3689 my @caplist = split(/\s/, $capabilities);
3690 foreach my $entry (@caplist)
3692 next unless $entry =~ /\w/;
3693 next if $entry =~ /^\s*\#/;
3694 push(@{$newaccount->{'Capabilities'}}, $entry);
3698 # Sign the new ticket
3699 my $Signature = SignTicketWithMasterkey($newaccount, $newaccount->{'Salt'}->[0]);
3702 my $datetime = gmtime();
3703 my $newuserfile = "";
3704 if(grep(/^CreateUser$/, @{$authorization->{'Capabilities'}}))
3706 my $newuserfilename = lc($newuser);
3707 $newuserfilename =~ s/[^\w]/_/isg;
3708 $newuserfile = $authorizationfile;
3709 $newuserfile =~ s![^/]*$!!isg;
3710 $newuserfile .= $newuserfilename;
3715 elsif($FullHomeDirectoryPath && !(-d $FullHomeDirectoryPath || -s $FullHomeDirectoryPath))
3717 if(-d "$ENV{'HOME'}${currentRoot
}.SkeletonDir
")
3719 `cp -r '$ENV{'HOME'}${currentRoot}.SkeletonDir' '$FullHomeDirectoryPath'`;
3721 elsif(-d "$ENV{'HOME'}${currentRoot
}SkeletonDir
")
3723 `cp -r '$ENV{'HOME'}${currentRoot}SkeletonDir' '$FullHomeDirectoryPath'`;
3725 elsif(-s "$ENV{'HOME'}${currentRoot
}UserIndex
.html
")
3727 mkdir $FullHomeDirectoryPath;
3728 `cp '$ENV{'HOME'}${currentRoot}UserIndex.html' '$FullHomeDirectoryPath/index.html'`;
3730 elsif(-s "$ENV{'HOME'}${currentRoot
}index.html
")
3732 mkdir $FullHomeDirectoryPath;
3733 `cp '$ENV{'HOME'}${currentRoot}index.html' '$FullHomeDirectoryPath/index.html'`;
3739 my $newaccounttext = write_ticket($newuserfile, $newaccount, $serversalt);
3741 # Re-encrypt the new password for transmission
3742 if($newaccounttext =~ /^(Password\:\s+)(\S+)\s*$/)
3744 my $passwordvalue = $1;
3745 my $reencryptedpassword = XOR_hex_strings($secretkey, $passwordvalue);
3746 my $encryptedpasswordline = "<span id
='newaccount'>$reencryptedpassword</span
>";
3747 $newaccounttext =~ s/^(Password\:\s+)(\S+)\s*$/\1$encryptedpasswordline/gim;
3749 # No lingering passwords
3750 $passwordvalue = $serversalt;
3752 return $newaccounttext;
3755 # Copy a Challenge ticket file to a new name which is the hash of the new $CHALLENGETICKET and the password
3756 sub copy_challenge_file #($oldchallengefile, $authorizationfile, $sessionpath) -> $CHALLENGETICKET
3758 my $oldchallengefile = shift || "";
3759 my $authorizationfile = shift || "";
3760 my $sessionpath = shift || "";
3761 $sessionpath =~ s!/+$!!g;
3763 # Get Login session ticket
3764 my $oldchallenge = read_ticket($oldchallengefile);
3765 return "" unless $oldchallenge;
3767 # Get Authorization (user) session file
3768 my $authorization = read_ticket($authorizationfile);
3769 return "" unless $authorization;
3770 my $storedpassword = $authorization->{'Password'}->[0];
3771 return "" unless $storedpassword;
3772 my $challengekey = $oldchallenge->{'Key'}->[0];
3773 return "" unless $challengekey;
3775 # Create Random Hash Salt
3776 my $NEWCHALLENGETICKET = get_random_hex();;
3777 my $newchallengefile = hash_string($challengekey.$NEWCHALLENGETICKET);
3778 return "" unless $newchallengefile;
3780 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3781 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3782 ${"CGIexecute
::CHALLENGETICKET
"} = $NEWCHALLENGETICKET;
3784 # Write Session Ticket
3785 open(OLDCHALLENGE, "<$oldchallengefile") || die "<$oldchallengefile: $!\n";
3786 my @OldChallengeLines = <OLDCHALLENGE>;
3787 close(OLDCHALLENGE);
3788 # Old file should now be removed
3789 unlink($oldchallengefile);
3791 open(SESSION, ">$sessionpath/$newchallengefile") || die "$sessionpath/$newchallengefile: $!\n";
3792 foreach $line (@OldChallengeLines)
3794 print SESSION $line;
3798 # No lingering passwords
3799 $storedpassword = $oldchallenge;
3801 return $NEWCHALLENGETICKET;
3804 sub create_login_file #($PasswordDir, $SessionDir, $IPaddress)
3806 my $PasswordDir = shift || "";
3807 my $SessionDir = shift || "";
3808 my $IPaddress = shift || "";
3810 # Create Login Ticket
3811 my $LOGINTICKET= get_random_hex ();
3813 # Create Random Hash Salt
3814 my $RANDOMSALT= get_random_hex();
3816 # Create SALT file if it does not exist
3817 # Remove this, including test account for life system
3818 unless(-d "$SessionDir")
3820 `mkdir -p "$SessionDir"`;
3822 unless(-d "$PasswordDir")
3824 `mkdir -p "$PasswordDir"`;
3826 # Create SERVERSALT and default test account
3827 my $SERVERSALT = "";
3828 unless(-s "$PasswordDir/SALT
")
3830 $SERVERSALT= get_random_hex();
3831 open(SALTFILE, ">$PasswordDir/SALT") || die ">$PasswordDir/SALT
: $!\n";
3832 print SALTFILE "$SERVERSALT\n";
3835 # Update test account (should be removed in live system)
3836 my @alltestusers = ("test
", "testip
", "testchallenge
", "admin
");
3837 foreach my $testuser (@alltestusers)
3839 if(-s "$PasswordDir/$testuser")
3841 my $plainpassword = $testuser eq 'admin' ? "There is
no password like more password
" : "testing
";
3843 my $storedpassword = hash_string(${plainpassword}.${testuser}.${SERVERSALT});
3844 # Encrypt the new password with the MasterKey
3845 my $authorization = read_ticket("$PasswordDir/$testuser") || return "";
3846 $authorization->{'Salt'} = [$SERVERSALT];
3847 $authorization->{'Type'} = ['INACTIVE PASSWORD'] if $testuser eq 'admin';
3848 set_password($authorization, $SERVERSALT, $plainpassword);
3849 write_ticket("$PasswordDir/$testuser", $authorization, $SERVERSALT);
3850 # No lingering passwords
3851 $storedpassword = $SERVERSALT;
3852 $plainpassword = $SERVERSALT;
3858 open(SALTFILE, "<$PasswordDir/SALT") || die "$PasswordDir/SALT
: $!\n";
3859 $SERVERSALT=<SALTFILE>;
3863 # Create login session ticket
3864 my $datetime = gmtime();
3865 my $timesec = time();
3866 my $loginticket = {};
3867 $loginticket->{Type} = ['LOGIN'];
3868 $loginticket->{IPaddress} = [$IPaddress];
3869 $loginticket->{Salt} = [$SERVERSALT];
3870 $loginticket->{Session} = [$LOGINTICKET];
3871 $loginticket->{Randomsalt} = [$RANDOMSALT];
3872 $loginticket->{Expires} = ['+600s'];
3873 $loginticket->{Date} = ["$datetime UTC
"];
3874 $loginticket->{Time} = [$timesec];
3875 write_ticket("$SessionDir/$LOGINTICKET", $loginticket, $SERVERSALT);
3877 # Set global variables
3879 $ENV{'SERVERSALT'} = $SERVERSALT;
3880 CGIexecute::defineCGIvariable('SERVERSALT', "");
3881 ${"CGIexecute
::SERVERSALT
"} = $SERVERSALT;
3884 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3885 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3886 ${"CGIexecute
::SESSIONTICKET
"} = $SESSIONTICKET;
3889 $ENV{'RANDOMSALT'} = $RANDOMSALT;
3890 CGIexecute::defineCGIvariable('RANDOMSALT', "");
3891 ${"CGIexecute
::RANDOMSALT
"} = $RANDOMSALT;
3894 $ENV{'LOGINTICKET'} = $LOGINTICKET;
3895 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3896 ${"CGIexecute
::LOGINTICKET
"} = $LOGINTICKET;
3898 return $ENV{'LOGINTICKET'};
3901 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
3903 my $sessionfile = shift || "";
3904 my $loginfile = shift || "";
3905 my $authorizationfile = shift || "";
3906 my $path = shift || "";
3908 # Get Login session ticket
3909 my $loginticket = read_ticket($loginfile);
3910 return unlink($loginfile) unless $loginticket;
3912 # Get Authorization (user) session file
3913 my $authorization = read_ticket($authorizationfile);
3914 return unlink($loginfile) unless $authorization;
3916 # For a Session or a Challenge, we need a stored key
3917 my $sessionkey = "";
3919 if($authorization->{'Session'} && $authorization->{'Session'}->[0] ne 'IPADDRESS')
3921 my $storedpassword = $authorization->{'Password'}->[0];
3922 my $loginticketid = $loginticket->{'Session'}->[0];
3923 my $randomsalt = $loginticket->{'Randomsalt'}->[0];
3924 $sessionkey = hash_string($storedpassword.$loginticketid);
3925 $secretkey = hash_string($storedpassword.$loginticketid.$randomsalt);
3926 # No lingering passwords
3927 $storedpassword = $loginticketid;
3931 if($sessionfile =~ m!([^/]+)$!)
3936 # Convert Authorization content to Session content
3937 my $sessionContent = {};
3938 my $SessionType = $authorization->{'Session'}->[0] ? $authorization->{'Session'}->[0] : "SESSION
";
3939 $sessionContent->{Type} = [$SessionType];
3940 $sessionContent->{Username} = [lc($authorization->{'Username'}->[0])];
3941 $sessionContent->{Session} = [$sessionid];
3942 $sessionContent->{Time} = [time];
3943 # Limit communication to the login IP address, except for Tor like situations with VariableREMOTE_ADDR
3944 $sessionContent->{IPaddress} = ['.'];
3945 if($sessionContent->{Type}->[0] eq 'CHALLENGE' && grep(/^VariableREMOTE_ADDR$/, @{$authorization->{'Capabilities'}}))
3947 $sessionContent->{IPaddress} = $authorization->{'IPaddress'} if $authorization->{'IPaddress'};
3951 $sessionContent->{IPaddress} = $loginticket->{'IPaddress'};
3953 $sessionContent->{Salt} = $authorization->{'Salt'};
3954 $sessionContent->{Randomsalt} = $loginticket->{'Randomsalt'};
3955 $sessionContent->{AllowedPaths} = $authorization->{'AllowedPaths'};
3956 $sessionContent->{DeniedPaths} = $authorization->{'DeniedPaths'};
3957 $sessionContent->{Expires} = $authorization->{'MaxLifetime'};
3958 $sessionContent->{Capabilities} = $authorization->{'Capabilities'};
3959 foreach my $pattern (keys(%TicketRequiredPatterns))
3961 if($path =~ m#$pattern#)
3963 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3964 push(@{$sessionContent->{Expires}}, $validtime);
3967 $sessionContent->{Key} = [$sessionkey] if $sessionkey;
3968 $sessionContent->{Secretkey} = [$secretkey] if $secretkey;
3969 $sessionContent->{Date} = [gmtime()." UTC
"];
3971 # Write Session Ticket
3972 write_ticket($sessionfile, $sessionContent, $authorization->{'Salt'}->[0]);
3974 # Login file should now be removed
3975 return unlink($loginfile);
3978 sub check_ticket_validity # ($type, $ticketfile, $address, $path [, $unsigned])
3980 my $type = shift || "SESSION
";
3981 my $ticketfile = shift || "";
3982 my $address = shift || "";
3983 my $path = shift || "";
3984 my $unsigned = shift || 0;
3986 # Is there a session ticket of this name?
3987 return 0 unless -s "$ticketfile";
3989 # There is a session ticket, is it linked to this IP address?
3990 my $ticket = read_ticket($ticketfile);
3993 print STDERR "Ticket expired
or empty
: $ticketfile\n";
3997 # Is this the right type of ticket
3998 unless($ticket && $ticket->{'Type'}->[0] eq $type)
4000 print STDERR "Wrong ticket type
: $ticket->{'Type'}->[0] eq $type\n";
4004 # Does the IP address match?
4005 my $IPmatches = @{$ticket->{"IPaddress
"}} ? 0 : 1;
4006 for $IPpattern (@{$ticket->{"IPaddress
"}})
4008 ++$IPmatches if $address =~ m#^$IPpattern#ig;
4010 if($address && ! $IPmatches)
4012 print STDERR "Wrong REMOTE ADDR
for $ticket->{'Username'}->[0]: $ticket->{'IPaddress'}->[0] vs
$address\n";
4016 # Is the path denied
4017 my $Pathmatches = 0;
4018 foreach $Pathpattern (@{$ticket->{"DeniedPaths
"}})
4020 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
4022 return 0 if @{$ticket->{"DeniedPaths
"}} && $Pathmatches;
4024 # Is the path allowed
4026 foreach $Pathpattern (@{$ticket->{"AllowedPaths
"}})
4028 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
4030 return 0 unless !@{$ticket->{"AllowedPaths
"}} || $Pathmatches;
4032 # Check signature if not told to use an unsigned ticket (dangerous)
4033 my $Signature = TicketSignature($ticket, $ticket->{'Salt'}->[0]);
4034 if((! $unsigned) && $Signature && $Signature ne $ticket->{'Signature'}->[0])
4036 print STDERR "Invalid signature
for $ticket->{'Type'}: $ticket->{'Username'}\n$ticketfile\n";
4040 # Make login values available (will also protect against resetting by query)
4041 $ENV{"LOGINUSERNAME
"} = lc($ticket->{'Username'}->[0]);
4042 $ENV{"LOGINIPADDRESS
"} = $address;
4043 $ENV{"LOGINPATH
"} = $path;
4044 $ENV{"SESSIONTYPE
"} = $type unless $type eq "PASSWORD
";
4046 # Set Capabilities, if present
4047 if($ticket->{'Username'}->[0] && @{$ticket->{'Capabilities'}})
4049 $ENV{'CAPABILITIES'} = $ticket->{'Username'}->[0];
4050 CGIexecute::defineCGIvariableList('CAPABILITIES', "");
4051 @{"CGIexecute
::CAPABILITIES
"} = @{$ticket->{'Capabilities'}};
4052 # Capabilities should not be changed anymore by CGI query!
4054 # Capabilities are NOT to be set by the query
4055 CGIexecute::ProtectCGIvariable('CAPABILITIES');
4061 # This might be run in a fork()?
4062 sub remove_expired_tickets # ($path) -> number of tickets removed
4064 my $path = shift || "";
4065 return 0 unless $path;
4067 my $removed_tickets = 0;
4068 my @ticketlist = glob("$path/*");
4069 foreach my $ticketfile (@ticketlist)
4071 my $ticket = read_ticket($ticketfile);
4078 return $removed_tickets;
4081 sub set_password # ($ticket, $salt, $plainpassword) -> $password
4083 my $ticket = shift || "";
4084 my $salt = shift || "";
4085 my $plainpassword = shift || "";
4087 my $user = lc($ticket->{'Username'}->[0]);
4088 return "" unless $user;
4089 $salt = $ticket->{'Salt'}->[0] unless $salt;
4091 my $storedpassword = hash_string(${plainpassword}.${user}.${salt});
4092 $ticket->{'Password'} = [$storedpassword];
4093 $ticket->{'Salt'} = [$salt];
4094 # No lingering passwords
4095 $storedpassword = $salt;
4096 $plainpassword = $salt;
4098 return $ticket->{'Password'}->[0];
4101 sub write_ticket # ($ticketfile, $ticket, $salt [, $masterkey]) -> &%ticket
4103 my $ticketfile = shift || "";
4104 my $ticket = shift || "";
4105 my $salt = shift || "";
4106 my $masterkey = shift || $ENV{'CGIMasterKey'};
4109 EncryptTicketWithMasterKey($ticket, $salt, $masterkey);
4111 # Sign the new ticket
4112 my $signature = SignTicketWithMasterkey($ticket, $salt, $masterkey);
4114 # Create ordered list with labels
4115 my @orderlist = ('Type', 'Username', 'Password', 'IPaddress', 'AllowedPaths', 'DeniedPaths',
4116 'Expires', 'Capabilities', 'Salt', 'Session', 'Randomsalt',
4117 'Date', 'Time', 'Signature', 'Key', 'Secretkey');
4118 my @labellist = keys(%{$ticket});
4119 foreach my $label (@orderlist)
4121 @labellist = grep(!/\b$label\b/, @labellist);
4124 # Create ticket in text
4125 my $TicketText = "";
4126 foreach my $label (@orderlist, @labellist)
4128 next unless exists($ticket->{$label}) && $ticket->{$label}->[0];
4129 foreach my $value (@{$ticket->{$label}})
4131 $TicketText .= "$label: $value\n";
4136 open(TICKET, ">$ticketfile") || die "$ticketfile: $!\n";
4137 print TICKET $TicketText;
4144 # Note, read_ticket will return 0 if the ticket has expired!
4145 sub read_ticket # ($ticketfile [, $salt, $masterkey]) -> &%ticket
4147 my $ticketfile = shift || "";
4148 my $serversalt = shift || "";
4149 my $masterkey = shift || $ENV{'CGIMasterKey'};
4152 if($ticketfile && -s $ticketfile)
4154 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
4155 my @alllines = <TICKETFILE>;
4157 foreach my $currentline (@alllines)
4159 # Skip empty lines and comments
4160 next unless $currentline =~ /\S/;
4161 next if $currentline =~ /^\s*\#/;
4163 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
4167 $ticket->{$Label} = () unless exists($ticket->{$Label});
4168 push(@{$ticket->{$Label}}, $Value);
4172 elsif(-z $ticketfile)
4176 if($masterkey && exists($ticket->{'Password'}) && $ticket->{'Password'}->[0])
4178 # Use the ServerSalt stored in the ticket, if present
4179 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4181 $serversalt = $ticket->{Salt}->[0];
4183 # Decrypt all passwords
4184 DecryptTicketWithMasterKey($ticket, $serversalt, $masterkey) ||
4185 die "Decryption failed
: DecryptTicketWithMasterKey
($ticket, $serversalt)\n";
4188 # Check whether the ticket has expired
4189 if(exists($ticket->{Expires}))
4192 if(exists($ticket->{Time}) && $ticket->{Time}->[0] > 0)
4194 $StartTime = [(sort(@{$ticket->{Time}}))]->[0];
4198 # Get SessionTicket file stats
4199 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
4200 = stat($ticketfile);
4201 $StartTime = $ctime;
4203 foreach my $Value (@{$ticket->{'Expires'}})
4205 # Recalculate expire date from relative time
4208 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
4210 $ExpireTime = 24*3600*$1;
4212 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
4214 $ExpireTime = 60*$1;
4216 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
4218 $ExpireTime = 3600*$1;
4220 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
4224 elsif($Value =~ /^\+(\d+)\s*$/)
4229 my $absoluteTime = $Value =~ /^\+/ ? $StartTime + $ExpireTime : $Value;
4230 return 0 unless $absoluteTime > time;
4232 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
4237 # Set up a valid ticket from a given text file
4238 # Use from command line. DO NOT USE ONLINE
4239 # Watch out for passwords that get stored in the history file
4241 # perl CGIscriptor.pl --managelogin [options] [files]
4243 # salt={file or saltvalue}
4244 # masterkey={file or plaintext}
4245 # newmasterkey={file or plaintext}
4246 # password={file or palintext}
4248 # Followed by one or more file names.
4249 # Options can be interspersed between filenames,
4250 # e.g., password='plaintext'
4251 # Note that passwords are only used once!
4253 sub setup_ticket_file # (@ARGV)
4255 # Stop when run on-line
4256 return if $ENV{'PATH_INFO'} || $ENV{'QUERY_STRING'};
4259 foreach my $input (@_)
4261 if($input =~ /^([\w]+)\=/)
4267 if($value !~ m![^\w\.\~\/\:\-]! && $value !~ /^[\-\.]/ && -s "$value" && ! -d "$value")
4269 # Warn about reading a value from file
4270 print STDERR "Read
'$name' from
: '$value'\n";
4271 open(INPUTVALUE, "<$value") || die "$value: $!\n";
4272 $value = <INPUTVALUE>;
4276 $value =~ s/(^\'([^\']*)\'$)/\1/g;
4277 $value =~ s/(^\"([^\"]*)\"$)/\1/g;
4278 $Settings{$name} = $value;
4280 elsif($input !~ m![^\w\.\~\/\:\-]!i && $input !~ /^[\-\.]/i && -s $input)
4282 # We MUST have a salt
4283 $Settings{'salt'} = $ticket->{'Salt'}->[0] unless $Settings{'salt'};
4285 # Set the new masterkey to the old masterkey if there is no new masterkey
4286 $Settings{'newmasterkey'} = $Settings{'masterkey'} unless exists($Settings{'newmasterkey'});
4289 my $ticket = read_ticket($input, $Settings{'salt'}, $Settings{'masterkey'});
4291 # Set a new password from plaintext
4292 $ticket->{'Salt'}->[0] = $Settings{'salt'} if $Settings{'salt'} && $Settings{'password'};
4293 set_password ($ticket, $Settings{'salt'}, $Settings{'password'}) if $Settings{'password'};
4294 # Write the ticket back to file
4295 write_ticket($input, $ticket, $Settings{'salt'}, $Settings{'newmasterkey'});
4297 # A password is only used once
4298 $Settings{'password'} = "";
4303 # Add a signature from $masterkey to a ticket in the label $signlabel
4304 sub SignTicketWithMasterkey # ($ticket, $serversalt [, $masterkey, $signlabel]) -> $Signature
4306 my $ticket = shift || return 0;
4307 my $serversalt = shift || "";
4308 my $masterkey = shift || $ENV{'CGIMasterKey'};
4309 my $signlabel = shift || 'Signature';
4311 my $Signature = TicketSignature($ticket, $serversalt, $masterkey);
4313 $ticket->{$signlabel} = [$Signature] if $Signature;
4318 # Determine ticket signature
4319 sub TicketSignature # ($ticket, $serversalt [, $masterkey]) -> $Signature
4321 my $ticket = shift || return 0;
4322 my $serversalt = shift || "";
4323 my $masterkey = shift || $ENV{'CGIMasterKey'};
4328 # If the ServerSalt is not stored in the ticket, the SALT file has to be found
4329 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4331 $serversalt = $ticket->{Salt}->[0];
4336 my $username = lc($ticket->{'Username'}->[0]);
4337 my $hash1 = hash_string(${masterkey}.${serversalt});
4338 # The order of $username.$hash1 should be different than in DecryptTicketWithMasterKey
4339 my $CryptKey = hash_string($username.${'hash1'});
4340 my $SignText = "Type
: ".$ticket->{'Type'}->[0]."\n";
4341 my @tmp = sort(@{$ticket->{'Username'}});
4342 $SignText .= "Username
: @tmp\n";
4343 @tmp = sort(@{$ticket->{'IPaddress'}});
4344 $SignText .= "IPaddress
: @tmp\n";
4345 @tmp = sort(@{$ticket->{'AllowedPaths'}});
4346 $SignText .= "AllowedPaths
: @tmp\n";
4347 @tmp = sort(@{$ticket->{'DeniedPaths'}});
4348 $SignText .= "DeniedPaths
: @tmp\n";
4349 @tmp = sort(@{$ticket->{'Session'}});
4350 $SignText .= "Session
: @tmp\n";
4351 @tmp = sort(@{$ticket->{'Time'}});
4352 $SignText .= "Time
: @tmp\n";
4353 @tmp = sort(@{$ticket->{'Expires'}});
4354 $SignText .= "Expires
: @tmp\n";
4355 @tmp = sort(@{$ticket->{'Capabilities'}});
4356 $SignText .= "Capabilities
: @tmp\n";
4357 @tmp = sort(@{$ticket->{'MaxLifetime'}});
4358 $SignText .= "MaxLifetime
: @tmp\n";
4359 $Signature = HMAC_hex($CryptKey, $SignText);
4365 # Decrypts a password list IN PLACE
4366 sub DecryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4368 my $ticket = shift || return 0;
4369 my $serversalt = shift || "";
4370 my $masterkey = shift || $ENV{'CGIMasterKey'};
4372 if($masterkey && exists($ticket->{Password}) && $ticket->{Password}->[0])
4374 # If the ServerSalt is not given, read it from the the ticket
4375 if(! $serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4377 $serversalt = $ticket->{Salt}->[0];
4379 # Decrypt password(s)
4382 my $hash1 = hash_string(${masterkey}.${serversalt});
4383 my $username = lc($ticket->{'Username'}->[0]);
4384 # The order of $hash1.$username should be different than in TicketSignature
4385 my $CryptKey = hash_string(${'hash1'}.$username);
4386 foreach my $password (@{$ticket->{Password}})
4388 $password = XOR_hex_strings($CryptKey,$password);
4392 return $ticket->{'Password'};
4394 sub EncryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4396 DecryptTicketWithMasterKey(@_);
4399 # Implement HMAC signature hash.
4400 # Blocksize is length in HEX characters, NOT bytes
4401 sub HMAC_hex # ($key, $message [, $blocksizehex]) -> $hex
4403 my $key = shift || "";
4404 my $message = shift || "";
4405 my $blocksizehex = shift || length($key);
4406 $key = hash_string($key) if length($key) > $blocksizehex;
4408 my $innerkey = XOR_hex_byte ($key, "36");
4409 my $outerkey = XOR_hex_byte ($key, "5c
");
4410 my $innerhash = hash_string($innerkey.$message);
4411 my $outerhash = hash_string($outerkey.$innerhash);
4416 # XOR input with equally long string of repeated 2 hex character (byte)
4417 # string. Input must have even number of hex characters
4418 sub XOR_hex_byte # ($hex1, $hexbyte) -> $hex
4420 my $hex1 = shift || "";
4421 my $hexbyte = shift || "";
4422 my $bytelength = length($hexbyte);
4424 $hex2 =~ s/.{$bytelength}/$hexbyte/ig;
4425 return XOR_hex_strings($hex1, $hex2);
4428 sub XOR_hex_strings # ($hex1, $hex2) -> $hex
4430 my $hex1 = shift || "";
4431 my $hex2 = shift || "";
4432 my @hex1list = split('', $hex1);
4433 my @hex2list = split('', $hex2);
4434 my @hexresultlist = ();
4435 for(my $i; $i < scalar(@hex1list); ++$i)
4437 my $d1 = hex($hex1list[$i]);
4438 my $d2 = hex($hex2list[$i]);
4439 my $dresult = ($d1 ^ $d2);
4440 $hexresultlist[$i] = sprintf("%x", $dresult);
4442 $hexresult = join('', @hexresultlist);
4446 # End of Handle login access
4449 ############################################################################
4451 # Handle foreign interpreters (i.e., scripting languages)
4453 # Insert perl code to execute scripts in foreign scripting languages.
4454 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
4455 # into an interpreter.
4456 # The code presented here is fairly confusing because it
4457 # actually writes perl code code to the output.
4459 # A table with the file handles
4460 %SCRIPTINGINPUT = ();
4462 # A function to clean up Client delivered CGI parameter values
4463 # (i.e., quote all odd characters)
4473 sub shrubCGIparameter # ($String) -> Cleaned string
4475 my $String = shift || "";
4477 # Change all quotes [`'"] into HTML character entities
4478 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
4481 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
4483 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
4485 next if $Char eq '&';
4486 $String =~ s/\Q$Char\E/$Transcript/isg;
4490 $String =~ s/[\n]/\\n/g;
4491 # Replace control characters with their backslashed octal ordinal numbers
4492 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
4493 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
4499 # The initial open statements: Open a pipe to the foreign script interpreter
4500 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
4502 my $ContentType = lc(shift) || return "";
4503 my $NewDirective = "";
4505 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
4507 # Construct a unique file handle name
4508 $SCRIPTINGFILEHANDLE = uc($ContentType);
4509 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
4510 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
4511 unless $SCRIPTINGINPUT{$ContentType};
4513 # Create the relevant script: Open the pipe to the interpreter
4514 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
4515 # Open interpreter for '$ContentType'
4516 # Open pipe to interpreter (if it isn't
open already
)
4517 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main
::dieHandler
(14, "$ContentType: \$!\\n");
4518 BLOCKCGISCRIPTOROPEN
4520 # Insert Initialization code and CGI variables
4521 $NewDirective .= InitializeForeignScript
($ContentType);
4524 return $NewDirective;
4528 # The final closing code to stop the interpreter
4529 sub CloseForeignScript
# ($ContentType) -> $DirectivePrefix
4531 my $ContentType = lc(shift) || return "";
4532 my $NewDirective = "";
4534 # Do nothing unless the pipe realy IS open
4535 return "" unless $SCRIPTINGINPUT{$ContentType};
4538 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
4541 # Write the Postfix code
4542 $NewDirective .= CleanupForeignScript
($ContentType);
4544 # Create the relevant script: Close the pipe to the interpreter
4545 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
4546 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
4547 select(STDOUT); \$|=1;
4549 BLOCKCGISCRIPTORCLOSE
4551 # Remove the file handler of the foreign script
4552 delete($SCRIPTINGINPUT{$ContentType});
4554 return $NewDirective;
4558 # The initialization code for the foreign script interpreter
4559 sub InitializeForeignScript
# ($ContentType) -> $DirectivePrefix
4561 my $ContentType = lc(shift) || return "";
4562 my $NewDirective = "";
4564 # Add initialization code
4565 if($ScriptingInitialization{$ContentType})
4567 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
4568 # Initialization Code for '$ContentType'
4569 # Select relevant output filehandle
4570 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4572 # The Initialization code (if any)
4573 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
4574 $ScriptingInitialization{$ContentType}
4575 ${ContentType}INITIALIZATIONCODE
4577 BLOCKCGISCRIPTORINIT
4580 # Add all CGI variables defined
4581 if(exists($ScriptingCGIvariables{$ContentType}))
4583 # Start writing variable definitions to the Interpreter
4584 if($ScriptingCGIvariables{$ContentType})
4586 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
4587 # CGI variables (from the %default_values table)
4588 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
4589 BLOCKCGISCRIPTORVARDEF
4593 foreach $N (keys(%default_values))
4595 # Determine whether the parameter has been defined
4596 # (the eval is a workaround to get at the variable value)
4597 next unless eval("defined(\$CGIexecute::$N)");
4599 # Get the value from the EXECUTION environment
4600 $V = eval("\$CGIexecute::$N");
4601 # protect control characters (i.e., convert them to \0.. form)
4602 $V = shrubCGIparameter
($V);
4604 # Protect interpolated variables
4605 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
4607 # Print the actual declaration for this scripting language
4608 if($ScriptingCGIvariables{$ContentType})
4610 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
4611 $NewDirective .= "\n";
4615 # Stop writing variable definitions to the Interpreter
4616 if($ScriptingCGIvariables{$ContentType})
4618 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
4619 ${ContentType}CGIVARIABLES
4620 BLOCKCGISCRIPTORVARDEFEND
4625 $NewDirective .= << "BLOCKCGISCRIPTOREND";
4627 # Select STDOUT filehandle
4628 select(STDOUT
); \
$|=1;
4632 return $NewDirective;
4636 # The cleanup code for the foreign script interpreter
4637 sub CleanupForeignScript
# ($ContentType) -> $DirectivePrefix
4639 my $ContentType = lc(shift) || return "";
4640 my $NewDirective = "";
4642 # Return if not needed
4643 return $NewDirective unless $ScriptingCleanup{$ContentType};
4645 # Create the relevant script: Open the pipe to the interpreter
4646 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
4647 # Cleanup Code for '$ContentType'
4648 # Select relevant output filehandle
4649 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4650 # Print Cleanup code to foreign script
4651 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
4652 $ScriptingCleanup{$ContentType}
4653 ${ContentType}SCRIPTSTOP
4655 # Select STDOUT filehandle
4656 select(STDOUT); \$|=1;
4657 BLOCKCGISCRIPTORSTOP
4659 return $NewDirective;
4663 # The prefix code for each <script></script> block
4664 sub PrefixForeignScript
# ($ContentType) -> $DirectivePrefix
4666 my $ContentType = lc(shift) || return "";
4667 my $NewDirective = "";
4669 # Return if not needed
4670 return $NewDirective unless $ScriptingPrefix{$ContentType};
4673 # If the CGIvariables parameter is defined, but empty, interpolate
4674 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4675 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4676 !$ScriptingCGIvariables{$ContentType};
4678 # Add initialization code
4679 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
4680 # Prefix Code for '$ContentType'
4681 # Select relevant output filehandle
4682 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4684 # The block Prefix code (if any)
4685 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
4686 $ScriptingPrefix{$ContentType}
4687 ${ContentType}PREFIXCODE
4688 # Select STDOUT filehandle
4689 select(STDOUT); \$|=1;
4690 BLOCKCGISCRIPTORPREFIX
4692 return $NewDirective;
4696 # The postfix code for each <script></script> block
4697 sub PostfixForeignScript
# ($ContentType) -> $DirectivePrefix
4699 my $ContentType = lc(shift) || return "";
4700 my $NewDirective = "";
4702 # Return if not needed
4703 return $NewDirective unless $ScriptingPostfix{$ContentType};
4706 # If the CGIvariables parameter is defined, but empty, interpolate
4707 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4708 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4709 !$ScriptingCGIvariables{$ContentType};
4711 # Create the relevant script: Open the pipe to the interpreter
4712 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
4713 # Postfix Code for '$ContentType'
4714 # Select filehandle to interpreter
4715 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4716 # Print postfix code to foreign script
4717 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
4718 $ScriptingPostfix{$ContentType}
4719 ${ContentType}SCRIPTPOSTFIX
4720 # Select STDOUT filehandle
4721 select(STDOUT); \$|=1;
4722 BLOCKCGISCRIPTORPOSTFIX
4724 return $NewDirective;
4727 sub InsertForeignScript
# ($ContentType, $directive, @SRCfile) -> $NewDirective
4729 my $ContentType = lc(shift) || return "";
4730 my $directive = shift || return "";
4732 my $NewDirective = "";
4735 # If the CGIvariables parameter is defined, but empty, interpolate
4736 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4737 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4738 !$ScriptingCGIvariables{$ContentType};
4740 # Create the relevant script
4741 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4742 # Insert Code for '$ContentType'
4743 # Select filehandle to interpreter
4744 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4745 BLOCKCGISCRIPTORINSERT
4747 # Use SRC feature files
4749 while($ThisSRCfile = shift(@_))
4752 if($ThisSRCfile =~ /^\s*\{\s*/)
4755 $Block = $` if $Block =~ /\s*\}\s*$/;
4756 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
4757 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
4759 ${ContentType}SRCBLOCKCODE
4760 BLOCKCGISCRIPTORSRCBLOCK
4766 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
4768 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
4769 while(<SCRIPTINGSOURCE>)
4771 print $SCRIPTINGINPUT{$ContentType} \$_;
4773 close(SCRIPTINGSOURCE);
4775 BLOCKCGISCRIPTORSRCFILES
4782 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4783 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
4785 ${ContentType}DIRECTIVECODE
4786 BLOCKCGISCRIPTORINSERT
4790 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
4791 # Select STDOUT filehandle
4792 select(STDOUT); \$|=1;
4793 BLOCKCGISCRIPTORSELECT
4796 return $NewDirective;
4799 sub CloseAllForeignScripts
# Call CloseForeignScript on all open scripts
4802 foreach $ContentType (keys(%SCRIPTINGINPUT))
4804 my $directive = CloseForeignScript
($ContentType);
4805 print STDERR
"\nDirective $CGI_Date: ", $directive;
4806 CGIexecute
->evaluate($directive);
4811 # End of handling foreign (external) scripting languages.
4813 ############################################################################
4815 # A subroutine to handle "nested" quotes, it cuts off the leading
4816 # item or quoted substring
4818 # ' A_word and more words' -> @('A_word', ' and more words')
4819 # '"quoted string" The rest' -> @('quoted string', ' The rest')
4820 # (this is needed for parsing the <TAGS> and their attributes)
4821 my $SupportedQuotes = "\'\"\`\(\{\[";
4822 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
4823 sub ExtractQuotedItem
# ($String) -> @($QuotedString, $RestOfString)
4826 my $String = shift || return @Result;
4828 if($String =~ /^\s*([\w\/\
-\
.]+)/is
)
4830 push(@Result, $1, $');
4832 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
4834 my $BackSlash = $1 || "";
4836 my $CloseQuote = $OpenQuote;
4837 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
4841 $String =~ /^\s*\\\Q$OpenQuote\E/i;
4843 $Onset =~ /\\\Q$CloseQuote\E/i;
4846 push(@Result, $Item, $Rest);
4851 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
4852 push(@Result, $1, $');
4857 push(@Result, "", $String);
4862 # Now, start with the real work
4864 # Control the output of the Content-type: text/html\n\n message
4865 my $SupressContentType = 0;
4868 sub ProcessFile
# ($file_path)
4870 my $file_path = shift || return 0;
4873 # Generate a unique file handle (for recursions)
4875 my $FileHandle = "file";
4877 while(!eof($FileHandle.$n)) {++$n;};
4881 # Use the default Content-type if this is NOT a raw file
4882 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@
($RawFilePattern)$@i)
4883 || $SupressContentType)
4885 $ENV{'PATH_INFO'} =~ m@
($FilePattern)$@i;
4886 my $ContentType = $ContentTypeTable{$1};
4887 print "Content-type: $ContentType\n";
4888 if(%SETCOOKIELIST && keys(%SETCOOKIELIST))
4890 foreach my $name (keys(%SETCOOKIELIST))
4892 my $value = $SETCOOKIELIST{$name};
4893 print "Set-Cookie: $name=$value\n";
4895 # Cookies are set only ONCE
4896 %SETCOOKIELIST = ();
4899 $SupressContentType = 1; # Content type has been printed
4903 # Get access to the actual data. This can be from RAM (by way of an
4904 # environment variable) or by opening a file.
4906 # Handle the use of RAM images (file-data is stored in the
4907 # $CGI_FILE_CONTENTS environment variable)
4908 # Note that this environment variable will be cleared, i.e., it is strictly for
4910 if($ENV{$CGI_FILE_CONTENTS})
4912 # File has been read already
4913 $_ = $ENV{$CGI_FILE_CONTENTS};
4914 # Sorry, you have to do the reading yourself (dynamic document creation?)
4915 # NOTE: you must read the whole document at once
4918 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
4920 else # Clear environment variable
4922 $ENV{$CGI_FILE_CONTENTS} = '-';
4925 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
4926 # THIS IS A SECURITY FEATURE!
4927 elsif($file_path eq '-' || (-e
"$file_path" && -r _
&& -T _
&& -f _
&& ! (-x _
|| -X _
) ))
4929 open($FileHandle, $file_path) || dieHandler
(17, "<h2>File not found</h2>\n");
4930 push(@OpenFiles, $file_path);
4931 $_ = <$FileHandle>; # Read first line
4933 elsif( -e
"$file_path" && -r _
&& -T _
&& -f _
&& $useFAT )
4935 open($FileHandle, $file_path) || dieHandler
(17, "<h2>File not found</h2>\n");
4936 push(@OpenFiles, $file_path);
4937 $_ = <$FileHandle>; # Read first line
4941 print "<h2>File not found</h2>\n";
4942 dieHandler
(18, "$file_path\n");
4945 $| = 1; # Flush output buffers
4947 # Initialize variables
4948 my $METAarguments = ""; # The CGI arguments from the latest META tag
4949 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
4950 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
4953 # Send document to output
4954 # Process the requested document.
4955 # Do a loop BEFORE reading input again (this catches the RAM/Database
4956 # type of documents).
4960 # Handle translations if needed
4962 performTranslation
(\
$_) if $TranslationPaths;
4964 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
4965 # There can be more than 1 <SCRIPT> or META tags on a line
4966 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
4969 # Store rest of line
4973 my $TagType = uc($1);
4974 # The before part can be send to the output
4977 # Read complete Tag from after and/or file
4978 until($After =~ /([^\\])\>/)
4980 $After .= <$FileHandle>;
4981 performTranslation(\$After) if $TranslationPaths;
4984 if($After =~ /([^\\])\>/)
4986 $ScriptTag .= $`.$&; # Keep the Script Tag intact
4991 dieHandler(19, "Closing > not found\n");
4994 # The tag could be closed by />, we handle this in the XML way
4995 # and don't process any content
(we ignore whitespace
)
4996 $ClosedTag = ($ScriptTag =~ m@
[^\\]/\s
*\
>\s
*$@
) ?
1 : 0;
5000 my $TypeName = ($TagType =~ /META/is) ?
"CONTENT" : "TYPE";
5001 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
5003 # Parse <SCRIPT> or <META> directive
5004 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
5005 # send the line to the output and go to the next loop
5006 my $CurrentContentType = "";
5007 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
5009 my ($Type) = ExtractQuotedItem
($');
5010 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
5011 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
5012 # CSS classes are aliases of $ServerScriptContentType
5013 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
5015 $CurrentContentType = $ServerScriptContentType;
5020 # Not a known server-side content type, print and continue
5021 unless(($CurrentContentType =~
5022 /$ServerScriptContentType|$ShellScriptContentType/is) ||
5023 $ScriptingLanguages{$CurrentContentType})
5031 # A known server-side content type, evaluate
5033 # First, handle \> and \<
5034 $ScriptTag =~ s/\\\>/\>/isg;
5035 $ScriptTag =~ s/\\\</\</isg;
5037 # Extract the CGI, SRC, ID, IF and UNLESS attributes
5038 my %ScriptTagAttributes = ();
5039 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
5044 ($Value, $ScriptTag) = ExtractQuotedItem
($Rest);
5045 $ScriptTagAttributes{uc($Attribute)} = $Value;
5049 # The attribute used to define the CGI variables
5050 # Extract CGI-variables from
5051 # <META CONTENT="text/ssperl; CGI='' SRC=''">
5052 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
5053 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
5054 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
5055 if($ScriptTagAttributes{'CGI'})
5057 @ARGV = (); # Reset ARGV
5059 $METAarguments = ""; # Reset the META CGI arguments
5061 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
5063 # Process default values of variables ($<name> = 'default value')
5064 # Allowed quotes are '', "", ``, (), [], and {}
5065 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
5067 my $varType = $2 || '$'; # Variable or list
5068 my $name = $3; # The Name
5072 if($Meta_CGI =~ /^\s*\=\s*/is)
5074 # Locate (any) default value
5075 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
5077 $RemainingTag = $Meta_CGI;
5080 # Define CGI (or ENV) variable, initalize it from the
5081 # Query string or the default value
5083 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
5084 # scripts to access the CGI arguments defined in the META tag
5085 # (Not for CGI inside <SCRIPT> tags)
5088 CGIexecute
::defineCGIvariable
($name, $default)
5089 || dieHandler
(20, "INVALID CGI name/value pair ($name, $default)\n");
5090 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
5091 # Add value to the @ARGV list
5092 push(@ARGV, ${"CGIexecute::$name"});
5095 elsif($varType eq '@')
5097 CGIexecute
::defineCGIvariableList
($name, $default)
5098 || dieHandler
(21, "INVALID CGI name/value list pair ($name, $default)\n");
5099 push(@METAvalues, "'".join("'", @
{"CGIexecute::$name"})."'");
5100 # Add value to the @ARGV list
5101 push(@ARGV, @
{"CGIexecute::$name"});
5102 $ARGC = scalar(@CGIexecute::ARGV
);
5104 elsif($varType eq '%')
5106 CGIexecute
::defineCGIvariableHash
($name, $default)
5107 || dieHandler
(22, "INVALID CGI name/value hash pair ($name, $default)\n");
5108 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
5109 push(@METAvalues, "'".join("'", @PairList)."'");
5110 # Add value to the @ARGV list
5111 push(@ARGV, %{"CGIexecute::$name"});
5112 $ARGC = scalar(@CGIexecute::ARGV
);
5115 # Store the values for internal and later use
5116 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
5118 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
5123 # The IF (conditional execution) Attribute
5124 # Evaluate the condition and stop unless it evaluates to true
5125 if($ScriptTagAttributes{'IF'})
5127 my $IFcondition = $ScriptTagAttributes{'IF'};
5129 # Convert SCRIPT calls, ./<script>
5130 $IFcondition =~ s@
([\W
]|^)\
./([\S
])@
$1$SCRIPT_SUB$2@g;
5132 # Convert FILE calls, ~/<file>
5133 $IFcondition =~ s@
([\W
])\
~/([\S
])@
$1$HOME_SUB$2@g;
5135 # Block execution if necessary
5136 unless(CGIexecute
->evaluate($IFcondition))
5138 %ScriptTagAttributes = ();
5139 $CurrentContentType = "";
5143 # The UNLESS (conditional execution) Attribute
5144 # Evaluate the condition and stop if it evaluates to true
5145 if($ScriptTagAttributes{'UNLESS'})
5147 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
5149 # Convert SCRIPT calls, ./<script>
5150 $UNLESScondition =~ s@
([\W
]|^)\
./([\S
])@
$1$SCRIPT_SUB$2@g;
5152 # Convert FILE calls, ~/<file>
5153 $UNLESScondition =~ s@
([\W
])\
~/([\S
])@
$1$HOME_SUB$2@g;
5155 # Block execution if necessary
5156 if(CGIexecute
->evaluate($UNLESScondition))
5158 %ScriptTagAttributes = ();
5159 $CurrentContentType = "";
5163 # The SRC (Source File) Attribute
5164 # Extract any source script files and add them in
5165 # front of the directive
5166 # The SRC list should be emptied
5170 my $PrefixDirective = "";
5171 my $PostfixDirective = "";
5172 # There is a SRC attribute
5173 if($ScriptTagAttributes{'SRC'})
5175 $SRCtag = $ScriptTagAttributes{'SRC'};
5176 # Remove "file://" prefixes
5177 $SRCtag =~ s@
([^\w\
/\\]|^)file\://([^\s\/\@\
=])@
$1$2@gis;
5178 # Expand script filenames "./Script"
5179 $SRCtag =~ s@
([^\w\
/\\]|^)\./([^\s\
/\@\=])@$1$SCRIPT_SUB/$2@gis;
5180 # Expand script filenames "~/Script"
5181 $SRCtag =~ s@
([^\w\
/\\]|^)\~/([^\s\
/\@\=])@$1$HOME_SUB/$2@gis;
5185 while($SRCtag =~ /\S/is)
5187 my $SRCdirective = "";
5189 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
5191 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
5193 my $InsertionPlace = $1;
5196 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
5200 # {}-blocks are just evaluated by "do"
5201 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
5204 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
5208 # SAFEqx shell script blocks
5209 if($CurrentContentType =~ /$ShellScriptContentType/is)
5211 # Handle ''-quotes inside the script
5212 $SRCblock =~ s/[\']/\\$&/gis;
5214 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
5215 $SRCdirective .= $SRCblock."\n";
5218 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
5220 $SRCblock = "print do { $SRCblock };'';";
5221 $SRCdirective .= $SRCblock."\n";
5223 else # The interpreter should handle this
5225 push(@SRClist, "{ $SRCblock }");
5230 { dieHandler(23, "Closing \} missing\n");};
5232 # Files are processed as Text or Executable files
5233 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
5238 # We are handling one of the external interpreters
5239 if($ScriptingLanguages{$CurrentContentType})
5241 push(@SRClist, $SrcFile);
5243 # We are at the start of a DIV tag, just load all SRC files and/or URL's
5244 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
5246 # $SrcFile is a URL pointing to an HTTP or FTP server
5247 if($SrcFile =~ m!^([a-z]+)\://!)
5249 my $URLoutput = CGIscriptor::read_url($SrcFile);
5250 $SRCdirective .= $URLoutput;
5252 # SRC file is an existing file
5253 elsif(-e "$SrcFile")
5255 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
5257 while(sysread(DIVSOURCE, $Content, 1024) > 0)
5259 $SRCdirective .= $Content;
5264 # Executable files are executed as
5265 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
5266 elsif(-x "$SrcFile")
5268 $SRCdirective .= "print \`$SrcFile @METAvalues\
`;'';\n";
5270 # Handle 'standard' files, using ProcessFile
5271 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
5272 && $SrcFile =~ m@($FilePattern)$@) # A recursion
5275 # Do not process still open files because it can lead
5276 # to endless recursions
5277 if(grep(/^$SrcFile$/, @OpenFiles))
5278 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
5279 # Prepare meta arguments
5280 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5282 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
5284 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
5286 $SRCdirective .= GET_URL($SrcFile);
5288 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
5290 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5291 $SRCdirective .= "do \'$SrcFile\';'';\n";
5293 else # This one could not be resolved (should be handled by BinaryMapFile)
5295 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
5303 $PrefixDirective .= $SRCdirective;
5307 $PostfixDirective .= $SRCdirective;
5310 # The prefix should be handled immediately
5311 $directive .= $PrefixDirective;
5312 $PrefixDirective = "";
5316 # Handle the content of the <SCRIPT></SCRIPT> tags
5317 # Do not process the content of <SCRIPT/>
5318 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
5320 my $EndScriptTag = "";
5322 # Execute SHELL scripts with SAFEqx()
5323 if($CurrentContentType =~ /$ShellScriptContentType/is)
5325 $directive .= "SAFEqx(\'";
5329 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
5331 $After .= <$FileHandle>;
5332 performTranslation(\$After) if $TranslationPaths;
5335 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
5343 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO
'}\n");
5346 # Process only when content should be executed
5347 if($CurrentContentType)
5350 # Remove all comments from Perl scripts
5351 # (NOT from OS shell scripts)
5352 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
5353 if $CurrentContentType =~ /$ServerScriptContentType/i;
5355 # Convert SCRIPT calls, ./<script>
5356 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5358 # Convert FILE calls, ~/<file>
5359 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5361 # Execute SHELL scripts with SAFEqx(), closing bracket
5362 if($CurrentContentType =~ /$ShellScriptContentType/i)
5364 # Handle ''-quotes inside the script
5365 $directive =~ /SAFEqx\(\'/;
5367 my $Executable = $';
5368 $Executable =~ s/[\']/\\$&/gs;
5370 $directive .= $Executable."\');"; # Closing bracket
5378 # Handle the content of the <DIV></DIV> tags
5379 # Do not process the content of <DIV/>
5380 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
5382 my $EndScriptTag = "";
5385 while($After !~ /\<\s*\/$TagType[^\
>]*\
>/is
&& !eof($FileHandle))
5387 $After .= <$FileHandle>;
5388 performTranslation
(\
$After) if $TranslationPaths;
5391 if($After =~ /\<\s*\/$TagType[^\
>]*\
>/is
)
5399 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
5402 # Add the Postfixed directives (but only when it contains something printable)
5403 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5404 $PostfixDirective = "";
5407 # Process only when content should be handled
5408 if($CurrentContentType)
5411 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
5412 # a valid Perl name). Names should not contain $, but we can handle it.
5413 my $name = $ScriptTagAttributes{'ID'};
5414 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
5417 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
5418 CGIexecute::defineCGIexecuteVariable($name, $directive);
5422 # Nothing to execute
5427 # Handle Foreign scripting languages
5428 if($ScriptingLanguages{$CurrentContentType})
5430 my $newDirective = "";
5431 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
5432 $newDirective .= PrefixForeignScript($CurrentContentType);
5433 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
5434 $newDirective .= PostfixForeignScript($CurrentContentType);
5435 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
5437 $newDirective .= '"";';
5439 $directive = $newDirective;
5443 # Add the Postfixed directives (but only when it contains something printable)
5444 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5445 $PostfixDirective = "";
5448 # EXECUTE the script and print the results
5450 # Use this to debug the program
5451 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
5453 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
5454 $Result =~ s/\n$//g; # Remove final newline
5456 # Print the Result of evaluating the directive
5457 # (this will handle LARGE, >64 kB output)
5458 my $BytesWritten = 1;
5459 while($Result && $BytesWritten)
5461 $BytesWritten = syswrite(STDOUT, $Result, 64);
5462 $Result = substr($Result, $BytesWritten);
5464 # print $Result; # Could be used instead of above code
5466 # Store result if wanted, i.e., if $CGIscriptorResults has been
5467 # defined in a <META> tag.
5468 push(@CGIexecute::CGIscriptorResults, $Result)
5469 if exists($default_values{'CGIscriptorResults'});
5471 # Process the rest of the input line (this could contain
5472 # another directive)
5476 } while(<$FileHandle>); # Read and Test AFTER first loop!
5478 close ($FileHandle);
5479 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
5483 ###############################################################################
5485 # Call the whole package
5491 # Initialization Code
5492 Initialize_Request();
5494 # SECURITY: ACCESS CONTROL
5497 # Read the POST part of the query, if there is one
5498 Get_POST_part_of_query();
5500 # Start (HTML) output and logging
5501 $file_path = Initialize_output();
5503 # Check login access or divert to login procedure
5504 $Use_Login = Log_In_Access();
5505 $file_path = $Use_Login if $Use_Login;
5507 # Record which files are still open (to avoid endless recursions)
5510 # Record whether the default HTML ContentType has already been printed
5511 # but only if the SERVER uses HTTP or some other protocol that might interpret
5512 # a content MIME type.
5514 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
5516 # Process the specified file
5517 ProcessFile($file_path) if $file_path ne $SS_PUB;
5519 # Cleanup all open external (foreign) interpreters
5520 CloseAllForeignScripts();
5526 # Make a single call to handle an (empty) request
5530 # END OF PACKAGE MAIN
5533 ####################################################################################
5535 # The CGIEXECUTE PACKAGE
5537 ####################################################################################
5539 # Isolate the evaluation of directives as PERL code from the rest of the program.
5540 # Remember that each package has its own name space.
5541 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
5542 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
5549 my $directive = shift;
5550 $directive = eval($directive);
5551 warn $@ if $@; # Write an error message to STDERR
5552 $directive; # Return value of directive
5556 # defineCGIexecuteVariable($name [, $value]) -> 0/1
5558 # Define and intialize variables inside CGIexecute
5559 # Does no sanity checking, for internal use only
5561 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
5563 my $name = shift || return 0; # The Name
5564 my $value = shift || ""; # The value
5571 # Protect certain CGI variables values when set internally
5572 # If not defined internally, there will be no variable set AT ALL
5573 my %CGIprotectedVariable = ();
5574 sub ProtectCGIvariable # ($name) -> 0/1
5576 my $name = shift || "";
5577 return 0 unless $name && $name =~ /\w/;
5579 ++$CGIprotectedVariable{$name};
5581 return $CGIprotectedVariable{$name};
5584 # defineCGIvariable($name [, $default]) -> 0/1
5586 # Define and intialize CGI variables
5587 # Tries (in order) $ENV{$name}, the Query string and the
5589 # Removes all '-quotes etc.
5591 sub defineCGIvariable # ($name [, $default]) -> 0/1
5593 my $name = shift || return 0; # The Name
5594 my $default = shift || ""; # The default value
5596 # Protect variables set internally
5597 return 1 if !$name || exists($CGIprotectedVariable{$name});
5599 # Remove \-quoted characters
5600 $default =~ s/\\(.)/$1/g;
5601 # Store default values
5602 $::default_values{$name} = $default if $default;
5606 # If there is a user supplied value, it replaces the
5609 # Environment values have precedence
5610 if(exists($ENV{$name}))
5612 $temp = $ENV{$name};
5614 # Get name and its value from the query string
5615 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5617 $temp = ::YOUR_CGIPARSE($name);
5619 # Defined values must exist for security
5620 elsif(!exists($::default_values{$name}))
5622 $::default_values{$name} = undef;
5625 # SECURITY, do not allow '- and `-quotes
in
5627 # Remove all existing '-quotes
5628 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5629 $temp =~ s/[\']/’/igs; # Remove all single quotes
5630 $temp =~ s/[\`]/‘/igs; # Remove all backtick quotes
5631 # If $temp is empty, use the default value (if it exists)
5632 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
5634 $temp = $::default_values
{$name};
5635 # Remove all existing '-quotes
5636 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5637 $temp =~ s/[\']/’/igs; # Remove all single quotes
5638 $temp =~ s/[\`]/‘/igs; # Remove all backtick quotes
5640 else # Store current CGI values and remove defaults
5642 $::default_values
{$name} = $temp;
5644 # Define the CGI variable and its value (in the execute package)
5651 sub defineCGIvariableList
# ($name [, $default]) -> 0/1)
5653 my $name = shift || return 0; # The Name
5654 my $default = shift || ""; # The default value
5656 # Protect variables set internally
5657 return 1 if !$name || exists($CGIprotectedVariable{$name});
5659 # Defined values must exist for security
5660 if(!exists($::default_values
{$name}))
5662 $::default_values
{$name} = $default;
5669 # Environment values have precedence
5670 if(exists($ENV{$name}))
5672 push(@temp, $ENV{$name});
5674 # Get name and its values from the query string
5675 elsif($ENV{QUERY_STRING
} =~ /$name/) # $name is in the query string
5677 push(@temp, ::YOUR_CGIPARSE
($name, 1)); # Extract LIST
5681 push(@temp, $::default_values
{$name});
5685 # SECURITY, do not allow '- and `-quotes in
5687 # Remove all existing '-quotes
5688 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
5689 @temp = map {s/[\']/’/igs; $_} @temp; # Remove all single quotes
5690 @temp = map {s/[\`]/‘/igs; $_} @temp; # Remove all backtick quotes
5692 # Store current CGI values and remove defaults
5693 $::default_values
{$name} = $temp[0];
5695 # Define the CGI variable and its value (in the execute package)
5702 sub defineCGIvariableHash
# ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
5704 my $name = shift || return 0; # The Name
5705 my $default = shift || ""; # The default value
5707 # Protect variables set internally
5708 return 1 if !$name || exists($CGIprotectedVariable{$name});
5710 # Defined values must exist for security
5711 if(!exists($::default_values
{$name}))
5713 $::default_values
{$name} = $default;
5720 # Environment values have precedence
5721 if(exists($ENV{$name}))
5723 $temp{""} = $ENV{$name};
5725 # Get name and its values from the query string
5726 elsif($ENV{QUERY_STRING
} =~ /$name/) # $name is in the query string
5728 %temp = ::YOUR_CGIPARSE
($name, -1); # Extract HASH table
5730 elsif($::default_values
{$name} ne "")
5732 $temp{""} = $::default_values
{$name};
5736 # SECURITY, do not allow '- and `-quotes in
5738 # Remove all existing '-quotes
5740 foreach $Key (keys(%temp))
5742 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5743 $temp{$Key} =~ s/[\']/’/igs; # Remove all single quotes
5744 $temp{$Key} =~ s/[\`]/‘/igs; # Remove all backtick quotes
5747 # Store current CGI values and remove defaults
5748 $::default_values
{$name} = $temp{""};
5750 # Define the CGI variable and its value (in the execute package)
5753 foreach $tempKey (keys(%temp))
5755 ${$name}{$tempKey} = $temp{$tempKey};
5763 # SAFEqx('CommandString')
5765 # A special function that is a safe alternative to backtick quotes (and qx//)
5766 # with client-supplied CGI values. All CGI variables are surrounded by
5767 # single ''-quotes (except between existing \'\'-quotes, don't try to be
5768 # too smart). All variables are then interpolated. Simple (@) lists are
5769 # expanded with join(' ', @List), and simple (%) hash tables expanded
5770 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
5771 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
5772 # $@% that should NOT be interpolated must be preceeded by a "\".
5773 # If the first line of the String starts with "#! interpreter", the
5774 # remainder of the string is piped into interpreter (after interpolation), i.e.,
5775 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
5776 # just like in UNIX. There are some problems with quotes. Be carefull in
5777 # using them. You do not have access to the output of any piped (#!)
5778 # process! If you want such access, execute
5779 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
5780 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
5783 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
5784 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
5785 sub SAFEqx
# ('String') -> result of executing qx/"String"/
5787 my $CommandString = shift;
5788 my $NewCommandString = "";
5790 # Only interpolate when required (check the On/Off switch)
5791 unless($CGIscriptor::NoShellScriptInterpolation
)
5794 # Handle existing single quotes around CGI values
5795 while($CommandString =~ /\'[^\']+\'/s)
5797 my $CurrentQuotedString = $&;
5798 $NewCommandString .= $`;
5799 $CommandString = $'; # The remaining string
5800 # Interpolate CGI variables between quotes
5801 # (e.g., '$CGIscriptorResults[-1]')
5802 $CurrentQuotedString =~
5803 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
5804 "$1".eval("$2$3")}else{"$&"}/egs;
5806 # Combine result with previous result
5807 $NewCommandString .= $CurrentQuotedString;
5809 $CommandString = $NewCommandString.$CommandString;
5811 # Select known CGI variables and surround them with single quotes,
5812 # then interpolate all variables
5814 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
5815 if($2 eq '$' && exists($main::default_values{$4}))
5816 {"$1\'".eval("\$$3")."\'";}
5817 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
5818 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
5820 else{$1.eval("${2}$3");
5823 # Remove backslashed [$@%]
5824 $CommandString =~ s/\\([\$\@\%])/$1/gs;
5828 # return $CommandString;
5830 # Handle UNIX style "#! shell command\n" constructs as
5831 # a pipe into the shell command. The output cannot be tapped.
5832 my $ReturnValue = "";
5833 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
5835 my $ShellScripts = $';
5836 my $ShellCommand = $1;
5837 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
5838 select(INTERPRETER);$| = 1;
5839 print INTERPRETER $ShellScripts;
5841 select(STDOUT);$| = 1;
5843 # Shell scripts which are redirected to an existing named pipe.
5844 # The output cannot be tapped.
5845 elsif($CGIscriptor::ShellScriptPIPE)
5847 CGIscriptor::printSAFEqxPIPE($CommandString);
5849 else # Plain ``-backtick execution
5851 # Execute the commands
5852 $ReturnValue = qx/$CommandString/;
5854 return $ReturnValue;
5857 ####################################################################################
5859 # The CGIscriptor PACKAGE
5861 ####################################################################################
5863 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
5866 package CGIscriptor;
5869 # The Interpolation On/Off switch
5870 my $NoShellScriptInterpolation = undef;
5871 # The ShellScript redirection pipe
5872 my $ShellScriptPIPE = undef;
5874 # Open a named PIPE for SAFEqx to receive ALL shell scripts
5875 sub RedirectShellScript # ('CommandString')
5877 my $CommandString = shift || undef;
5881 $ShellScriptPIPE = "ShellScriptNamedPipe";
5882 open($ShellScriptPIPE, "|$CommandString")
5883 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
5887 close($ShellScriptPIPE);
5888 $ShellScriptPIPE = undef;
5890 return $ShellScriptPIPE;
5893 # Print to redirected shell script pipe
5894 sub printSAFEqxPIPE # ("String") -> print return value
5896 my $String = shift || undef;
5898 select($ShellScriptPIPE); $| = 1;
5899 my $returnvalue = print $ShellScriptPIPE ($String);
5900 select(STDOUT); $| = 1;
5902 return $returnvalue;
5905 # a pointer to CGIexecute::SAFEqx
5906 sub SAFEqx # ('String') -> result of qx/"String"/
5908 my $CommandString = shift;
5909 return CGIexecute::SAFEqx($CommandString);
5913 # a pointer to CGIexecute::defineCGIvariable
5914 sub defineCGIvariable # ($name[, $default]) ->0/1
5917 my $default = shift;
5918 return CGIexecute::defineCGIvariable($name, $default);
5922 # a pointer to CGIexecute::defineCGIvariable
5923 sub defineCGIvariableList # ($name[, $default]) ->0/1
5926 my $default = shift;
5927 return CGIexecute::defineCGIvariableList($name, $default);
5931 # a pointer to CGIexecute::defineCGIvariable
5932 sub defineCGIvariableHash # ($name[, $default]) ->0/1
5935 my $default = shift;
5936 return CGIexecute::defineCGIvariableHash($name, $default);
5940 # Decode URL encoded arguments
5941 sub URLdecode # (URL encoded input) -> string
5948 my $EncodedValue = $Value; # Do not change the loop variable
5949 # Convert all "+" to " "
5950 $EncodedValue =~ s/\+/ /g;
5951 # Convert all hexadecimal codes (%FF) to their byte values
5952 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
5954 $output .= $`.chr(hex($1));
5957 $output .= $EncodedValue; # The remaining part of $Value
5962 # Encode arguments as URL codes.
5963 sub URLencode # (input) -> URL encoded string
5970 my @CharList = split('', $Value);
5971 foreach $char (@CharList)
5975 elsif($char =~ /\w\-/)
5976 { $output .= $char;}
5979 $output .= uc(sprintf("%%%2.2x", ord($char)));
5986 # Extract the value of a CGI variable from the URL-encoded $string
5987 # Also extracts the data blocks from a multipart request. Does NOT
5988 # decode the multipart blocks
5989 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
5991 my $ValueName = shift;
5992 my $QueryString = shift || $main::ENV{'QUERY_STRING
'};
5993 my $ReturnReference = shift || undef;
5996 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
5998 $output = URLdecode($2);
5999 $$ReturnReference = $' if ref($ReturnReference);
6001 # Get multipart POST or PUT methods
6002 elsif($main::ENV
{'CONTENT_TYPE'} =~ m@
(multipart
/([\w\
-]+)\
;\s
+boundary\
=([\S
]+))@i)
6004 my $MultipartType = $2;
6005 my $BoundaryString = $3;
6006 # Remove the boundary-string
6007 my $temp = $QueryString;
6008 $temp =~ /^\Q--$BoundaryString\E/m;
6011 # Identify the newline character(s), this is the first character in $temp
6012 my $NewLine = "\r\n"; # Actually, this IS the correct one
6013 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
6015 # Is this correct??? I have to check.
6016 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
6017 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
6018 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
6019 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
6022 # search through all data blocks
6023 while($temp =~ /^\Q--$BoundaryString\E/m)
6027 # Get the empty line after the header
6028 $DataBlock =~ /$NewLine$NewLine/;
6034 # Remove newlines from the header
6035 $Header =~ s/$NewLine/ /g;
6037 # Look whether this block is the one you are looking for
6038 # Require the quotes!
6039 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
6042 for($i=length($NewLine); $i; --$i)
6049 # reinitialize the output
6052 $$ReturnReference = $temp if ref($ReturnReference);
6054 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
6057 $$ReturnReference = undef if ref($ReturnReference);
6061 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
6067 # Get a list of values for the same ValueName. Uses CGIparseValue
6069 sub CGIparseValueList
# (ValueName [, URL_encoded_QueryString]) -> List of decoded values
6071 my $ValueName = shift;
6072 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
6074 my $RestQueryString;
6076 while($QueryString &&
6077 (($Value = CGIparseValue
($ValueName, $QueryString, \
$RestQueryString))
6078 || defined($Value)))
6080 push(@output, $Value);
6081 $QueryString = $RestQueryString; # QueryString is consumed!
6083 # ready, return list with values
6087 sub CGIparseValueHash
# (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
6089 my $ValueName = shift;
6090 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
6091 my $RestQueryString;
6093 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
6096 my $Value = CGIparseValue
("$ValueName$Key", $QueryString, \
$RestQueryString);
6097 $output{$Key} = $Value;
6098 $QueryString = $RestQueryString; # QueryString is consumed!
6100 # ready, return list with values
6104 sub CGIparseForm
# ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
6106 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
6109 $QueryString =~ s/\&/\n/g;
6110 $output = URLdecode
($QueryString);
6115 # Extract the header of a multipart CGI variable from the POST input
6116 sub CGIparseHeader
# (ValueName [, URL_encoded_QueryString]) -> Decoded value
6118 my $ValueName = shift;
6119 my $QueryString = shift || $main::ENV
{'QUERY_STRING'};
6122 if($main::ENV
{'CONTENT_TYPE'} =~ m@
(multipart
/([\w\
-]+)\
;\s
+boundary\
=([\S
]+))@i)
6124 my $MultipartType = $2;
6125 my $BoundaryString = $3;
6126 # Remove the boundary-string
6127 my $temp = $QueryString;
6128 $temp =~ /^\Q--$BoundaryString\E/m;
6131 # Identify the newline character(s), this is the first character in $temp
6132 my $NewLine = "\r\n"; # Actually, this IS the correct one
6133 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
6135 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
6136 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
6137 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
6138 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
6141 # search through all data blocks
6142 while($temp =~ /^\Q--$BoundaryString\E/m)
6146 # Get the empty line after the header
6147 $DataBlock =~ /$NewLine$NewLine/;
6151 # Remove newlines from the header
6152 $Header =~ s/$NewLine/ /g;
6154 # Look whether this block is the one you are looking for
6155 # Require the quotes!
6156 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
6161 # reinitialize the output
6169 # Checking variables for security (e.g., file names and email addresses)
6170 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
6171 sub CGIsafeFileName
# FileName -> FileName or ""
6173 my $FileName = shift || "";
6174 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
6175 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
6176 return "" if $FileName =~ m@\
.\
.\Q
$::DirectorySeparator\E@
; # Higher directory not allowed
6177 return "" if $FileName =~ m@\Q
$::DirectorySeparator\E\
.\
.@
; # Higher directory not allowed
6178 return "" if $::BlockPathAccess
&& $FileName =~ m@
$::BlockPathAccess@
; # Invisible (blocked) file
6183 sub CGIsafeEmailAddress
# email -> email or ""
6185 my $Email = shift || "";
6186 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
6190 # Get a URL from the web. Needs main::GET_URL($URL) function
6191 # (i.e., curl, snarf, or wget)
6192 sub read_url
# ($URL) -> page/file
6194 my $URL = shift || return "";
6196 # Get the commands to read the URL, do NOT add a print command
6197 my $URL_command = main
::GET_URL
($URL, 1);
6198 # execute the commands, i.e., actually read it
6199 my $URLcontent = CGIexecute
->evaluate($URL_command);
6201 # Ready, return the content.
6205 ################################################>>>>>>>>>>Start Remove
6207 # BrowseAllDirs(Directory, indexfile)
6210 # <SCRIPT TYPE='text/ssperl'>
6211 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
6214 # Allows to browse all directories. Stops at '/'. If the directory contains
6215 # an indexfile, eg, index.html, that file will be used instead. Files must match
6216 # the $Pattern, if it is given. Default is
6217 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
6219 sub BrowseAllDirs
# (Directory, indexfile, $Pattern) -> Print HTML code
6221 my $Directory = shift || '/';
6222 my $indexfile = shift || 'index.html';
6223 my $Pattern = shift || '';
6224 $Directory =~ s!/$!!g;
6226 # If the index directory exists, use that one
6227 if(-s
"$::CGI_HOME$Directory/$indexfile")
6229 return main
::ProcessFile
("$::CGI_HOME$Directory/$indexfile");
6232 # No indexfile, continue
6233 my @DirectoryList = glob("$::CGI_HOME$Directory");
6234 $CurrentDirectory = shift(@DirectoryList);
6235 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6236 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6238 print "$CurrentDirectory" if $CurrentDirectory;
6241 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
6242 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6246 print "<pre><ul TYPE='NONE
'>\n";
6247 foreach $file (@AllFiles)
6249 next unless -d "$::CGI_HOME$Directory/$file";
6250 # Check whether this file should be visible
6251 next if $::BlockPathAccess &&
6252 "$Directory/$file/" =~ m@$::BlockPathAccess@;
6253 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
6255 print "</ul></pre>\n";
6258 print "<pre><ul TYPE='CIRCLE
'>\n";
6260 foreach $file (@AllFiles)
6262 next if $file =~ /^\./;
6263 next if -d "$::CGI_HOME$Directory/$file";
6264 next if -l "$::CGI_HOME$Directory/$file";
6265 # Check whether this file should be visible
6266 next if $::BlockPathAccess &&
6267 "$Directory/$file" =~ m@$::BlockPathAccess@;
6269 if(!$Pattern || $file =~ m@$Pattern@)
6271 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
6272 my $Size = -s "$::CGI_HOME$Directory/$file";
6273 $Size = sprintf("%6.0F kB", $Size/1024);
6274 my $Type = `file $::CGI_HOME$Directory/$file`;
6275 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
6279 print "<a href='$Directory/$file'>";
6280 printf("%-40s", "$file</a>");
6281 print "\t$Size\t$Date\t$Type";
6285 print "</ul></pre>";
6291 ################################################
6293 # BrowseDirs(RootDirectory [, Pattern, Start])
6296 # <SCRIPT TYPE='text
/ssperl
'>
6297 # CGIscriptor::BrowseDirs('Sounds
', '\
.aifc
$', 'Speech
', 'DIRECTORY
')
6300 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
6301 # e.g., the full path of the directory 'Speech
' is '~/Sounds/Speech
'.
6302 # Only files which fit /$Pattern/ and directories are displayed.
6303 # Directories down or up the directory tree are supplied with a
6304 # GET request with the name of the CGI variable in the fourth argument (default
6305 # is 'BROWSEDIRS
'). So the correct call for a subdirectory could be:
6306 # CGIscriptor::BrowseDirs('Sounds
', '\
.aifc
$', $DIRECTORY, 'DIRECTORY
')
6308 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
6310 my $RootDirectory = shift; # || return 0;
6311 my $Pattern = shift || '\S
';
6312 my $Start = shift || "";
6313 my $CGIvariable = shift || "BROWSEDIRS";
6314 my $HTTPserver = shift || '';
6316 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
6317 $Start =~ s@//+@/@g;
6318 $Start =~ s@[^/]+/\.\.@@ig;
6319 $Start =~ s@^\.\.@@ig;
6320 $Start =~ s@/\.$@@ig;
6322 $Start .= "/" if $Start;
6324 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
6325 $CurrentDirectory = shift(@Directory);
6326 $CurrentDirectory = $' if $CurrentDirectory =~ m@
(/\.\./)+@
;
6327 $CurrentDirectory =~ s@
^$::CGI_HOME@
@g;
6329 print "$CurrentDirectory" if $CurrentDirectory;
6331 opendir(BROWSE
, "$::CGI_HOME/$RootDirectory/$Start") || main
::dieHandler
(31, "$::CGI_HOME/$RootDirectory/$Start $!");
6332 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE
));
6336 print "<pre><ul TYPE='NONE'>\n";
6337 foreach $file (@AllFiles)
6339 next unless -d
"$::CGI_HOME/$RootDirectory/$Start$file";
6340 # Check whether this file should be visible
6341 next if $::BlockPathAccess
&&
6342 "/$RootDirectory/$Start$file/" =~ m@
$::BlockPathAccess@
;
6344 my $NewURL = $Start ?
"$Start$file" : $file;
6345 $NewURL = CGIscriptor
::URLencode
($NewURL);
6346 print "<dt><a href='";
6347 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME
} !~ m@
[^\w
+\
-/]@
;
6348 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
6350 print "</ul></pre>\n";
6353 print "<pre><ul TYPE='CIRCLE'>\n";
6355 foreach $file (@AllFiles)
6357 next if $file =~ /^\./;
6358 next if -d
"$::CGI_HOME/$RootDirectory/$Start$file";
6359 next if -l
"$::CGI_HOME/$RootDirectory/$Start$file";
6360 # Check whether this file should be visible
6361 next if $::BlockPathAccess
&&
6362 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@
$::BlockPathAccess@
;
6364 if($file =~ m@
$Pattern@
)
6366 my $Date = localtime($^T
- (-M
"$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
6367 my $Size = -s
"$::CGI_HOME/$RootDirectory/$Start$file";
6368 $Size = sprintf("%6.0F kB", $Size/1024);
6369 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
6370 $Type =~ s@\s
*$::CGI_HOME
/$RootDirectory/$Start$file\s
*\
:\s
*@
@ig;
6374 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
6376 print "<a href='$RootDirectory/$Start$file'>";
6380 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
6382 printf("%-40s", "$file</a>") if $HTTPserver;
6383 printf("%-40s", "$file") unless $HTTPserver;
6384 print "\t$Size\t$Date\t$Type";
6388 print "</ul></pre>";
6394 # ListDocs(Pattern [,ListType])
6397 # <SCRIPT TYPE=text/ssperl>
6398 # CGIscriptor::ListDocs("/*", "dl");
6401 # This subroutine is very usefull to manage collections of independent
6402 # documents. The resulting list will display the tree-like directory
6403 # structure. If this routine is too slow for online use, you can
6404 # store the result and use a link to that stored file.
6406 # List HTML and Text files with title and first header (HTML)
6407 # or filename and first meaningfull line (general text files).
6408 # The listing starts at the ServerRoot directory. Directories are
6409 # listed recursively.
6411 # You can change the list type (default is dl).
6413 # <dt><a href=<file.html>>title</a>
6415 # <dt><a href=<file.txt>>file.txt</a>
6416 # <dd>First meaningfull line of text
6418 sub ListDocs
# ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
6420 my $Pattern = shift;
6422 my $ListType = shift || "dl";
6423 my $Prefix = lc($ListType) eq "dl" ?
"dt" : "li";
6424 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6425 my @FileList = glob("$::CGI_HOME$Pattern");
6426 my ($FileName, $Path, $Link);
6428 # Print List markers
6429 print "<$ListType>\n";
6432 File
: foreach $FileName (@FileList)
6434 # Check whether this file should be visible
6435 next if $::BlockPathAccess
&& $FileName =~ m@
$::BlockPathAccess@
;
6437 # Recursively list files in all directories
6440 $FileName =~ m@
([^/]*)$@
;
6442 print "<$Prefix>$DirName\n";
6443 $Pattern =~ m@
([^/]*)$@
;
6444 &ListDocs
("$`$DirName/$1", $ListType);
6448 elsif(-T
"$FileName")
6450 open(TextFile
, $FileName) || next;
6452 # Ignore all other file types
6456 # Get file path for link
6457 $FileName =~ /$::CGI_HOME/;
6458 print "<$Prefix><a href=$URL_root$'>";
6459 # Initialize all variables
6464 # Read file and step through
6470 if($FileName =~ /\.ht[a-zA-Z]*$/i)
6475 if($Line =~ m@
<title
>([^<]*)</title
>@i)
6482 $Line .= <TextFile> || goto Print;
6486 # Catch First Header
6489 if($Line =~ m@</h1>@i)
6493 $Caption =~ m@
<h1
>@i;
6495 $Line = $`.$Caption.$Line;
6499 $Line .= <TextFile> || goto Print;
6507 # Title equals file name
6508 $FileName =~ /([^\/]+)$/;
6510 # Catch equals First Meaningfull line
6513 if($Line =~ /[A-Z]/ &&
6514 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
6515 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
6517 $Line =~ s/\<[^\>]+\>//g;
6522 $Line = <TextFile> || goto Print;
6526 Print: # Print title and subject
6527 print "$Title</a>\n";
6528 print "<dd>$Caption\n" if $ListType eq "dl";
6535 # Print Closing List Marker
6536 print "</$ListType>\n";
6537 ""; # Empty return value
6541 # HTMLdocTree(Pattern [,ListType])
6544 # <SCRIPT TYPE=text/ssperl>
6545 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
6548 # The following subroutine is very usefull for checking large document
6549 # trees. Starting from the root (s), it reads all files and prints out
6550 # a nested list of links to all attached files. Non-existing or misplaced
6551 # files are flagged. This is quite a file-i/o intensive routine
6552 # so you would not like it to be accessible to everyone. If you want to
6553 # use the result, save the whole resulting page to disk and use a link
6556 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
6557 # with links to *local* files (i.e., only links to the local server are
6558 # followed). The list entries are the document titles.
6559 # If the list type is <dl>, the first <H1> header is used too.
6560 # For each file matching the pattern, a list is made recursively of all
6561 # HTML documents that are linked from it and are stored in the same directory
6562 # or a sub-directory. Warnings are given for missing files.
6563 # The listing starts for the ServerRoot directory.
6564 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
6568 sub HTMLdocTree # ($Pattern [, listtype])
6569 # e.g., ("/Welcome.html", [, "ul"])
6571 my $Pattern = shift;
6572 my $ListType = shift || "dl";
6573 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6574 my $URL_root = "http://$::ENV{'SERVER_NAME
'}\:$::ENV{'SERVER_PORT
'}";
6575 my ($Filename, $Path, $Link);
6576 my %LocalLinks = {};
6578 # Read files (glob them for expansion of wildcards)
6579 my @FileList = glob("$::CGI_HOME$Pattern");
6580 foreach $Path (@FileList)
6583 $Path =~ /$::CGI_HOME/;
6585 # Check whether this file should be visible
6586 next if $::BlockPathAccess
&& $URL_path =~ m@
$::BlockPathAccess@
;
6588 my $Title = $URL_path;
6590 # Current file should not be used again
6591 ++$LinkUsed{$URL_path};
6593 unless(open(TextFile
, $Path))
6595 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
6603 while($Line =~ m@
<title
>@i)
6605 if($Line =~ m@
<title
>([^<]*)</title
>@i)
6612 $Line .= <TextFile>;
6616 # Catch First Header
6617 while(!$Caption && $Line =~ m@<h1>@i)
6619 if($Line =~ m@</h[1-9]>@i)
6623 $Caption =~ m@
<h1
>@i;
6625 $Line = $`.$Caption.$Line;
6629 $Line .= <TextFile>;
6633 # Catch and print Links
6634 while($Line =~ m@<a href\=([^>]*)>@i)
6641 $Link =~ s/[\#\?].*$//g;
6643 if($Link =~ m@
(http
://|^)@i)
6646 # Only build tree for current server
6647 next unless $Link =~ m@$::ENV{'SERVER_NAME
'}|^/@;
6648 # Remove server name and port
6649 $Link =~ s@^[^\/]*@@g;
6651 # Store the current link
6652 next if $LinkUsed{$Link} || $Link eq $URL_path;
6654 ++$LocalLinks{$Link};
6660 print "<a href=http://";
6661 print "$::ENV{'SERVER_NAME
'}\:$::ENV{'SERVER_PORT
'}$URL_path>";
6662 print "$Title</a>\n";
6663 print "<br>$Caption\n"
6664 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
6665 print "<$ListType>\n";
6666 foreach $Link (keys(%LocalLinks))
6668 &HTMLdocTree($Link, $ListType);
6670 print "</$ListType>\n";
6674 ###########################<<<<<<<<<<End Remove
6676 # Make require happy
6685 A flexible HTML 4 compliant script/module for CGI-aware
6686 embeded Perl, shell-scripts, and other scripting languages,
6687 executed at the server side.
6691 Executes embeded Perl code in HTML pages with easy
6692 access to CGI variables. Also processes embeded shell
6693 scripts and scripts in any other language with an
6694 interactive interpreter (e.g., in-line Python, Tcl,
6695 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
6696 sh, bash, csh, ksh).
6698 CGIscriptor is very flexible and hides all the specifics
6699 and idiosyncrasies of correct output and CGI coding and naming.
6700 CGIscriptor complies with the W3C HTML 4.0 recommendations.
6702 This Perl program will run on any WWW server that runs
6703 Perl scripts, just add a line like the following to your
6704 srm.conf file (Apache example):
6706 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
6708 URL's that refer to http
://www
.your
.address
/SHTML/... will
6709 now be handled by CGIscriptor
.pl
, which can
use a private
6710 directory tree
(default is the DOCUMENT_ROOT directory tree
,
6711 but it can be anywhere
).
6713 =head1 PREREQUISITES
6721 Linux, *BSD, *nix, MS WinXP
6723 =pod SCRIPT CATEGORIES