Added Capabilities to CreateUser form
[CGIscriptor.git] / CGIscriptor.pl
blobbfcd24919235d489e7f58d9dd684fb484de4d65f
1 #! /usr/bin/perl
3 # (configure the first line to contain YOUR path to perl 5.000+)
5 # CGIscriptor.pl
6 # Version 2.4
7 # 10 July 2012
9 # YOU NEED:
11 # perl 5.0 or higher (see: "http://www.perl.org/")
13 # Notes:
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
28 # instead. See below.
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.
55 ENDOFPREHELPTEXT1
58 # Configuration, copyright notice, and user manual follow the next
59 # (Changes) section.
61 ############################################################################
63 # Changes (document ALL changes with date, name and email here):
64 # 05 Apr 2013 - Renamed COOKIE_JAR to HTTP_COOKIE, added support for
65 # CGI::Cookie in case $ENV{HTTP_COOKIE} is undefined (untested)
66 # 31 Mar 2013 - Added support for Digest::SHA
67 # 13 Mar 2013 - Changed password hash
68 # 10 Jul 2012 - Version 2.4
69 # 11 Jun 2012 - Securing CGIvariable setting. Made
70 # 'if($ENV{QUERY_STRING} =~ /$name/)' into elsif in
71 # defineCGIvariable/List/Hash to give precedence to ENV{$name}
72 # This was a very old security bug. Added ProtectCGIvariable($name).
73 # 06 Jun 2012 - Added IP only session types after login.
74 # 31 May 2012 - Session ticket system added for handling login sessions.
75 # 29 May 2012 - CGIsafeFileName does not accept filenames starting with '.'
76 # 29 May 2012 - Added CGIscriptor::BrowseAllDirs to handle browsing directories
77 # correctly.
78 # 22 May 2012 - Added Access control with Session Tickets linked to
79 # IP Address and PATH_INFO.
80 # 21 May 2012 - Corrected the links generated by CGIscriptor::BrowseDirs
81 # Will link to current base URL when the HTTP server is '.' or '~'
82 # 29 Oct 2009 - Adapted David A. Wheeler's suggestion about filenames:
83 # CGIsafeFileName does not accept filenames starting with '-'
84 # (http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html)
85 # 08 Oct 2009 - Some corrections in the README.txt file, eg, new email address
86 # 28 Jan 2005 - Added a file selector to performTranslation.
87 # Changed %TranslationTable to @TranslationTable
88 # and patterns to lists.
89 # 27 Jan 2005 - Added a %TranslationTable with associated
90 # performTranslation(\$text) function to allow
91 # run changes in the web pages. Say, to translate
92 # legacy pages with <%=...%> delimiters to the new
93 # <SCRIPT TYPE=..></SCRIPT> format.
94 # 27 Jan 2005 - Small bug of extra '\n' in output removed from the
95 # Other Languages Code.
96 # 10 May 2004 - Belated upload of latest version (2.3) to CPAN
97 # 07 Oct 2003 - Corrected error '\s' -> '\\s' in rebol scripting
98 # language call
99 # 07 Oct 2003 - Corrected omitted INS tags in <DIV><INS> handling
100 # 20 May 2003 - Added a --help switch to print the manual.
101 # 06 Mar 2003 - Adapted the blurb at the end of the file.
102 # 03 Mar 2003 - Added a user definable dieHandler function to catch all
103 # "die" calls. Also "enhanced" the STDERR printout.
104 # 10 Feb 2003 - Split off the reading of the POST part of a query
105 # from Initialize_output. This was suggested by Gerd Franke
106 # to allow for the catching of the file_path using a
107 # POST based lookup. That is, he needed the POST part
108 # to change the file_path.
109 # 03 Feb 2003 - %{$name}; => %{$name} = (); in defineCGIvariableHash.
110 # 03 Feb 2003 - \1 better written as $1 in
111 # $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
112 # 29 Jan 2003 - This makes "CLASS="ssperl" CSS-compatible Gerd Franke
113 # added:
114 # $ServerScriptContentClass = "ssperl";
115 # changed in ProcessFile():
116 # unless(($CurrentContentType =~
117 # 28 Jan 2003 - Added 'INS' Tag! Gerd Franke
118 # 20 Dec 2002 - Removed useless $Directoryseparator variable.
119 # Update comments and documentation.
120 # 18 Dec 2002 - Corrected bug in Accept/Reject processing.
121 # Files didn't work.
122 # 24 Jul 2002 - Added .htaccess documentation (from Gerd Franke)
123 # Also added a note that RawFilePattern can be a
124 # complete file name.
125 # 19 Mar 2002 - Added SRC pseudo-files PREFIX and POSTFIX. These
126 # switch to prepending or to appending the content
127 # of the SRC attribute. Default is prefixing. You
128 # can add as many of these switches as you like.
129 # 13 Mar 2002 - Do not search for tag content if a tag closes with
130 # />, i.e., <DIV ... /> will be handled the XML/XHTML way.
131 # 25 Jan 2002 - Added 'curl' and 'snarf' to SRC attribute URL handling
132 # (replaces wget).
133 # 25 Jan 2002 - Found a bug in SAFEqx, now executes qx() in a scalar context
134 # (i.o. a list context). This is necessary for binary results.
135 # 24 Jan 2002 - Disambiguated -T $SRCfile to -T "$SRCfile" (and -e) and
136 # changed the order of if/elsif to allow removing these
137 # conditions in systems with broken -T functions.
138 # (I also removed a spurious ')' bracket)
139 # 17 Jan 2002 - Changed DIV tag SRC from <SOURCE> to sysread(SOURCE,...)
140 # to support binary files.
141 # 17 Jan 2002 - Removed WhiteSpace from $FileAllowedCharacters.
142 # 17 Jan 2002 - Allow "file://" prefix in SRC attribute. It is simply
143 # stipped from the path.
144 # 15 Jan 2002 - Version 2.2
145 # 15 Jan 2002 - Debugged and completed URL support (including
146 # CGIscriptor::read_url() function)
147 # 07 Jan 2002 - Added automatic (magic) URL support to the SRC attribute
148 # with the main::GET_URL function. Uses wget -O underlying.
149 # 04 Jan 2002 - Added initialization of $NewDirective in InsertForeignScript
150 # (i.e., my $NewDirective = "";) to clear old output
151 # (this was a realy anoying bug).
152 # 03 Jan 2002 - Added a <DIV CLASS='text/ssperl' ID='varname'></DIV>
153 # tags that assign the body text as-is (literally)
154 # to $varname. Allows standard HTML-tools to handle
155 # Cascading Style Sheet templates. This implements a
156 # design by Gerd Franke (franke@roo.de).
157 # 03 Jan 2002 - I finaly gave in and allowed SRC files to expand ~/.
158 # 12 Oct 2001 - Normalized spelling of "CGIsafFileName" in documentation.
159 # 09 Oct 2001 - Added $ENV{'CGI_BINARY_FILE'} to log files to
160 # detect unwanted indexing of TAR files by webcrawlers.
161 # 10 Sep 2001 - Added $YOUR_SCRIPTS directory to @INC for 'require'.
162 # 22 Aug 2001 - Added .txt (Content-type: text/plain) as a default
163 # processed file type. Was processed via BinaryMapFile.
164 # 31 May 2001 - Changed =~ inside CGIsafeEmailAddress that was buggy.
165 # 29 May 2001 - Updated $CGI_HOME to point to $ENV{DOCUMENT_ROOT} io
166 # the root of PATH_TRANSLATED. DOCUMENT_ROOT can now
167 # be manipulated to achieve a "Sub Root".
168 # NOTE: you can have $YOUR_HTML_FILES != DOCUMENT_ROOT
169 # 28 May 2001 - Changed CGIscriptor::BrowsDirs function for security
170 # and debugging (it now works).
171 # 21 May 2001 - defineCGIvariableHash will ADD values to existing
172 # hashes,instead of replacing existing hashes.
173 # 17 May 2001 - Interjected a '&' when pasting POST to GET data
174 # 24 Apr 2001 - Blocked direct requests for BinaryMapFile.
175 # 16 Aug 2000 - Added hash table extraction for CGI parameters with
176 # CGIparseValueHash (used with structured parameters).
177 # Use: CGI='%<CGI-partial-name>' (fill in your name in <>)
178 # Will collect all <CGI-partial-name><key>=value pairs in
179 # $<CGI-partial-name>{<key>} = value;
180 # 16 Aug 2000 - Adapted SAFEqx to protect @PARAMETER values.
181 # 09 Aug 2000 - Added support for non-filesystem input by way of
182 # the CGI_FILE_CONTENTS and CGI_DATA_ACCESS_CODE
183 # environment variables.
184 # 26 Jul 2000 - On the command-line, file-path '-' indicates STDIN.
185 # This allows CGIscriptor to be used in pipes.
186 # Default, $BLOCK_STDIN_HTTP_REQUEST=1 will block this
187 # in an HTTP request (i.e., in a web server).
188 # 26 Jul 2000 - Blocked 'Content-type: text/html' if the SERVER_PROTOCOL
189 # is not HTTP or another protocol. Changed the default
190 # source directory to DOCUMENT_ROOT (i.o. the incorrect
191 # SERVER_ROOT).
192 # 24 Jul 2000 - -slim Command-line argument added to remove all
193 # comments, security, etc.. Updated documentation.
194 # 05 Jul 2000 - Added IF and UNLESS attributes to make the
195 # execution of all <META> and <SCRIPT> code
196 # conditional.
197 # 05 Jul 2000 - Rewrote and isolated the code for extracting
198 # quoted items from CGI and SRC attributes.
199 # Now all attributes expect the same set of
200 # quotes: '', "", ``, (), {}, [] and the same
201 # preceded by a \, e.g., "\((aap)\)" will be
202 # extracted as "(aap)".
203 # 17 Jun 2000 - Construct @ARGV list directly in CGIexecute
204 # name-space (i.o. by evaluation) from
205 # CGI attributes to prevent interference with
206 # the processing for non perl scripts.
207 # Changed CGIparseValueList to prevent runaway
208 # loops.
209 # 16 Jun 2000 - Added a direct (interpolated) display mode
210 # (text/ssdisplay) and a user log mode
211 # (text/sslogfile).
212 # 06 Jun 2000 - Replace "print $Result" with a syswrite loop to
213 # allow large string output.
214 # 02 Jun 2000 - Corrected shrubCGIparameter($CGI_VALUE) to realy
215 # remove all control characters. Changed Interpreter
216 # initialization to shrub interpolated CGI parameters.
217 # Added 'text/ssmailto' interpreter script.
218 # 22 May 2000 - Changed some of the comments
219 # 09 May 2000 - Added list extraction for CGI parameters with
220 # CGIparseValueList (used with multiple selections).
221 # Use: CGI='@<CGI-parameter>' (fill in your name in <>)
222 # 09 May 2000 - Added a 'Not Present' condition to CGIparseValue.
223 # 27 Apr 2000 - Updated documentation to reflect changes.
224 # 27 Apr 2000 - SRC attribute "cleaned". Supported for external
225 # interpreters.
226 # 27 Apr 2000 - CGI attribute can be used in <SCRIPT> tag.
227 # 27 Apr 2000 - Gprolog, M4 support added.
228 # 26 Apr 2000 - Lisp (rep) support added.
229 # 20 Apr 2000 - Use of external interpreters now functional.
230 # 20 Apr 2000 - Removed bug from extracting Content types (RegExp)
231 # 10 Mar 2000 - Qualified unconditional removal of '#' that preclude
232 # the use of $#foo, i.e., I changed
233 # s/[^\\]\#[^\n\f\r]*([\n\f\r])/\1/g
234 # to
235 # s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/\1/g
236 # 03 Mar 2000 - Added a '$BlockPathAccess' variable to "hide"
237 # things like, e.g., CVS information in CVS subtrees
238 # 10 Feb 2000 - URLencode/URLdecode have been made case-insensitive
239 # 10 Feb 2000 - Added a BrowseDirs function (CGIscriptor package)
240 # 01 Feb 2000 - A BinaryMapFile in the ~/ directory has precedence
241 # over a "burried" BinaryMapFile.
242 # 04 Oct 1999 - Added two functions to check file names and email addresses
243 # (CGIscriptor::CGIsafeFileName and
244 # CGIscriptor::CGIsafeEmailAddress)
245 # 28 Sept 1999 - Corrected bug in sysread call for reading POST method
246 # to allow LONG posts.
247 # 28 Sept 1999 - Changed CGIparseValue to handle multipart/form-data.
248 # 29 July 1999 - Refer to BinaryMapFile from CGIscriptor directory, if
249 # this directory exists.
250 # 07 June 1999 - Limit file-pattern matching to LAST extension
251 # 04 June 1999 - Default text/html content type is printed only once.
252 # 18 May 1999 - Bug in replacement of ~/ and ./ removed.
253 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
254 # 15 May 1999 - Changed the name of the execute package to CGIexecute.
255 # Changed the processing of the Accept and Reject file.
256 # Added a full expression evaluation to Access Control.
257 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
258 # 27 Apr 1999 - Brought CGIscriptor under the GNU GPL. Made CGIscriptor
259 # Version 1.1 a module that can be called with 'require "CGIscriptor.pl"'.
260 # Requests are serviced by "Handle_Request()". CGIscriptor
261 # can still be called as a isolated perl script and a shell
262 # command.
263 # Changed the "factory default setting" so that it will run
264 # from the DOCUMENT_ROOT directory.
265 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
266 # 29 Mar 1999 - Remove second debugging STDERR switch. Moved most code
267 # to subroutines to change CGIscriptor into a module.
268 # Added mapping to process unsupported file types (e.g., binary
269 # pictures). See $BinaryMapFile.
270 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
271 # 24 Sept 1998 - Changed text of license (Rob van Son, R.J.J.H.vanSon@gmail.com)
272 # Removed a double setting of filepatterns and maximum query
273 # size. Changed email address. Removed some typos from the
274 # comments.
275 # 02 June 1998 - Bug fixed in URLdecode. Changing the foreach loop variable
276 # caused quiting CGIscriptor.(Rob van Son, R.J.J.H.vanSon@gmail.com)
277 # 02 June 1998 - $SS_PUB and $SS_SCRIPT inserted an extra /, removed.
278 # (Rob van Son, R.J.J.H.vanSon@gmail.com)
281 # Known Bugs:
283 # 23 Mar 2000
284 # It is not possible to use operators or variables to construct variable names,
285 # e.g., $bar = \@{$foo}; won't work. However, eval('$bar = \@{'.$foo.'};');
286 # will indeed work. If someone could tell me why, I would be obliged.
289 ############################################################################
291 # OBLIGATORY USER CONFIGURATION
293 # Configure the directories where all user files can be found (this
294 # is the equivalent of the server root directory of a WWW-server).
295 # These directories can be located ANYWHERE. For security reasons, it is
296 # better to locate them outside the WWW-tree of your HTTP server, unless
297 # CGIscripter handles ALL requests.
299 # For convenience, the defaults are set to the root of the WWW server.
300 # However, this might not be safe!
302 # ~/ text files
303 # $YOUR_HTML_FILES = "/usr/pub/WWW/SHTML"; # or SS_PUB as environment var
304 # (patch to use the parent directory of CGIscriptor as document root, should be removed)
305 if($ENV{'SCRIPT_FILENAME'}) # && $ENV{'SCRIPT_FILENAME'} !~ /\Q$ENV{'DOCUMENT_ROOT'}\E/)
307 $ENV{'DOCUMENT_ROOT'} = $ENV{'SCRIPT_FILENAME'};
308 $ENV{'DOCUMENT_ROOT'} =~ s@/CGIscriptor.*$@@ig;
311 # Just enter your own directory path here
312 $YOUR_HTML_FILES = $ENV{'DOCUMENT_ROOT'}; # default is the DOCUMENT_ROOT
314 # ./ script files (recommended to be different from the previous)
315 # $YOUR_SCRIPTS = "/usr/pub/WWW/scripts"; # or SS_SCRIPT as environment var
316 $YOUR_SCRIPTS = $YOUR_HTML_FILES; # This might be a SECURITY RISK
318 # End of obligatory user configuration
319 # (note: there is more non-essential user configuration below)
321 ############################################################################
323 # OPTIONAL USER CONFIGURATION (all values are used CASE INSENSITIVE)
325 # Script content-types: TYPE="Content-type" (user defined mime-type)
326 $ServerScriptContentType = "text/ssperl"; # Server Side Perl scripts
327 # CSS require a simple class
328 $ServerScriptContentClass = $ServerScriptContentType =~ m!/! ?
329 $' : "ssperl"; # Server Side Perl CSS classes
331 $ShellScriptContentType = "text/osshell"; # OS shell scripts
332 # # (Server Side perl ``-execution)
334 # Accessible file patterns, block any request that doesn't match.
335 # Matches any file with the extension .(s)htm(l), .txt, or .xmr
336 # (\. is used in regexp)
337 # Note: die unless $PATH_INFO =~ m@($FilePattern)$@is;
338 $FilePattern = ".shtml|.htm|.html|.xml|.xmr|.txt|.js|.css";
340 # The table with the content type MIME types
341 # (allows to differentiate MIME types, if needed)
342 %ContentTypeTable =
344 '.html' => 'text/html',
345 '.shtml' => 'text/html',
346 '.htm' => 'text/html',
347 '.xml' => 'text/xml',
348 '.txt' => 'text/plain',
349 '.js' => 'text/plain',
350 '.css' => 'text/plain'
354 # File pattern post-processing
355 $FilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
357 # SHAsum command needed for Authorization and Login
358 # (note, these have to be accessible in the HTML pages, ie, the CGIexecute environment)
359 my $shasum = "shasum -a 256";
360 if(qx{uname} =~ /Darwin/)
362 $shasum = "shasum-5.12 -a 256" unless `which shasum`;
364 my $SHASUMCMD = $shasum.' |cut -f 1 -d" "';
365 $ENV{"SHASUMCMD"} = $SHASUMCMD;
366 my $RANDOMHASHCMD = 'dd bs=1 count=64 if=/dev/urandom 2>/dev/null | '.$shasum.' -b |cut -f 1 -d" "';
367 $ENV{"RANDOMHASHCMD"} = $RANDOMHASHCMD;
369 # Hash a string, return hex of hash
370 sub hash_string_cmd # ($string) -> hex_hash
372 my $string = shift || "";
373 # Catch nasty \'-quotes, embed them in '..'"'"'..'
374 $string =~ s/\'/\'\"\'\"\'/isg;
375 my $hash = `printf '%s' '$string'| $ENV{"SHASUMCMD"}`;
376 chomp($hash);
377 return $hash;
380 # Note that you CANNOT replace $RANDOMHASHCMD with a call using hash_string_cmd
381 # as the output of /dev/urandom breaks string handling in Perl.
382 # Generate random hex hash
383 sub get_random_hex_cmd # () -> hex
385 # Create Random Hash Salt
386 open(URANDOM, "$RANDOMHASHCMD |") || die "URANDOM; $RANDOMHASHCMD | $!\n";
387 my $RANDOMSALT= <URANDOM>;
388 close(URANDOM);
389 chomp($RANDOMSALT);
391 return $RANDOMSALT;
395 # You can use Digest::SHA (SHA.pm), you need sha256_hex
396 # See http://search.cpan.org/~mshelor/Digest-SHA-5.84/lib/Digest/SHA.pm
397 # > sudo CPAN -i Digest
399 # The following code will check whether Digest::SHA is available and then
400 # use the appropriate function calls.
402 $shaDigestLoaded = (eval("require Digest::SHA;1;") eq "1") ? 1 : 0;
404 sub hash_string_Digest # ($string) -> hex_hash
406 my $string = shift || "";
407 my $digest = Digest::SHA::sha256_hex($string);
408 $string = $digest;
409 return $digest;
412 sub get_random_hex_Digest # () -> hex
414 my $randomstring = "";
415 # Create Random Hash Salt
416 open(URANDOM, "</dev/urandom") || die "/dev/urandom: $!\n";
417 read URANDOM, $randomstring, 64 || die "No random bytes read: $!\n";
418 close(URANDOM);
419 my $RANDOMSALT= hash_string_Digest($randomstring);
421 return $RANDOMSALT;
424 # The final functions
425 sub hash_string # ($string) -> hex_hash
427 if($shaDigestLoaded)
428 { return hash_string_Digest (@_) }
429 else
430 { return hash_string_cmd(@_);};
433 sub get_random_hex # () -> hex
435 if($shaDigestLoaded)
436 { return get_random_hex_Digest () }
437 else
438 { return get_random_hex_cmd();};
441 ######################################################################
443 # File patterns of files which are handled by session tickets.
444 %TicketRequiredPatterns = (
445 '^/Private(/|$)' => "Private/.Sessions\tPrivate/.Passwords\t/Private/Login.html\t+36000"
447 # Used to set cookies, only session cookies supported
448 my %SETCOOKIELIST = ();
449 my %CGI_Cookies = ();
450 # Parse the cookies if $ENV{'HTTP_COOKIE'} is defined, else use CGI::Cookie
451 # if it is available
452 sub Get_All_Cookies
454 $ENV{'HTTP_COOKIE'} = $ENV{'Cookie'} if defined($ENV{'Cookie'}) && !defined($ENV{'HTTP_COOKIE'});
456 if(defined($ENV{'HTTP_COOKIE'}))
458 my @CookieList = split(/[\;\s]+/, $ENV{'HTTP_COOKIE'});
459 foreach my $CookieEntry (@CookieList)
461 my ($k, $v) = split(/\=/, $CookieEntry);
462 # Add new cookie only if it does not already exist
463 $CGI_Cookies{$k} = $v unless exists($CGI_Cookies{$k}) && ($v eq "" || $v eq "-");
464 ($k, $v, $CookieEntry) = (0, 0, 0);
466 @CookieList = ();
467 $ENV{'Cookie'} = "" if defined($ENV{'Cookie'})
469 else
471 my $cookiesLoaded = (eval("require CGI::Cookie;1;") eq "1") ? 1 : 0;
472 if($cookiesLoaded)
474 %CGI_Cookies = fetch CGI::Cookie;
480 # Session Ticket Directory: Private/.Sessions
481 # Password Directory: Private/.Passwords
482 # Login page (url path): /Private/Login.html
483 # Expiration time (s): +3600
484 # +<seconds> = relative time <seconds> is absolute date-time
486 # Manage login
487 # Set up a valid ticket from a given text file
488 # Use from command line. DO NOT USE ONLINE
489 # Watch out for passwords that get stored in the history file
491 # perl CGIscriptor.pl --managelogin [options] [files]
492 # Options:
493 # salt={file or saltvalue}
494 # masterkey={file or plaintext}
495 # newmasterkey={file or plaintext}
496 # password={file or palintext}
498 # Followed by one or more file names.
499 # Options can be interspersed between filenames,
500 # e.g., password='plaintext'
501 # Note that passwords are only used once!
503 if($ARGV[0] =~ /^\-\-managelogin/i)
505 my @arguments = @ARGV;
506 shift(@arguments);
507 setup_ticket_file(@arguments);
508 # Should be run on the command line
509 exit;
514 # Raw files must contain their own Content-type (xmr <- x-multipart-replace).
515 # THIS IS A SUBSET OF THE FILES DEFINED IN $FilePattern
516 $RawFilePattern = ".xmr";
517 # (In principle, this could contain a full file specification, e.g.,
518 # ".xmr|relocated.html")
520 # Raw File pattern post-processing
521 $RawFilePattern =~ s/([@.])/\\$1/g; # Convert . and @ to \. and \@
523 # Server protocols for which "Content-type: text/html\n\n" should be printed
524 # (you should not bother with these, except for HTTP, they are mostly imaginary)
525 $ContentTypeServerProtocols = 'HTTP|MAIL|MIME';
527 # Block access to all (sub-) paths and directories that match the
528 # following (URL) path (is used as:
529 # 'die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;' )
530 $BlockPathAccess = '/(CVS|\.git)/'; # Protect CVS and .git information
532 # All (blocked) other file-types can be mapped to a single "binary-file"
533 # processor (a kind of pseudo-file path). This can either be an error
534 # message (e.g., "illegal file") or contain a script that serves binary
535 # files.
536 # Note: the real file path wil be stored in $ENV{CGI_BINARY_FILE}.
537 $BinaryMapFile = "/BinaryMapFile.xmr";
538 # Allow for the addition of a CGIscriptor directory
539 # Note that a BinaryMapFile in the root "~/" directory has precedence
540 $BinaryMapFile = "/CGIscriptor".$BinaryMapFile
541 if ! -e "$YOUR_HTML_FILES".$BinaryMapFile
542 && -e "$YOUR_HTML_FILES/CGIscriptor".$BinaryMapFile;
545 # List of all characters that are allowed in file names and paths.
546 # All requests containing illegal characters are blocked. This
547 # blocks most tricks (e.g., adding "\000", "\n", or other control
548 # characters, also blocks URI's using %FF)
549 # THIS IS A SECURITY FEATURE
550 # (this is also used to parse filenames in SRC= features, note the
551 # '-quotes, they are essential)
552 $FileAllowedChars = '\w\.\~\/\:\*\?\-'; # Covers Unix and Mac, but NO spaces
554 # Maximum size of the Query (number of characters clients can send
555 # covers both GET & POST combined)
556 $MaximumQuerySize = 2**20 - 1; # = 2**14 - 1
559 # Embeded URL get function used in SRC attributes and CGIscriptor::read_url
560 # (returns a string with the PERL code to transfer the URL contents, e.g.,
561 # "SAFEqx(\'curl \"http://www.fon.hum.uva.nl\"\')")
562 # "SAFEqx(\'wget --quiet --output-document=- \"http://www.fon.hum.uva.nl\"\')")
563 # Be sure to handle <BASE HREF='URL'> and allow BOTH
564 # direct printing GET_URL($URL [, 0]) and extracting the content of
565 # the $URL for post-processing GET_URL($URL, 1).
566 # You get the WHOLE file, including HTML header.
567 # The shell command Use $URL where the URL should go
568 # ('wget', 'snarf' or 'curl', uncomment the one you would like to use)
569 my $GET_URL_shell_command = 'wget --quiet --output-document=- $URL';
570 #my $GET_URL_shell_command = 'snarf $URL -';
571 #my $GET_URL_shell_command = 'curl $URL';
573 sub GET_URL # ($URL, $ValueNotPrint) -> content_of_url
575 my $URL = shift || return;
576 my $ValueNotPrint = shift || 0;
578 # Check URL for illegal characters
579 return "print '<h1>Illegal URL<h1>'\"\n\";" if $URL =~ /[^$FileAllowedChars\%]/;
581 # Include URL in final command
582 my $CurrentCommand = $GET_URL_shell_command;
583 $CurrentCommand =~ s/\$URL/$URL/g;
585 # Print to STDOUT or return a value
586 my $BlockPrint = "print STDOUT ";
587 $BlockPrint = "" if $ValueNotPrint;
589 my $Commands = <<"GETURLCODE";
590 # Get URL
592 my \$Page = "";
594 # Simple, using shell command
595 \$Page = SAFEqx('$CurrentCommand');
597 # Add a BASE tage to the header
598 \$Page =~ s!\\</head!\\<base href='$URL'\\>\\</head!ig unless \$Page =~ m!\\<base!;
600 # Print the URL value, or return it as a value
601 $BlockPrint\$Page;
603 GETURLCODE
604 return $Commands;
607 # As files can get rather large (and binary), you might want to use
608 # some more intelligent reading procedure, e.g.,
609 # Direct Perl
610 # # open(URLHANDLE, '/usr/bin/wget --quiet --output-document=- "$URL"|') || die "wget: \$!";
611 # #open(URLHANDLE, '/usr/bin/snarf "$URL" -|') || die "snarf: \$!";
612 # open(URLHANDLE, '/usr/bin/curl "$URL"|') || die "curl: \$!";
613 # my \$text = "";
614 # while(sysread(URLHANDLE,\$text, 1024) > 0)
616 # \$Page .= \$text;
617 # };
618 # close(URLHANDLE) || die "\$!";
619 # However, this doesn't work with the CGIexecute->evaluate() function.
620 # You get an error: 'No child processes at (eval 16) line 15, <file0> line 8.'
622 # You can forget the next two variables, they are only needed when
623 # you don't want to use a regular file system (i.e., with open)
624 # but use some kind of database/RAM image for accessing (generating)
625 # the data.
627 # Name of the environment variable that contains the file contents
628 # when reading directly from Database/RAM. When this environment variable,
629 # $ENV{$CGI_FILE_CONTENTS}, is not false, no real file will be read.
630 $CGI_FILE_CONTENTS = 'CGI_FILE_CONTENTS';
631 # Uncomment the following if you want to force the use of the data access code
632 # $ENV{$CGI_FILE_CONTENTS} = '-'; # Force use of $ENV{$CGI_DATA_ACCESS_CODE}
634 # Name of the environment variable that contains the RAM access perl
635 # code needed to read additional "files", i.e.,
636 # $ENV{$CGI_FILE_CONTENTS} = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
637 # When $ENV{$CGI_FILE_CONTENTS} eq '-', this code is executed to generate the data.
638 $CGI_DATA_ACCESS_CODE = 'CGI_DATA_ACCESS_CODE';
640 # You can, of course, fill this yourself, e.g.,
641 # $ENV{$CGI_DATA_ACCESS_CODE} =
642 # 'open(INPUT, "<$_[0]"); while(<INPUT>){print;};close(INPUT);'
645 # DEBUGGING
647 # Suppress error messages, this can be changed for debugging or error-logging
648 #open(STDERR, "/dev/null"); # (comment out for use in debugging)
650 # SPECIAL: Remove Comments, security, etc. if the command line is
651 # '>CGIscriptor.pl -slim >slimCGIscriptor.pl'
652 $TrimDownCGIscriptor = 1 if $ARGV[0] =~ /^\-slim/i;
654 # If CGIscriptor is used from the command line, the command line
655 # arguments are interpreted as the file (1st) and the Query String (rest).
656 # Get the arguments
657 $ENV{'PATH_INFO'} = shift(@ARGV) unless exists($ENV{'PATH_INFO'}) || grep(/\-\-help/i, @ARGV);
658 $ENV{'QUERY_STRING'} = join("&", @ARGV) unless exists($ENV{'QUERY_STRING'});
661 # Handle bail-outs in a user definable way.
662 # Catch Die and replace it with your own function.
663 # Ends with a call to "die $_[0];"
665 sub dieHandler # ($ErrorCode, "Message", @_) -> DEAD
667 my $ErrorCode = shift;
668 my $ErrorMessage = shift;
670 # Place your own reporting functions here
672 # Now, kill everything (default)
673 print STDERR "$ErrorCode: $ErrorMessage\n";
674 die $ErrorMessage;
678 # End of optional user configuration
679 # (note: there is more non-essential user configuration below)
681 if(grep(/\-\-help/i, @ARGV))
683 print << 'ENDOFPREHELPTEXT2';
685 ###############################################################################
687 # Author and Copyright (c):
688 # Rob van Son, © 1995,1996,1997,1998,1999,2000,2001,2002-2012
689 # NKI-AVL Amsterdam
690 # r.v.son@nki.nl
691 # Institute of Phonetic Sciences & IFOTT/ACLS
692 # University of Amsterdam
693 # Email: R.J.J.H.vanSon@gmail.com
694 # Email: R.J.J.H.vanSon@gmail.com
695 # WWW : http://www.fon.hum.uva.nl/rob/
697 # License for use and disclaimers
699 # CGIscriptor merges plain ASCII HTML files transparantly
700 # with CGI variables, in-line PERL code, shell commands,
701 # and executable scripts in other scripting languages.
703 # This program is free software; you can redistribute it and/or
704 # modify it under the terms of the GNU General Public License
705 # as published by the Free Software Foundation; either version 2
706 # of the License, or (at your option) any later version.
708 # This program is distributed in the hope that it will be useful,
709 # but WITHOUT ANY WARRANTY; without even the implied warranty of
710 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
711 # GNU General Public License for more details.
713 # You should have received a copy of the GNU General Public License
714 # along with this program; if not, write to the Free Software
715 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
718 # Contributors:
719 # Rob van Son (R.J.J.H.vanSon@gmail.com)
720 # Gerd Franke franke@roo.de (designed the <DIV> behaviour)
722 #######################################################
723 ENDOFPREHELPTEXT2
725 #######################################################>>>>>>>>>>Start Remove
727 # You can skip the following code, it is an auto-splice
728 # procedure.
730 # Construct a slimmed down version of CGIscriptor
731 # (i.e., CGIscriptor.pl -slim > slimCGIscriptor.pl)
733 if($TrimDownCGIscriptor)
735 open(CGISCRIPTOR, "<CGIscriptor.pl")
736 || dieHandler(1, "<CGIscriptor.pl not slimmed down: $!\n");
737 my $SKIPtext = 0;
738 my $SKIPComments = 0;
740 while(<CGISCRIPTOR>)
742 my $SKIPline = 0;
744 ++$LineCount;
746 # Start of SKIP text
747 $SKIPtext = 1 if /[\>]{10}Start Remove/;
748 $SKIPComments = 1 if $SKIPtext == 1;
750 # Skip this line?
751 $SKIPline = 1 if $SKIPtext || ($SKIPComments && /^\s*\#/);
753 ++$PrintCount unless $SKIPline;
755 print STDOUT $_ unless $SKIPline;
757 # End of SKIP text ?
758 $SKIPtext = 0 if /[\<]{10}End Remove/;
760 # Ready!
761 print STDERR "\# Printed $PrintCount out of $LineCount lines\n";
762 exit;
765 #######################################################
767 if(grep(/\-\-help/i, @ARGV))
769 print << 'ENDOFHELPTEXT';
771 # HYPE
773 # CGIscriptor merges plain ASCII HTML files transparantly and safely
774 # with CGI variables, in-line PERL code, shell commands, and executable
775 # scripts in many languages (on-line and real-time). It combines the
776 # "ease of use" of HTML files with the versatillity of specialized
777 # scripts and PERL programs. It hides all the specifics and
778 # idiosyncrasies of correct output and CGI coding and naming. Scripts
779 # do not have to be aware of HTML, HTTP, or CGI conventions just as HTML
780 # files can be ignorant of scripts and the associated values. CGIscriptor
781 # complies with the W3C HTML 4.0 recommendations.
782 # In addition to its use as a WWW embeded CGI processor, it can
783 # be used as a command-line document preprocessor (text-filter).
785 # THIS IS HOW IT WORKS
787 # The aim of CGIscriptor is to execute "plain" scripts inside a text file
788 # using any required CGIparameters and environment variables. It
789 # is optimized to transparantly process HTML files inside a WWW server.
790 # The native language is Perl, but many other scripting languages
791 # can be used.
793 # CGIscriptor reads text files from the requested input file (i.e., from
794 # $YOUR_HTML_FILES$PATH_INFO) and writes them to <STDOUT> (i.e., the
795 # client requesting the service) preceded by the obligatory
796 # "Content-type: text/html\n\n" or "Content-type: text/plain\n\n" string
797 # (except for "raw" files which supply their own Content-type message
798 # and only if the SERVER_PROTOCOL supports HTTP, MAIL, or MIME).
800 # When CGIscriptor encounters an embedded script, indicated by an HTML4 tag
802 # <SCRIPT TYPE="text/ssperl" [CGI="$VAR='default value'"] [SRC="ScriptSource"]>
803 # PERL script
804 # </SCRIPT>
806 # or
808 # <SCRIPT TYPE="text/osshell" [CGI="$name='default value'"] [SRC="ScriptSource"]>
809 # OS Shell script
810 # </SCRIPT>
812 # construct (anything between []-brackets is optional, other MIME-types
813 # and scripting languages are supported), the embedded script is removed
814 # and both the contents of the source file (i.e., "do 'ScriptSource'")
815 # AND the script are evaluated as a PERL program (i.e., by eval()),
816 # shell script (i.e., by a "safe" version of `Command`, qx) or an external
817 # interpreter. The output of the eval() function takes the place of the
818 # original <SCRIPT></SCRIPT> construct in the output string. Any CGI
819 # parameters declared by the CGI attribute are available as simple perl
820 # variables, and can subsequently be made available as variables to other
821 # scripting languages (e.g., bash, python, or lisp).
823 # Example: printing "Hello World"
824 # <HTML><HEAD><TITLE>Hello World</TITLE>
825 # <BODY>
826 # <H1><SCRIPT TYPE="text/ssperl">"Hello World"</SCRIPT></H1>
827 # </BODY></HTML>
829 # Save this in a file, hello.html, in the directory you indicated with
830 # $YOUR_HTML_FILES and access http://your_server/SHTML/hello.html
831 # (or to whatever name you use as an alias for CGIscriptor.pl).
832 # This is realy ALL you need to do to get going.
834 # You can use any values that are delivered in CGI-compliant form (i.e.,
835 # the "?name=value" type URL additions) transparently as "$name" variables
836 # in your scripts IFF you have declared them in the CGI attribute of
837 # a META or SCRIPT tag before e.g.:
838 # <META CONTENT="text/ssperl; CGI='$name = `default value`'
839 # [SRC='ScriptSource']">
840 # or
841 # <SCRIPT TYPE="text/ssperl" CGI="$name = 'default value'"
842 # [SRC='ScriptSource']>
843 # After such a 'CGI' attribute, you can use $name as an ordinary PERL variable
844 # (the ScriptSource file is immediately evaluated with "do 'ScriptSource'").
845 # The CGIscriptor script allows you to write ordinary HTML files which will
846 # include dynamic CGI aware (run time) features, such as on-line answers
847 # to specific CGI requests, queries, or the results of calculations.
849 # For example, if you wanted to answer questions of clients, you could write
850 # a Perl program called "Answer.pl" with a function "AnswerQuestion()"
851 # that prints out the answer to requests given as arguments. You then write
852 # an HTML page "Respond.html" containing the following fragment:
854 # <center>
855 # The Answer to your question
856 # <META CONTENT="text/ssperl; CGI='$Question'">
857 # <h3><SCRIPT TYPE="text/ssperl">$Question</SCRIPT></h3>
858 # is
859 # <h3><SCRIPT TYPE="text/ssperl" SRC="./PATH/Answer.pl">
860 # AnswerQuestion($Question);
861 # </SCRIPT></h3>
862 # </center>
863 # <FORM ACTION=Respond.html METHOD=GET>
864 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
865 # <INPUT TYPE=SUBMIT VALUE="Ask">
866 # </FORM>
868 # The output could look like the following (in HTML-speak):
870 # <CENTER>
871 # The Answer to your question
872 # <h3>What is the capital of the Netherlands?</h3>
873 # is
874 # <h3>Amsterdam</h3>
875 # </CENTER>
876 # <FORM ACTION=Respond.html METHOD=GET>
877 # Next question: <INPUT NAME="Question" TYPE=TEXT SIZE=40><br>
878 # <INPUT TYPE=SUBMIT VALUE="Ask">
880 # Note that the function "Answer.pl" does know nothing about CGI or HTML,
881 # it just prints out answers to arguments. Likewise, the text has no
882 # provisions for scripts or CGI like constructs. Also, it is completely
883 # trivial to extend this "program" to use the "Answer" later in the page
884 # to call up other information or pictures/sounds. The final text never
885 # shows any cue as to what the original "source" looked like, i.e.,
886 # where you store your scripts and how they are called.
888 # There are some extra's. The argument of the files called in a SRC= tag
889 # can access the CGI variables declared in the preceding META tag from
890 # the @ARGV array. Executable files are called as:
891 # `file '$ARGV[0]' ... ` (e.g., `Answer.pl \'$Question\'`;)
892 # The files called from SRC can even be (CGIscriptor) html files which are
893 # processed in-line. Furthermore, the SRC= tag can contain a perl block
894 # that is evaluated. That is,
895 # <META CONTENT="text/ssperl; CGI='$Question' SRC='{$Question}'">
896 # will result in the evaluation of "print do {$Question};" and the VALUE
897 # of $Question will be printed. Note that these "SRC-blocks" can be
898 # preceded and followed by other file names, but only a single block is
899 # allowed in a SRC= tag.
901 # One of the major hassles of dynamic WWW pages is the fact that several
902 # mutually incompatible browsers and platforms must be supported. For example,
903 # the way sound is played automatically is different for Netscape and
904 # Internet Explorer, and for each browser it is different again on
905 # Unix, MacOS, and Windows. Realy dangerous is processing user-supplied
906 # (form-) values to construct email addresses, file names, or database
907 # queries. All Apache WWW-server exploits reported in the media are
908 # based on faulty CGI-scripts that didn't check their user-data properly.
910 # There is no panacee for these problems, but a lot of work and problems
911 # can be saved by allowing easy and transparent control over which
912 # <SCRIPT></SCRIPT> blocks are executed on what CGI-data. CGIscriptor
913 # supplies such a method in the form of a pair of attributes:
914 # IF='...condition..' and UNLESS='...condition...'. When added to a
915 # script tag, the whole block (including the SRC attribute) will be
916 # ignored if the condition is false (IF) or true (UNLESS).
917 # For example, the following block will NOT be evaluated if the value
918 # of the CGI variable FILENAME is NOT a valid filename:
920 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
921 # IF='CGIscriptor::CGIsafeFileName($FILENAME)'>
922 # .....
923 # </SCRIPT>
925 # (the function CGIsafeFileName(String) returns an empty string ("")
926 # if the String argument is not a valid filename).
927 # The UNLESS attribute is the mirror image of IF.
929 # A user manual follows the HTML 4 and security paragraphs below.
931 ##########################################################################
933 # HTML 4 compliance
935 # In general, CGIscriptor.pl complies with the HTML 4 recommendations of
936 # the W3C. This means that any software to manage Web sites will be able
937 # to handle CGIscriptor files, as will web agents.
939 # All script code should be placed between <SCRIPT></SCRIPT> tags, the
940 # script type is indicated with TYPE="mime-type", the LANGUAGE
941 # feature is ignored, and a SRC feature is implemented. All CGI specific
942 # features are delegated to the CGI attribute.
944 # However, the behavior deviates from the W3C recommendations at some
945 # points. Most notably:
946 # 0- The scripts are executed at the server side, invissible to the
947 # client (i.e., the browser)
948 # 1- The mime-types are personal and idiosyncratic, but can be adapted.
949 # 2- Code in the body of a <SCRIPT></SCRIPT> tag-pair is still evaluated
950 # when a SRC feature is present.
951 # 3- The SRC attribute reads a list of files.
952 # 4- The files in a SRC attribute are processed according to file type.
953 # 5- The SRC attribute evaluates inline Perl code.
954 # 6- Processed META, DIV, INS tags are removed from the output
955 # document.
956 # 7- All attributes of the processed META tags, except CONTENT, are ignored
957 # (i.e., deleted from the output).
958 # 8- META tags can be placed ANYWHERE in the document.
959 # 9- Through the SRC feature, META tags can have visible output in the
960 # document.
961 # 10- The CGI attribute that declares CGI parameters, can be used
962 # inside the <SCRIPT> tag.
963 # 11- Use of an extended quote set, i.e., '', "", ``, (), {}, []
964 # and their \-slashed combinations: \'\', \"\", \`\`, \(\),
965 # \{\}, \[\].
966 # 12- IF and UNLESS attributes to <SCRIPT>, <META>, <DIV>, <INS> tags.
967 # 13- <DIV> tags cannot be nested, DIV tags are not
968 # rendered with new-lines.
969 # 14- The XML style <TAG .... /> is recognized and handled correctly.
970 # (i.e., no content is processed)
972 # The reasons for these choices are:
973 # You can still write completely HTML4 compliant documents. CGIscriptor
974 # will not force you to write "deviant" code. However, it allows you to
975 # do so (which is, in fact, just as bad). The prime design principle
976 # was to allow users to include plain Perl code. The code itself should
977 # be "enhancement free". Therefore, extra features were needed to
978 # supply easy access to CGI and Web site components. For security
979 # reasons these have to be declared explicitly. The SRC feature
980 # transparently manages access to external files, especially the safe
981 # use of executable files.
982 # The CGI attribute handles the declarations of external (CGI) variables
983 # in the SCRIPT and META tag's.
984 # EVERYTHING THE CGI ATTRIBUTE AND THE META TAG DO CAN BE DONE INSIDE
985 # A <SCRIPT></SCRIPT> TAG CONSTRUCT.
987 # The reason for the IF, UNLESS, and SRC attributes (and their Perl code
988 # evaluation) were build into the META and SCRIPT tags is part laziness,
989 # part security. The SRC blocks allows more compact documents and easier
990 # debugging. The values of the CGI variables can be immediately screened
991 # for security by IF or UNLESS conditions, and even SRC attributes (e.g.,
992 # email addresses and file names), and a few commands can be called
993 # without having to add another Perl TAG pair. This is especially important
994 # for documents that require the use of other (more restricted) "scripting"
995 # languages and facilities that lag transparent control structures.
997 ##########################################################################
999 # SECURITY
1001 # Your WWW site is a few keystrokes away from a few hundred million internet
1002 # users. A fair percentage of these users knows more about your computer
1003 # than you do. And some of these just might have bad intentions.
1005 # To ensure uncompromized operation of your server and platform, several
1006 # features are incorporated in CGIscriptor.pl to enhance security.
1007 # First of all, you should check the source of this program. No security
1008 # measures will help you when you download programs from anonymous sources.
1009 # If you want to use THIS file, please make sure that it is uncompromized.
1010 # The best way to do this is to contact the source and try to determine
1011 # whether s/he is reliable (and accountable).
1013 # BE AWARE THAT ANY PROGRAMMER CAN CHANGE THIS PROGRAM IN SUCH A WAY THAT
1014 # IT WILL SET THE DOORS TO YOUR SYSTEM WIDE OPEN
1016 # I would like to ask any user who finds bugs that could compromise
1017 # security to report them to me (and any other bug too,
1018 # Email: R.J.J.H.vanSon@gmail.com or ifa@hum.uva.nl).
1020 # Security features
1022 # 1 Invisibility
1023 # The inner workings of the HTML source files are completely hidden
1024 # from the client. Only the HTTP header and the ever changing content
1025 # of the output distinguish it from the output of a plain, fixed HTML
1026 # file. Names, structures, and arguments of the "embedded" scripts
1027 # are invisible to the client. Error output is suppressed except
1028 # during debugging (user configurable).
1030 # 2 Separate directory trees
1031 # Directories containing Inline text and script files can reside on
1032 # separate trees, distinct from those of the HTTP server. This means
1033 # that NEITHER the text files, NOR the script files can be read by
1034 # clients other than through CGIscriptor.pl, UNLESS they are
1035 # EXPLICITELY made available.
1037 # 3 Requests are NEVER "evaluated"
1038 # All client supplied values are used as literal values (''-quoted).
1039 # Client supplied ''-quotes are ALWAYS removed. Therefore, as long as the
1040 # embedded scripts do NOT themselves evaluate these values, clients CANNOT
1041 # supply executable commands. Be sure to AVOID scripts like:
1043 # <META CONTENT="text/ssperl; CGI='$UserValue'">
1044 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 $UserValue`;</SCRIPT>
1046 # These are a recipe for disaster. However, the following quoted
1047 # form should be save (but is still not adviced):
1049 # <SCRIPT TYPE="text/ssperl">$dir = `ls -1 \'$UserValue\'`;</SCRIPT>
1051 # A special function, SAFEqx(), will automatically do exactly this,
1052 # e.g., SAFEqx('ls -1 $UserValue') will execute `ls -1 \'$UserValue\'`
1053 # with $UserValue interpolated. I recommend to use SAFEqx() instead
1054 # of backticks whenever you can. The OS shell scripts inside
1056 # <SCRIPT TYPE="text/osshell">ls -1 $UserValue</SCRIPT>
1058 # are handeld by SAFEqx and automatically ''-quoted.
1060 # 4 Logging of requests
1061 # All requests can be logged separate from the Host server. The level of
1062 # detail is user configurable: Including or excluding the actual queries.
1063 # This allows for the inspection of (im-) proper use.
1065 # 5 Access control: Clients
1066 # The Remote addresses can be checked against a list of authorized
1067 # (i.e., accepted) or non-authorized (i.e., rejected) clients. Both
1068 # REMOTE_HOST and REMOTE_ADDR are tested so clients without a proper
1069 # HOST name can be (in-) excluded by their IP-address. Client patterns
1070 # containing all numbers and dots are considered IP-addresses, all others
1071 # domain names. No wild-cards or regexp's are allowed, only partial
1072 # addresses.
1073 # Matching of names is done from the back to the front (domain first,
1074 # i.e., $REMOTE_HOST =~ /\Q$pattern\E$/is), so including ".edu" will
1075 # accept or reject all clients from the domain EDU. Matching of
1076 # IP-addresses is done from the front to the back (domain first, i.e.,
1077 # $REMOTE_ADDR =~ /^\Q$pattern\E/is), so including "128." will (in-)
1078 # exclude all clients whose IP-address starts with 128.
1079 # There are two special symbols: "-" matches HOSTs with no name and "*"
1080 # matches ALL HOSTS/clients.
1081 # For those needing more expressional power, lines starting with
1082 # "-e" are evaluated by the perl eval() function. E.g.,
1083 # '-e $REMOTE_HOST =~ /\.edu$/is;' will accept/reject clients from the
1084 # domain '.edu'.
1086 # 6 Access control: Files
1087 # In principle, CGIscriptor could read ANY file in the directory
1088 # tree as discussed in 1. However, for security reasons this is
1089 # restricted to text files. It can be made more restricted by entering
1090 # a global file pattern (e.g., ".html"). This is done by default.
1091 # For each client requesting access, the file pattern(s) can be made
1092 # more restrictive than the global pattern by entering client specific
1093 # file patterns in the Access Control files (see 5).
1094 # For example: if the ACCEPT file contained the lines
1095 # * DEMO
1096 # .hum.uva.nl LET
1097 # 145.18.230.
1098 # Then all clients could request paths containing "DEMO" or "demo", e.g.
1099 # "/my/demo/file.html" ($PATH_INFO =~ /\Q$pattern\E/), Clients from
1100 # *.hum.uva.nl could also request paths containing "LET or "let", e.g.
1101 # "/my/let/file.html", and clients from the local cluster
1102 # 145.18.230.[0-9]+ could access ALL files.
1103 # Again, for those needing more expressional power, lines starting with
1104 # "-e" are evaluated. For instance:
1105 # '-e $REMOTE_HOST =~ /\.edu$/is && $PATH_INFO =~ m@/DEMO/@is;'
1106 # will accept/reject requests for files from the directory "/demo/" from
1107 # clients from the domain '.edu'.
1109 # 7 Access control: Server side session tickets
1110 # Specific paths can be controlled by Session Tickets which must be
1111 # present as a SESSIONTICKET=<value> CGI variable in the request. These paths
1112 # are defined in %TicketRequiredPatterns as pairs of:
1113 # ('regexp' => 'SessionPath\tPasswordPath\tLogin.html\tExpiration').
1114 # Session Tickets are stored in a separate directory (SessionPath, e.g.,
1115 # "Private/.Session") as files with the exact same name of the SESSIONTICKET
1116 # CGI. The following is an example:
1117 # Type: SESSION
1118 # IPaddress: 127.0.0.1
1119 # AllowedPaths: ^/Private/Name/
1120 # Expires: 3600
1121 # Username: test
1122 # ...
1123 # Other content can follow.
1125 # It is adviced that Session Tickets should be deleted
1126 # after some (idle) time. The IP address should be the IP number at login, and
1127 # the SESSIONTICKET will be rejected if it is presented from another IP address.
1128 # AllowedPaths and DeniedPaths are perl regexps. Be careful how they match. Make sure to delimit
1129 # the names to prevent access to overlapping names, eg, "^/Private/Rob" will also
1130 # match "^/Private/Robert", however, "^/Private/Rob/" will not. Expires is the
1131 # time the ticket will remain valid after creation (file ctime). Time can be given
1132 # in s[econds] (default), m[inutes], h[hours], or d[ays], eg, "24h" means 24 hours.
1133 # None of these need be present, but the Ticket must have a non-zero size.
1135 # Next to Session Tickets, there are two other type of ticket files:
1136 # - LOGIN tickets store information about a current login request
1137 # - PASSWORD ticket store account information to authorize login requests
1139 # 8 Query length limiting
1140 # The length of the Query string can be limited. If CONTENT_LENGTH is larger
1141 # than this limit, the request is rejected. The combined length of the
1142 # Query string and the POST input is checked before any processing is done.
1143 # This will prevent clients from overloading the scripts.
1144 # The actual, combined, Query Size is accessible as a variable through
1145 # $CGI_Content_Length.
1147 # 9 Illegal filenames, paths, and protected directories
1148 # One of the primary security concerns in handling CGI-scripts is the
1149 # use of "funny" characters in the requests that con scripts in executing
1150 # malicious commands. Examples are inserting ';', null bytes, or <newline>
1151 # characters in URL's and filenames, followed by executable commands. A
1152 # special variable $FileAllowedChars stores a string of all allowed
1153 # characters. Any request that translates to a filename with a character
1154 # OUTSIDE this set will be rejected.
1155 # In general, all (readable files) in the DocumentRoot tree are accessible.
1156 # This might not be what you want. For instance, your DocumentRoot directory
1157 # might be the working directory of a CVS project and contain sensitive
1158 # information (e.g., the password to get to the repository). You can block
1159 # access to these subdirectories by adding the corresponding patterns to
1160 # the $BlockPathAccess variable. For instance, $BlockPathAccess = '/CVS/'
1161 # will block any request that contains '/CVS/' or:
1162 # die if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@;
1164 #10 The execution of code blocks can be controlled in a transparent way
1165 # by adding IF or UNLESS conditions in the tags themselves. That is,
1166 # a simple check of the validity of filenames or email addresses can
1167 # be done before any code is executed.
1169 ###############################################################################
1171 # USER MANUAL (sort of)
1173 # CGIscriptor removes embedded scripts, indicated by an HTML 4 type
1174 # <SCRIPT TYPE='text/ssperl'> </SCRIPT> or <SCRIPT TYPE='text/osshell'>
1175 # </SCRIPT> constructs. CGIscriptor also recognizes XML-type
1176 # <SCRIPT TYPE='text/ssperl'/> constructs. These are usefull when
1177 # the necessary code is already available in the TAG itself (e.g.,
1178 # using external files). The contents of the directive are executed by
1179 # the PERL eval() and `` functions (in a separate name space). The
1180 # result of the eval() function replaces the <SCRIPT> </SCRIPT> construct
1181 # in the output file. You can use the values that are delivered in
1182 # CGI-compliant form (i.e., the "?name=value&.." type URL additions)
1183 # transparently as "$name" variables in your directives after they are
1184 # defined in a <META> or <SCRIPT> tag.
1185 # If you define the variable "$CGIscriptorResults" in a CGI attribute, all
1186 # subsequent <SCRIPT> and <META> results (including the defining
1187 # tag) will also be pushed onto a stack: @CGIscriptorResults. This list
1188 # behaves like any other, ordinary list and can be manipulated.
1190 # Both GET and POST requests are accepted. These two methods are treated
1191 # equal. Variables, i.e., those values that are determined when a file is
1192 # processed, are indicated in the CGI attribute by $<name> or $<name>=<default>
1193 # in which <name> is the name of the variable and <default> is the value
1194 # used when there is NO current CGI value for <name> (you can use
1195 # white-spaces in $<name>=<default> but really DO make sure that the
1196 # default value is followed by white space or is quoted). Names can contain
1197 # any alphanumeric characters and _ (i.e., names match /[\w]+/).
1198 # If the Content-type: is 'multipart/*', the input is treated as a
1199 # MIME multipart message and automatically delimited. CGI variables get
1200 # the "raw" (i.e., undecoded) body of the corresponding message part.
1202 # Variables can be CGI variables, i.e., those from the QUERY_STRING,
1203 # environment variables, e.g., REMOTE_USER, REMOTE_HOST, or REMOTE_ADDR,
1204 # or predefined values, e.g., CGI_Decoded_QS (The complete, decoded,
1205 # query string), CGI_Content_Length (the length of the decoded query
1206 # string), CGI_Year, CGI_Month, CGI_Time, and CGI_Hour (the current
1207 # date and time).
1209 # All these are available when defined in a CGI attribute. All environment
1210 # variables are accessible as $ENV{'name'}. So, to access the REMOTE_HOST
1211 # and the REMOTE_USER, use, e.g.:
1213 # <SCRIPT TYPE='text/ssperl'>
1214 # ($ENV{'REMOTE_HOST'}||"-")." $ENV{'REMOTE_USER'}"
1215 # </SCRIPT>
1217 # (This will print a "-" if REMOTE_HOST is not known)
1218 # Another way to do this is:
1220 # <META CONTENT="text/ssperl; CGI='$REMOTE_HOST = - $REMOTE_USER'">
1221 # <SCRIPT TYPE='text/ssperl'>"$REMOTE_HOST $REMOTE_USER"</SCRIPT>
1222 # or
1223 # <META CONTENT='text/ssperl; CGI="$REMOTE_HOST = - $REMOTE_USER"
1224 # SRC={"$REMOTE_HOST $REMOTE_USER\n"}'>
1226 # This is possible because ALL environment variables are available as
1227 # CGI variables. The environment variables take precedence over CGI
1228 # names in case of a "name clash". For instance:
1229 # <META CONTENT="text/ssperl; CGI='$HOME' SRC={$HOME}">
1230 # Will print the current HOME directory (environment) irrespective whether
1231 # there is a CGI variable from the query
1232 # (e.g., Where do you live? <INPUT TYPE="TEXT" NAME="HOME">)
1233 # THIS IS A SECURITY FEATURE. It prevents clients from changing
1234 # the values of defined environment variables (e.g., by supplying
1235 # a bogus $REMOTE_ADDR). Although $ENV{} is not changed by the META tags,
1236 # it would make the use of declared variables insecure. You can still
1237 # access CGI variables after a name clash with
1238 # CGIscriptor::CGIparseValue(<name>).
1240 # Some CGI variables are present several times in the query string
1241 # (e.g., from multiple selections). These should be defined as
1242 # @VARIABLENAME=default in the CGI attribute. The list @VARIABLENAME
1243 # will contain ALL VARIABLENAME values from the query, or a single
1244 # default value. If there is an ENVIRONMENT variable of the
1245 # same name, it will be used instead of the default AND the query
1246 # values. The corresponding function is
1247 # CGIscriptor::CGIparseValueList(<name>)
1249 # CGI variables collected in a @VARIABLENAME list are unordered.
1250 # When more structured variables are needed, a hash table can be used.
1251 # A variable defined as %VARIABLE=default will collect all
1252 # CGI-parameters whose name start with 'VARIABLE' in a hash table with
1253 # the remainder of the name as a key. For instance, %PERSON will
1254 # collect PERSONname='John Doe', PERSONbirthdate='01 Jan 00', and
1255 # PERSONspouse='Alice' into a hash table %PERSON such that $PERSON{'spouse'}
1256 # equals 'Alice'. Any default value or environment value will be stored
1257 # under the "" key. If there is an ENVIRONMENT variable of the same name,
1258 # it will be used instead of the default AND the query values. The
1259 # corresponding function is CGIscriptor::CGIparseValueHash(<name>)
1261 # This method of first declaring your environment and CGI variables
1262 # before being able to use them in the scripts might seem somewhat
1263 # clumsy, but it protects you from inadvertedly printing out the values of
1264 # system environment variables when their names coincide with those used
1265 # in the CGI forms. It also prevents "clients" from supplying CGI
1266 # parameter values for your private variables.
1267 # THIS IS A SECURITY FEATURE!
1270 # NON-HTML CONTENT TYPES
1272 # Normally, CGIscriptor prints the standard "Content-type: text/html\n\n"
1273 # message before anything is printed. This has been extended to include
1274 # plain text (.txt) files, for which the Content-type (MIME type)
1275 # 'text/plain' is printed. In all other respects, text files are treated
1276 # as HTML files (this can be switched off by removing '.txt' from the
1277 # $FilePattern variable) . When the content type should be something else,
1278 # e.g., with multipart files, use the $RawFilePattern (.xmr, see also next
1279 # item). CGIscriptor will not print a Content-type message for this file
1280 # type (which must supply its OWN Content-type message). Raw files must
1281 # still conform to the <SCRIPT></SCRIPT> and <META> tag specifications.
1284 # NON-HTML FILES
1286 # CGIscriptor is intended to process HTML and text files only. You can
1287 # create documents of any mime-type on-the-fly using "raw" text files,
1288 # e.g., with the .xmr extension. However, CGIscriptor will not process
1289 # binary files of any type, e.g., pictures or sounds. Given the sheer
1290 # number of formats, I do not have any intention to do so. However,
1291 # an escape route has been provided. You can construct a genuine raw
1292 # (.xmr) text file that contains the perl code to service any file type
1293 # you want. If the global $BinaryMapFile variable contains the path to
1294 # this file (e.g., /BinaryMapFile.xmr), this file will be called
1295 # whenever an unsupported (non-HTML) file type is requested. The path
1296 # to the requested binary file is stored in $ENV('CGI_BINARY_FILE')
1297 # and can be used like any other CGI-variable. Servicing binary files
1298 # then becomes supplying the correct Content-type (e.g., print
1299 # "Content-type: image/jpeg\n\n";) and reading the file and writing it
1300 # to STDOUT (e.g., using sysread() and syswrite()).
1303 # THE META TAG
1305 # All attributes of a META tag are ignored, except the
1306 # CONTENT='text/ssperl; CGI=" ... " [SRC=" ... "]' attribute. The string
1307 # inside the quotes following the CONTENT= indication (white-space is
1308 # ignored, "" '' `` (){}[]-quote pairs are allowed, plus their \ versions)
1309 # MUST start with any of the CGIscriptor mime-types (e.g.: text/ssperl or
1310 # text/osshell) and a comma or semicolon.
1311 # The quoted string following CGI= contains a white-space separated list
1312 # of declarations of the CGI (and Environment) values and default values
1313 # used when no CGI values are supplied by the query string.
1315 # If the default value is a longer string containing special characters,
1316 # possibly spanning several lines, the string must be enclosed in quotes.
1317 # You may use any pair of quotes or brackets from the list '', "", ``, (),
1318 # [], or {} to distinguish default values (or preceded by \, e.g., \(...\)
1319 # is different from (...)). The outermost pair will always be used and any
1320 # other quotes inside the string are considered to be part of the string
1321 # value, e.g.,
1323 # $Value = {['this'
1324 # "and" (this)]}
1325 # will result in $Value getting the default value: ['this'
1326 # "and" (this)]
1327 # (NOTE that the newline is part of the default value!).
1329 # Internally, for defining and initializing CGI (ENV) values, the META
1330 # and SCRIPT tags use the functions "defineCGIvariable($name, $default)"
1331 # (scalars) and "defineCGIvariableList($name, $default)" (lists).
1332 # These functions can be used inside scripts as
1333 # "CGIscriptor::defineCGIvariable($name, $default)" and
1334 # "CGIscriptor::defineCGIvariableList($name, $default)".
1335 # "CGIscriptor::defineCGIvariableHash($name, $default)".
1337 # The CGI attribute will be processed exactly identical when used inside
1338 # the <SCRIPT> tag. However, this use is not according to the
1339 # HTML 4.0 specifications of the W3C.
1342 # THE DIV/INS TAGS
1344 # There is a problem when constructing html files containing
1345 # server-side perl scripts with standard HTML tools. These
1346 # tools will refuse to process any text between <SCRIPT></SCRIPT>
1347 # tags. This is quite annoying when you want to use large
1348 # HTML templates where you will fill in values.
1350 # For this purpose, CGIscriptor will read the neutral
1351 # <DIV CLASS="ssperl" ID="varname"></DIV> or
1352 # <INS CLASS="ssperl" ID="varname"></INS>
1353 # tag (in Cascading Style Sheet manner) Note that
1354 # "varname" has NO '$' before it, it is a bare name.
1355 # Any text between these <DIV ...></DIV> or
1356 # <INS ...></INS>tags will be assigned to '$varname'
1357 # as is (e.g., as a literal).
1358 # No processing or interpolation will be performed.
1359 # There is also NO nesting possible. Do NOT nest a
1360 # </DIV> inside a <DIV></DIV>! Moreover, neither INS nor
1361 # DIV tags do ensure a block structure in the final
1362 # rendering (i.e., no empty lines).
1364 # Note that <DIV CLASS="ssperl" ID="varname"/>
1365 # is handled the XML way. No content is processed,
1366 # but varname is defined, and any SRC directives are
1367 # processed.
1369 # You can use $varname like any other variable name.
1370 # However, $varname is NOT a CGI variable and will be
1371 # completely internal to your script. There is NO
1372 # interaction between $varname and the outside world.
1374 # To interpolate a DIV derived text, you can use:
1375 # $varname =~ s/([\]])/\\\1/g; # Mark ']'-quotes
1376 # $varname = eval("qq[$varname]"); # Interpolate all values
1378 # The DIV tags will process IF, UNLESS, CGI and
1379 # SRC attributes. The SRC files will be pre-pended to the
1380 # body text of the tag. SRC blocks are NOT executed.
1382 # CONDITIONAL PROCESSING: THE 'IF' AND 'UNLESS' ATTRIBUTES
1384 # It is often necessary to include code-blocks that should be executed
1385 # conditionally, e.g., only for certain browsers or operating system.
1386 # Furthermore, quite often sanity and security checks are necessary
1387 # before user (form) data can be processed, e.g., with respect to
1388 # email addresses and filenames.
1390 # Checks added to the code are often difficult to find, interpret or
1391 # maintain and in general mess up the code flow. This kind of confussion
1392 # is dangerous.
1393 # Also, for many of the supported "foreign" scripting languages, adding
1394 # these checks is cumbersome or even impossible.
1396 # As a uniform method for asserting the correctness of "context", two
1397 # attributes are added to all supported tags: IF and UNLESS.
1398 # They both evaluate their value and block execution when the
1399 # result is <FALSE> (IF) or <TRUE> (UNLESS) in Perl, e.g.,
1400 # UNLESS='$NUMBER \> 100;' blocks execution if $NUMBER <= 100. Note that
1401 # the backslash in the '\>' is removed and only used to differentiate
1402 # this conditional '>' from the tag-closing '>'. For symmetry, the
1403 # backslash in '\<' is also removed. Inside these conditionals,
1404 # ~/ and ./ are expanded to their respective directory root paths.
1406 # For example, the following tag will be ignored when the filename is
1407 # invalid:
1409 # <SCRIPT TYPE='text/ssperl' CGI='$FILENAME'
1410 # IF='CGIscriptor::CGIsafeFileName($FILENAME);'>
1411 # ...
1412 # </SCRIPT>
1414 # The IF and UNLESS values must be quoted. The same quotes are supported
1415 # as with the other attributes. The SRC attribute is ignored when IF and
1416 # UNLESS block execution.
1418 # NOTE: 'IF' and 'UNLESS' always evaluate perl code.
1421 # THE MAGIC SOURCE ATTRIBUTE (SRC=)
1423 # The SRC attribute inside tags accepts a list of filenames and URL's
1424 # separated by "," comma's (or ";" semicolons).
1425 # ALL the variable values defined in the CGI attribute are available
1426 # in @ARGV as if the file or block was executed from the command line,
1427 # in the exact order in which they were declared in the preceding CGI
1428 # attribute.
1430 # First, a SRC={}-block will be evaluated as if the code inside the
1431 # block was part of a <SCRIPT></SCRIPT> construct, i.e.,
1432 # "print do { code };'';" or `code` (i.e., SAFEqx('code)).
1433 # Only a single block is evaluated. Note that this is processed less
1434 # efficiently than <SCRIPT> </SCRIPT> blocks. Type of evaluation
1435 # depends on the content-type: Perl for text/ssperl and OS shell for
1436 # text/osshell. For other mime types (scripting languages), anything in
1437 # the source block is put in front of the code block "inside" the tag.
1439 # Second, executable files (i.e., -x filename != 0) are evaluated as:
1440 # print `filename \'$ARGV[0]\' \'$ARGV[1]\' ...`
1441 # That is, you can actually call executables savely from the SRC tag.
1443 # Third, text files that match the file pattern, used by CGIscriptor to
1444 # check whether files should be processed ($FilePattern), are
1445 # processed in-line (i.e., recursively) by CGIscriptor as if the code
1446 # was inserted in the original source file. Recursions, i.e., calling
1447 # a file inside itself, are blocked. If you need them, you have to code
1448 # them explicitely using "main::ProcessFile($file_path)".
1450 # Fourth, Perl text files (i.e., -T filename != 0) are evaluated as:
1451 # "do FileName;'';".
1453 # Last, URL's (i.e., starting with 'HTTP://', 'FTP://', 'GOPHER://',
1454 # 'TELNET://', 'WHOIS://' etc.) are loaded
1455 # and printed. The loading and handling of <BASE> and document header
1456 # is done by a command generated by main::GET_URL($URL [, 0]). You can enter your
1457 # own code (default is curl, wget, or snarf and some post-processing to add a <BASE> tag).
1459 # There are two pseudo-file names: PREFIX and POSTFIX. These implement
1460 # a switch from prefixing the SRC code/files (PREFIX, default) before the
1461 # content of the tag to appending the code after the content of the tag
1462 # (POSTFIX). The switches are done in the order in which the PREFIX and
1463 # POSTFIX labels are encountered. You can mix PREFIX and POSTFIX labels
1464 # in any order with the SRC files. Note that the ORDER of file execution
1465 # is determined for prefixed and postfixed files seperately.
1467 # File paths can be preceded by the URL protocol prefix "file://". This
1468 # is simply STRIPPED from the name.
1470 # Example:
1471 # The request
1472 # "http://cgi-bin/Action_Forms.pl/Statistics/Sign_Test.html?positive=8&negative=22
1473 # will result in printing "${SS_PUB}/Statistics/Sign_Test.html"
1474 # With QUERY_STRING = "positive=8&negative=22"
1476 # on encountering the lines:
1477 # <META CONTENT="text/osshell; CGI='$positive=11 $negative=3'">
1478 # <b><SCRIPT LANGUAGE=PERL TYPE="text/ssperl" SRC="./Statistics/SignTest.pl">
1479 # </SCRIPT></b><p>"
1481 # This line will be processed as:
1482 # "<b>`${SS_SCRIPT}/Statistics/SignTest.pl '8' '22'`</b><p>"
1484 # In which "${SS_SCRIPT}/Statistics/SignTest.pl" is an executable script,
1485 # This line will end up printed as:
1486 # "<b>p <= 0.0161</b><p>"
1488 # Note that the META tag itself will never be printed, and is invisible to
1489 # the outside world.
1491 # The SRC files in a DIV or INS tag will be added (pre-pended) to the body
1492 # of the <DIV></DIV> tag. Blocks are NOT executed! If you do not
1493 # need any content, you can use the <DIV...../> format.
1496 # THE CGISCRIPTOR ROOT DIRECTORIES ~/ AND ./
1498 # Inside <SCRIPT></SCRIPT> tags, filepaths starting
1499 # with "~/" are replaced by "$YOUR_HTML_FILES/", this way files in the
1500 # public directories can be accessed without direct reference to the
1501 # actual paths. Filepaths starting with "./" are replaced by
1502 # "$YOUR_SCRIPTS/" and this should only be used for scripts.
1504 # Note: this replacement can seriously affect Perl scripts. Watch
1505 # out for constructs like $a =~ s/aap\./noot./g, use
1506 # $a =~ s@aap\.@noot.@g instead.
1508 # CGIscriptor.pl will assign the values of $SS_PUB and $SS_SCRIPT
1509 # (i.e., $YOUR_HTML_FILES and $YOUR_SCRIPTS) to the environment variables
1510 # $SS_PUB and $SS_SCRIPT. These can be accessed by the scripts that are
1511 # executed.
1512 # Values not preceded by $, ~/, or ./ are used as literals
1515 # OS SHELL SCRIPT EVALUATION (CONTENT-TYPE=TEXT/OSSHELL)
1517 # OS scripts are executed by a "safe" version of the `` operator (i.e.,
1518 # SAFEqx(), see also below) and any output is printed. CGIscriptor will
1519 # interpolate the script and replace all user-supplied CGI-variables by
1520 # their ''-quoted values (actually, all variables defined in CGI attributes
1521 # are quoted). Other Perl variables are interpolated in a simple fasion,
1522 # i.e., $scalar by their value, @list by join(' ', @list), and %hash by
1523 # their name=value pairs. Complex references, e.g., @$variable, are all
1524 # evaluated in a scalar context. Quotes should be used with care.
1525 # NOTE: the results of the shell script evaluation will appear in the
1526 # @CGIscriptorResults stack just as any other result.
1527 # All occurrences of $@% that should NOT be interpolated must be
1528 # preceeded by a "\". Interpolation can be switched off completely by
1529 # setting $CGIscriptor::NoShellScriptInterpolation = 1
1530 # (set to 0 or undef to switch interpolation on again)
1531 # i.e.,
1532 # <SCRIPT TYPE="text/ssperl">
1533 # $CGIscriptor::NoShellScriptInterpolation = 1;
1534 # </SCRIPT>
1537 # RUN TIME TRANSLATION OF INPUT FILES
1539 # Allows general and global conversions of files using Regular Expressions.
1540 # Very handy (but costly) to rewrite legacy pages to a new format.
1541 # Select files to use it on with
1542 # my $TranslationPaths = 'filepattern';
1543 # This is costly. For efficiency, define:
1544 # $TranslationPaths = ''; when not using translations.
1545 # Accepts general regular expressions: [$pattern, $replacement]
1547 # Define:
1548 # my $TranslationPaths = 'filepattern'; # Pattern matching PATH_INFO
1550 # push(@TranslationTable, ['pattern', 'replacement']);
1551 # e.g. (for Ruby Rails):
1552 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
1553 # push(@TranslationTable, ['%>', '</SCRIPT>']);
1555 # Runs:
1556 # my $currentRegExp;
1557 # foreach $currentRegExp (@TranslationTable)
1559 # my ($pattern, $replacement) = @$currentRegExp;
1560 # $$text =~ s!$pattern!$replacement!msg;
1561 # };
1564 # EVALUATION OF OTHER SCRIPTING LANGUAGES
1566 # Adding a MIME-type and an interpreter command to
1567 # %ScriptingLanguages automatically will catch any other
1568 # scripting language in the standard
1569 # <SCRIPT TYPE="[mime]"></SCRIPT> manner.
1570 # E.g., adding: $ScriptingLanguages{'text/sspython'} = 'python';
1571 # will actually execute the folowing code in an HTML page
1572 # (ignore 'REMOTE_HOST' for the moment):
1573 # <SCRIPT TYPE="text/sspython">
1574 # # A Python script
1575 # x = ["A","real","python","script","Hello","World","and", REMOTE_HOST]
1576 # print x[4:8] # Prints the list ["Hello","World","and", REMOTE_HOST]
1577 # </SCRIPT>
1579 # The script code is NOT interpolated by perl, EXCEPT for those
1580 # interpreters that cannot handle variables themselves.
1581 # Currently, several interpreters are pre-installed:
1583 # Perl test - "text/testperl" => 'perl',
1584 # Python - "text/sspython" => 'python',
1585 # Ruby - "text/ssruby" => 'ruby',
1586 # Tcl - "text/sstcl" => 'tcl',
1587 # Awk - "text/ssawk" => 'awk -f-',
1588 # Gnu Lisp - "text/sslisp" => 'rep | tail +5 '.
1589 # "| egrep -v '> |^rep. |^nil\\\$'",
1590 # XLispstat - "text/xlispstat" => 'xlispstat | tail +7 '.
1591 # "| egrep -v '> \\\$|^NIL'",
1592 # Gnu Prolog- "text/ssprolog" => 'gprolog',
1593 # M4 macro's- "text/ssm4" => 'm4',
1594 # Born shell- "text/sh" => 'sh',
1595 # Bash - "text/bash" => 'bash',
1596 # C-shell - "text/csh" => 'csh',
1597 # Korn shell- "text/ksh" => 'ksh',
1598 # Praat - "text/sspraat" => "praat - | sed 's/Praat > //g'",
1599 # R - "text/ssr" => "R --vanilla --slave | sed 's/^[\[0-9\]*] //g'",
1600 # REBOL - "text/ssrebol" =>
1601 # "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\s*\[> \]* //g'",
1602 # PostgreSQL- "text/postgresql" => 'psql 2>/dev/null',
1603 # (psql)
1605 # Note that the "value" of $ScriptingLanguages{mime} must be a command
1606 # that reads Standard Input and writes to standard output. Any extra
1607 # output of interactive interpreters (banners, echo's, prompts)
1608 # should be removed by piping the output through 'tail', 'grep',
1609 # 'sed', or even 'awk' or 'perl'.
1611 # For access to CGI variables there is a special hashtable:
1612 # %ScriptingCGIvariables.
1613 # CGI variables can be accessed in three ways.
1614 # 1. If the mime type is not present in %ScriptingCGIvariables,
1615 # nothing is done and the script itself should parse the relevant
1616 # environment variables.
1617 # 2. If the mime type IS present in %ScriptingCGIvariables, but it's
1618 # value is empty, e.g., $ScriptingCGIvariables{"text/sspraat"} = '';,
1619 # the script text is interpolated by perl. That is, all $var, @array,
1620 # %hash, and \-slashes are replaced by their respective values.
1621 # 3. In all other cases, the CGI and environment variables are added
1622 # in front of the script according to the format stored in
1623 # %ScriptingCGIvariables. That is, the following (pseudo-)code is
1624 # executed for each CGI- or Environment variable defined in the CGI-tag:
1625 # printf(INTERPRETER, $ScriptingCGIvariables{$mime}, $CGI_NAME, $CGI_VALUE);
1627 # For instance, "text/testperl" => '$%s = "%s";' defines variable
1628 # definitions for Perl, and "text/sspython" => '%s = "%s"' for Python
1629 # (note that these definitions are not save, the real ones contain '-quotes).
1631 # THIS WILL NOT WORK FOR @VARIABLES, the (empty) $VARIABLES will be used
1632 # instead.
1634 # The $CGI_VALUE parameters are "shrubed" of all control characters
1635 # and quotes (by &shrubCGIparameter($CGI_VALUE)) for the options 2 and 3.
1636 # Control characters are replaced by \0<octal ascii value> (the exception
1637 # is \015, the newline, which is replaced by \n) and quotes
1638 # and backslashes by their HTML character
1639 # value (' -> &#39; ` -> &#96; " -> &quot; \ -> &#92; & -> &amper;).
1640 # For example:
1641 # if a client would supply the string value (in standard perl, e.g.,
1642 # \n means <newline>)
1643 # "/dev/null';\nrm -rf *;\necho '"
1644 # it would be processed as
1645 # '/dev/null&#39;;\nrm -rf *;\necho &#39;'
1646 # (e.g., sh or bash would process the latter more according to your
1647 # intentions).
1648 # If your intepreter requires different protection measures, you will
1649 # have to supply these in %main::SHRUBcharacterTR (string => translation),
1650 # e.g., $SHRUBcharacterTR{"\'"} = "&#39;";
1652 # Currently, the following definitions are used:
1653 # %ScriptingCGIvariables = (
1654 # "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value' (for testing)
1655 # "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
1656 # "text/ssruby" => '@%s = "%s"', # Ruby @VAR = "value"
1657 # "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
1658 # "text/ssawk" => '%s = "%s";', # Awk VAR = "value";
1659 # "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
1660 # "text/xlispstat" => '(setq %s "%s")', # Xlispstat (setq VAR "value")
1661 # "text/ssprolog" => '', # Gnu prolog (interpolated)
1662 # "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
1663 # "text/sh" => "\%s='\%s';", # Born shell VAR='value';
1664 # "text/bash" => "\%s='\%s';", # Born again shell VAR='value';
1665 # "text/csh" => "\$\%s = '\%s';", # C shell $VAR = 'value';
1666 # "text/ksh" => "\$\%s = '\%s';", # Korn shell $VAR = 'value';
1667 # "text/sspraat" => '', # Praat (interpolation)
1668 # "text/ssr" => '%s <- "%s";', # R VAR <- "value";
1669 # "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
1670 # "text/postgresql" => '', # PostgreSQL (interpolation)
1671 # "" => ""
1672 # );
1674 # Four tables allow fine-tuning of interpreter with code that should be
1675 # added before and after each code block:
1677 # Code added before each script block
1678 # %ScriptingPrefix = (
1679 # "text/testperl" => "\# Prefix Code;", # Perl script testing
1680 # "text/ssm4" => 'divert(0)' # M4 macro's (open STDOUT)
1681 # );
1682 # Code added at the end of each script block
1683 # %ScriptingPostfix = (
1684 # "text/testperl" => "\# Postfix Code;", # Perl script testing
1685 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1686 # );
1687 # Initialization code, inserted directly after opening (NEVER interpolated)
1688 # %ScriptingInitialization = (
1689 # "text/testperl" => "\# Initialization Code;", # Perl script testing
1690 # "text/ssawk" => 'BEGIN {', # Server Side awk scripts
1691 # "text/sslisp" => '(prog1 nil ', # Lisp (rep)
1692 # "text/xlispstat" => '(prog1 nil ', # xlispstat
1693 # "text/ssm4" => 'divert(-1)' # M4 macro's (block STDOUT)
1694 # );
1695 # Cleanup code, inserted before closing (NEVER interpolated)
1696 # %ScriptingCleanup = (
1697 # "text/testperl" => "\# Cleanup Code;", # Perl script testing
1698 # "text/sspraat" => 'Quit',
1699 # "text/ssawk" => '};', # Server Side awk scripts
1700 # "text/sslisp" => '(princ "\n" standard-output)).' # Closing print to rep
1701 # "text/xlispstat" => '(print "" *standard-output*)).' # Closing print to xlispstat
1702 # "text/postgresql" => '\q',
1703 # );
1706 # The SRC attribute is NOT magical for these interpreters. In short,
1707 # all code inside a source file or {} block is written verbattim
1708 # to the interpreter. No (pre-)processing or executional magic is done.
1710 # A serious shortcomming of the described mechanism for handling other
1711 # (scripting) languages, with respect to standard perl scripts
1712 # (i.e., 'text/ssperl'), is that the code is only executed when
1713 # the pipe to the interpreter is closed. So the pipe has to be
1714 # closed at the end of each block. This means that the state of the
1715 # interpreter (e.g., all variable values) is lost after the closing of
1716 # the next </SCRIPT> tag. The standard 'text/ssperl' scripts retain
1717 # all values and definitions.
1719 # APPLICATION MIME TYPES
1721 # To ease some important auxilliary functions from within the
1722 # html pages I have added them as MIME types. This uses
1723 # the mechanism that is also used for the evaluation of
1724 # other scripting languages, with interpolation of CGI
1725 # parameters (and perl-variables). Actually, these are
1726 # defined exactly like any other "scripting language".
1728 # text/ssdisplay: display some (HTML) text with interpolated
1729 # variables (uses `cat`).
1730 # text/sslogfile: write (append) the interpolated block to the file
1731 # mentioned on the first, non-empty line
1732 # (the filename can be preceded by 'File: ',
1733 # note the space after the ':',
1734 # uses `awk .... >> <filename>`).
1735 # text/ssmailto: send email directly from within the script block.
1736 # The first line of the body must contain
1737 # To:Name@Valid.Email.Address
1738 # (note: NO space between 'To:' and the email adres)
1739 # For other options see the mailto man pages.
1740 # It works by directly sending the (interpolated)
1741 # content of the text block to a pipe into the
1742 # Linux program 'mailto'.
1744 # In these script blocks, all Perl variables will be
1745 # replaced by their values. All CGI variables are cleaned before
1746 # they are used. These CGI variables must be redefined with a
1747 # CGI attribute to restore their original values.
1748 # In general, this will be more secure than constructing
1749 # e.g., your own email command lines. For instance, Mailto will
1750 # not execute any odd (forged) email addres, but just stops
1751 # when the email address is invalid and awk will construct
1752 # any filename you give it (e.g. '<File;rm\\\040-f' would end up
1753 # as a "valid" UNIX filename). Note that it will also gladly
1754 # store this file anywhere (/../../../etc/passwd will work!).
1755 # Use the CGIscriptor::CGIsafeFileName() function to clean the
1756 # filename.
1758 # SHELL SCRIPT PIPING
1760 # If a shell script starts with the UNIX style "#! <shell command> \n"
1761 # line, the rest of the shell script is piped into the indicated command,
1762 # i.e.,
1763 # open(COMMAND, "| command");print COMMAND $RestOfScript;
1765 # In many ways this is equivalent to the MIME-type profiling for
1766 # evaluating other scripting languages as discussed above. The
1767 # difference breaks down to convenience. Shell script piping is a
1768 # "raw" implementation. It allows you to control all aspects of
1769 # execution. Using the MIME-type profiling is easier, but has a
1770 # lot of defaults built in that might get in the way. Another
1771 # difference is that shell script piping uses the SAFEqx() function,
1772 # and MIME-type profiling does not.
1774 # Execution of shell scripts is under the control of the Perl Script blocks
1775 # in the document. The MIME-type triggered execution of <SCRIPT></SCRIPT>
1776 # blocks can be simulated easily. You can switch to a different shell,
1777 # e.g. tcl, completely by executing the following Perl commands inside
1778 # your document:
1780 # <SCRIPT TYPE="text/ssperl">
1781 # $main::ShellScriptContentType = "text/ssTcl"; # Yes, you can do this
1782 # CGIscriptor::RedirectShellScript('/usr/bin/tcl'); # Pipe to Tcl
1783 # $CGIscriptor::NoShellScriptInterpolation = 1;
1784 # </SCRIPT>
1786 # After this script is executed, CGIscriptor will parse scripts of
1787 # TYPE="text/ssTcl" and pipe their contents into '|/usr/bin/tcl'
1788 # WITHOUT interpolation (i.e., NO substitution of Perl variables).
1789 # The crucial function is :
1790 # CGIscriptor::RedirectShellScript('/usr/bin/tcl')
1791 # After executing this function, all shell scripts AND all
1792 # calls to SAFEqx()) are piped into '|/usr/bin/tcl'. If the argument
1793 # of RedirectShellScript is empty, e.g., '', the original (default)
1794 # value is reset.
1796 # The standard output, STDOUT, of any pipe is send to the client.
1797 # Currently, you should be carefull with quotes in such a piped script.
1798 # The results of a pipe is NOT put on the @CGIscriptorResults stack.
1799 # As a result, you do not have access to the output of any piped (#!)
1800 # process! If you want such access, execute
1801 # <SCRIPT TYPE="text/osshell">echo "script"|command</SCRIPT>
1802 # or
1803 # <SCRIPT TYPE="text/ssperl">
1804 # $resultvar = SAFEqx('echo "script"|command');
1805 # </SCRIPT>.
1807 # Safety is never complete. Although SAFEqx() prevents some of the
1808 # most obvious forms of attacks and security slips, it cannot prevent
1809 # them all. Especially, complex combinations of quotes and intricate
1810 # variable references cannot be handled safely by SAFEqx. So be on
1811 # guard.
1814 # PERL CODE EVALUATION (CONTENT-TYPE=TEXT/SSPERL)
1816 # All PERL scripts are evaluated inside a PERL package. This package
1817 # has a separate name space. This isolated name space protects the
1818 # CGIscriptor.pl program against interference from user code. However,
1819 # some variables, e.g., $_, are global and cannot be protected. You are
1820 # advised NOT to use such global variable names. You CAN write
1821 # directives that directly access the variables in the main program.
1822 # You do so at your own risk (there is definitely enough rope available
1823 # to hang yourself). The behavior of CGIscriptor becomes undefined if
1824 # you change its private variables during run time. The PERL code
1825 # directives are used as in:
1826 # $Result = eval($directive); print $Result;'';
1827 # ($directive contains all text between <SCRIPT></SCRIPT>).
1828 # That is, the <directive> is treated as ''-quoted string and
1829 # the result is treated as a scalar. To prevent the VALUE of the code
1830 # block from appearing on the client's screen, end the directive with
1831 # ';""</SCRIPT>'. Evaluated directives return the last value, just as
1832 # eval(), blocks, and subroutines, but only as a scalar.
1834 # IMPORTANT: All PERL variables defined are persistent. Each <SCRIPT>
1835 # </SCRIPT> construct is evaluated as a {}-block with associated scope
1836 # (e.g., for "my $var;" declarations). This means that values assigned
1837 # to a PERL variable can be used throughout the document unless they
1838 # were declared with "my". The following will actually work as intended
1839 # (note that the ``-quotes in this example are NOT evaluated, but used
1840 # as simple quotes):
1842 # <META CONTENT="text/ssperl; CGI=`$String='abcdefg'`">
1843 # anything ...
1844 # <SCRIPT TYPE=text/ssperl>@List = split('', $String);</SCRIPT>
1845 # anything ...
1846 # <SCRIPT TYPE=text/ssperl>join(", ", @List[1..$#List]);</SCRIPT>
1848 # The first <SCRIPT TYPE=text/ssperl></SCRIPT> construct will return the
1849 # value scalar(@List), the second <SCRIPT TYPE=text/ssperl></SCRIPT>
1850 # construct will print the elements of $String separated by commas, leaving
1851 # out the first element, i.e., $List[0].
1853 # Another warning: './' and '~/' are ALWAYS replaced by the values of
1854 # $YOUR_SCRIPTS and $YOUR_HTML_FILES, respectively . This can interfere
1855 # with pattern matching, e.g., $a =~ s/aap\./noot\./g will result in the
1856 # evaluations of $a =~ s/aap\\${YOUR_SCRIPTS}noot\\${YOUR_SCRIPTS}g. Use
1857 # s@<regexp>.@<replacement>.@g instead.
1860 # SERVER SIDE SESSIONS AND ACCESS CONTROL (LOGIN)
1862 # An infrastructure for user acount authorization and file access control
1863 # is available. Each request is matched against a list of URL path patterns.
1864 # If the request matches, a Session Ticket is required to access the URL.
1865 # This Session Ticket should be present as a CGI parameter or Cookie, eg:
1867 # CGI: SESSIONTICKET=&lt;value&gt;
1868 # Cookie: CGIscriptorSESSION=&lt;value&gt;
1870 # The example implementation stores Session Tickets as files in a local
1871 # directory. To create Session Tickets, a Login request must be given
1872 # with a LOGIN=&lt;value&gt; CGI parameter, a user name and a (doubly hashed)
1873 # password. The user name and (singly hashed) password are stored in a
1874 # PASSWORD ticket with the same name as the user account (name cleaned up
1875 # for security).
1877 # The example session model implements 4 functions:
1878 # - Login
1879 # The password is hashed with the user name and server side salt, and then
1880 # hashed with a random salt. Client and Server both perform these actions
1881 # and the Server only grants access if restults are the same. The server
1882 # side only stores the password hashed with the user name and
1883 # server side salt. Neither the plain password, nor the hashed password is
1884 # ever exchanged. Only values hashed with the one-time salt are exchanged.
1885 # - Session
1886 # For every access to a restricted URL, the Session Ticket is checked before
1887 # access is granted. There are three session modes. The first uses a fixed
1888 # Session Ticket that is stored as a cookie value in the browser (actually,
1889 # as a sessionStorage value). The second uses only the IP address at login
1890 # to authenticate requests. The third
1891 # is a Challenge mode, where the client has to calculate the value of the
1892 # next one-time Session Ticket from a value derived from the password and
1893 # a random string.
1894 # - Password Change
1895 # A new password is hashed with the user name and server side salt, and
1896 # then encrypted (XORed)
1897 # with the old password hashed with the user name and salt. That value is
1898 # exchanged and XORed with the stored old hashed(password+username+salt).
1899 # Again, the stored password value is never exchanged unencrypted.
1900 # - New Account
1901 # The text of a new account (Type: PASSWORD) file is constructed from
1902 # the new username (CGI: NEWUSERNAME, converted to lowercase) and
1903 # hashed new password (CGI: NEWPASSWORD). The same process is used to encrypt
1904 # the new password as is used for the Password Change function.
1905 # Again, the stored password value is never exchanged unencrypted.
1906 # Some default setting are encoded. For display in the browser, the new password
1907 # is reencrypted (XORed) with a special key, the old password hash
1908 # hashed with a session specific random hex value sent initially with the
1909 # session login ticket ($RANDOMSALT).
1910 # For example for user "NewUser" and password "NewPassword" with filename
1911 # "newuser":
1913 # Type: PASSWORD
1914 # Username: newuser
1915 # Password: 19afeadfba8d5dcd252e157fafd3010859f8762b87682b6b6cdb3e565194fa91
1916 # IPaddress: 127\.0\.0\.1
1917 # AllowedPaths: ^/Private/[\w\-]+\.html?
1918 # AllowedPaths: ^/Private/newuser/
1919 # Salt: e93cf858a1d5626bf095ea5c25df990dfa969ff5a5dc908b22c9a5229b525f65
1920 # Session: SESSION
1921 # Date: Fri Jun 29 12:46:22 2012
1922 # Time: 1340973982
1923 # Signature: 676c35d3aa63540293ea5442f12872bfb0a22665b504f58f804582493b6ef04e
1925 # The password is created with the commands:
1927 # printf '%s' 'NewPasswordnewuser970e68017413fb0ea84d7fe3c463077636dd6d53486910d4a53c693dd4109b1a'|shasum -a 256
1929 # If the CPAN mudule Digest is installed, it is used instead of the commands.
1930 # However, the password account files are protected against unauthorized change.
1931 # To obtain a valid Password account, the following command should be given:
1933 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
1934 # masterkey='Sherlock investigates oleander curry in Bath' \
1935 # password='NewPassword' \
1936 # Private/.Passwords/newuser
1939 # Implementation
1941 # The session authentication mechanism is based on the exchange of ticket
1942 # identifiers. A ticket identifier is just a string of characters, a name
1943 # or a random 64 character hexadecimal string. Authentication is based
1944 # on a (password derived) shared secret and the ability to calculate ticket
1945 # identifiers from this shared secret. Ticket identifiers should be
1946 # "safe" filenames (except user names). There are four types of tickets:
1947 # PASSWORD: User account descriptors, including a user name and password
1948 # LOGIN: Temporary anonymous tickets used during login
1949 # IPADDRESS: Authentication tokens that allow access based on the IP address of the request
1950 # SESSION: Reusable authentication tokens
1951 # CHALLENGE: One-time authentication tokens
1952 # All tickets can have an expiration date in the form of a time duration
1953 # from creation, in seconds, minutes, hours, or days (+duration[smhd]).
1954 # An absolute time can be given in seconds since the epoch of the server host.
1955 # Note that expiration times of CHALLENGE authentication tokens are calculated
1956 # from the last access time. Accounts can include a maximal lifetime
1957 # for session tickets (MaxLifetime).
1959 # A Login page should create a LOGIN ticket file locally and send a
1960 # server specific salt, a Random salt, and a LOGIN ticket
1961 # identifier. The server side compares the username and hashed password,
1962 # actually hashed(hashed(password+serversalt)+Random salt) from the client with
1963 # the values it calculates from the stored Random salt from the LOGIN
1964 # ticket and the hashed(password+serversalt) from the PASSWORD ticket. If
1965 # successful, a new SESSION ticket is generated as a (double) hash sum of the stored
1966 # password and the LOGIN ticket. This SESSION ticket should also be
1967 # generated by the client and stored as sessionStorage and cookie values
1968 # as needed. The Username, IP address and Path are available as
1969 # $LoginUsername, $LoginIPaddress, and $LoginPath, respectively.
1971 # The CHALLENGE protocol stores the single hashed version of the SESSION tickets.
1972 # However, this value is not exchanged, but kept secret in the JavaScript
1973 # sessionStorage object. Instead, every page returned from the
1974 # server will contain a one-time Challenge value ($CHALLENGETICKET) which
1975 # has to be hashed with the stored value to return the current ticket
1976 # id string.
1978 # In the current example implementation, all random values are created as
1979 # full, 256 bit SHA256 hash values (Hex strings) of 64 bytes read from
1980 # /dev/urandom.
1983 # Authorization
1985 # A limited level of authorization tuning is build into the login system.
1986 # Each account file (PASSWORD ticket file) can contain a number of
1987 # Capabilities lines. These control special priveliges. The
1988 # Capabilities can be checked inside the HTML pages as part of the
1989 # ticket information. Two privileges are handled internally:
1990 # CreateUser and VariableREMOTE_ADDR.
1991 # CreateUser allows the logged in user to create a new user account.
1992 # With VariableREMOTE_ADDR, the session of the logged in user is
1993 # not limited to the Remote IP address from which the inital log-in took
1994 # place. Sessions can hop from one apparant (proxy) IP address to another,
1995 # e.g., when using Tor. Any IPaddress patterns given in the PASSWORD
1996 # ticket file remain in effect during the session. For security reasons,
1997 # the VariableREMOTE_ADDR capability is only effective if the session
1998 # type is CHALLENGE.
2001 # Security considerations with Session tickets
2003 # For strong security, please use end-to-end encryption. This can be
2004 # achieved using a VPN (Virtual Private Network), SSH tunnel, or a HTTPS
2005 # capable server with OpenSSL. The session ticket system of CGIscriptor.pl
2006 # is intended to be used as a simple authentication mechanism WITHOUT
2007 # END-TO-END ENCRYPTION. The authenticating mechanism tries to use some
2008 # simple means to protect the authentication process from eavesdropping.
2009 # For this it uses a secure hash function, SHA256. For all practial purposes,
2010 # it is impossible to "decrypt" a SHA256 sum. But this login scheme is
2011 # only as secure as your browser. Which, in general, is not very secure.
2013 # One fundamental weakness of the implemented procedure is that the Client
2014 # obtains the code to encrypt the passwords from the server. It is the JavaScript
2015 # code in the HTML pages. An attacker who could place himself between Server
2016 # and Client, a man in the middle attack (MITM), could change the code to
2017 # reveal the plaintext password and other information. There is no
2018 # real protection against this attack without end-to-end encryption and
2019 # authentication. A simple, but rather cumbersome, way to check for such
2020 # attacks would be to store known good copys of the pages (downloaded
2021 # with a browser or automatically with curl or wget) and
2022 # then use other tools to download new pages at random intervals and compare
2023 # them to the old pages. For instance, the following line would remove
2024 # the variable ticket codes and give a fixed SHA256 sum for the original
2025 # Login.html page+code:
2026 # curl http://localhost:8080/Private/index.html | \
2027 # sed 's/=\"[a-z0-9]\{64\}\"/=""/g' | shasum -a 256
2028 # A simple diff command between old and new files should give only
2029 # differences in half a dozen lines, where only hexadecimal salt values
2030 # will actually differ.
2032 # A sort of solution for the MITM attack problem that might protect at
2033 # least the plaintext password would be to run a trusted web
2034 # page from local storage to handle password input. The solution would be
2035 # to add a hidden iFrame tag loading the untrusted page from the URL and
2036 # extract the needed ticket and salt values. Then run the stored, trusted,
2037 # code with these values. It is not (yet) possible to set the
2038 # required session storage inside the browser, so this method only works
2039 # for IPADDRESS sessions and plain SESSION tickets. There are many
2040 # security problems with this "solution".
2042 # Humans tend to reuse passwords. A compromise of a site running
2043 # CGIscriptor.pl could therefore lead to a compromise of user accounts at
2044 # other sites. Therefore, plain text passwords are never stored, used, or
2045 # exchanged. Instead, the plain password and user name are "encrypted" with
2046 # a server site salt value. Actually, all are concatenated and hashed
2047 # with a one-way secure hash function (SHA256) into a single string.
2048 # Whenever the word "password" is used, this hash sum is meant. Note that
2049 # the salts are generated from /dev/urandom. You should check whether the
2050 # implementation of /dev/urandom on your platform is secure before
2051 # relying on it. This might be a problem when running CGIscriptor under
2052 # Cygwin on MS Windows.
2053 # Note: no attempt is made to slow down the password hash, so bad
2054 # passwords can be cracked by brute force
2056 # As the (hashed) passwords are all that is needed to identify at the site,
2057 # these should not be stored in this form. A site specific passphrase
2058 # can be entered as an environment variable ($ENV{'CGIMasterKey'}). This
2059 # phrase is hashed with the server site salt and the result is hashed with
2060 # the user name and then XORed with the password when it is stored. Also, to
2061 # detect changes to the account (PASSWORD) and session tickets, a
2062 # (HMAC) hash of some of the contents of the ticket with the server salt and
2063 # CGIMasterKey is stored in each ticket.
2065 # Creating a valid (hashed) password, encrypt it with the CGIMasterKey and
2066 # construct a signature of the ticket are non-trivial. This has to be redone
2067 # with every change of the ticket file or CGIMasterKey change. CGIscriptor
2068 # can do this from the command line with the command:
2070 # perl CGIscriptor.pl --managelogin salt=Private/.Passwords/SALT \
2071 # masterkey='Sherlock investigates oleander curry in Bath' \
2072 # password='There is no password like more password' \
2073 # admin
2075 # CGIscriptor will exit after this command with the first option being
2076 # --managelogin. Options have the form:
2078 # salt=[file or string]
2079 # Server salt value to use io the value
2080 # stored in the ticket file. Will replace the stored value if a new
2081 # password is given. If you change the server salt, you have to
2082 # reset all the passwords. There is absolutely no procedure known
2083 # to recover plaintext passwords, except asking the account holders.
2084 # You are strongly adviced to make a backup before you apply such a change
2085 # masterkey=[file or string]
2086 # CGIMasterKey used to read and decrypt the ticket
2087 # newmasterkey=[file or string]
2088 # CGIMasterKey used to encrypt, sign,
2089 # and write the ticket. Defaults to the masterkey. If you change
2090 # the masterkey, you will have to reset all the accounts. You are strongly
2091 # adviced to make a backup before you apply such a change
2092 # password=[file or string]
2093 # New plaintext password
2095 # When the value of an option is a existing file path, the first line of
2096 # that file is used. Options are followed by one or more paths plus names
2097 # of existing ticket files. Each password option is only used for a single
2098 # ticket file. It is most definitely a bad idea to use a password that is
2099 # identical to an existing filepath, as the file will be read instead. Be
2100 # aware that the name of the file should be a cleaned up version of the
2101 # Username. This will not be checked.
2103 # For the authentication and a change of password, the (old) password
2104 # is used to "encrypt" a random one-time token or the new password,
2105 # respectively. For authentication, decryption is not needed, so a secure
2106 # hash function (SHA256) is used to create a one-way hash sum "encryption".
2107 # A new password must be decrypted. New passwords are encryped by XORing
2108 # them with the old password.
2110 # Strong Passwords: It is so easy
2111 # If you only could see what you are typing
2113 # Your password might be vulnerable to brute force guessing
2114 # (https://en.wikipedia.org/wiki/Brute_force_attack).
2115 # Protections against such attacks are costly in terms of code
2116 # complexity, bugs, and execution time. However, there is a very
2117 # simple and secure counter measure. See the XKCD comic
2118 # (http://xkcd.com/936/). The phrase, "There is no password like more
2119 # password" would be both much easier to remember, and still stronger
2120 # than "h4]D%@m:49", at least before this phrase was pasted as an
2121 # example on the Internet.
2123 # For the procedures used at this site, a basic computer setup can
2124 # check in the order of a billion passwords per second. You need a
2125 # password (or phrase) strength in the order of 56 bits to be a
2126 # little secure (one year on a single computer). Please be so kind
2127 # and add the name of your favorite flower, dish, fictional
2128 # character, or small town to your password. Say, Oleander, Curry,
2129 # Sherlock, or Bath, UK (each adds ~12 bits) or even the phrase "Sherlock
2130 # investigates oleander curry in Bath" (adds > 56 bits, note that
2131 # oleander is poisonous, so do not try this curry at home). That
2132 # would be more effective than adding a thousand rounds of encryption.
2133 # Typing long passwords without seeing what you are typing is
2134 # problematic. So a button should be included to make password
2135 # visible.
2138 # Technical matters
2140 # Client side JavaScript code definitions. Variable names starting with '$'
2141 # are CGIscriptor CGI variables. Some of the hashes could be strengthened
2142 # by switching to HMAC signatures. However, the security issues of
2143 # maintaining parallel functions for HMAC in both Perl and Javascript seem
2144 # to be more serious than the attack vectors against the hashes. But HMAC
2145 # is indeed used for the ticket signatures.
2147 # // On Login
2148 # HashPlaintextPassword() {
2149 # var plaintextpassword = document.getElementById('PASSWORD');
2150 # var serversalt = document.getElementById('SERVERSALT');
2151 # var username = document.getElementById('CGIUSERNAME');
2152 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2154 # var randomsalt = $RANDOMSALT; // From CGIscriptor
2155 # var loginticket = $LOGINTICKET; // From CGIscriptor
2156 # // Hash plaintext password
2157 # var password = HashPlaintextPassword();
2158 # // Authorize login
2159 # var hashedpassword = hex_sha256(randomsalt+password);
2160 # // Sessionticket
2161 # var sessionticket = hex_sha256(loginticket+password);
2162 # sessionStorage.setItem("CGIscriptorPRIVATE", sessionticket);
2163 # // Secretkey for encrypting new passwords, acts like a one-time pad
2164 # // Is set anew with every login, ie, also whith password changes
2165 # // and for each create new user request
2166 # var secretkey = hex_sha256(password+loginticket+randomsalt);
2167 # sessionStorage.setItem("CGIscriptorSECRET", secretkey);
2169 # // For a SESSION type request
2170 # sessionticket = hex_sha256(sessionStorage.getItem("CGIscriptorPRIVATE"));
2171 # createCookie("CGIscriptorSESSION",sessionticket, 0, "");
2173 // For a CHALLENGE type request
2174 # var sessionset = "$CHALLENGETICKET"; // From CGIscriptor
2175 # var sessionkey = sessionStorage.getItem("CGIscriptorPRIVATE");
2176 # sessionticket = hex_sha256(sessionset+sessionkey);
2177 # createCookie("CGIscriptorCHALLENGE",sessionticket, 0, "");
2179 # // For transmitting a new password
2180 # HashPlaintextNewPassword() {
2181 # var plaintextpassword = document.getElementById('NEWPASSWORD');
2182 # var serversalt = document.getElementById('SERVERSALT');
2183 # var username = document.getElementById('NEWUSERNAME');
2184 # return hex_sha256(plaintextpassword.value+username.value.toLowerCase()+serversalt.value);
2187 # var newpassword = document.getElementById('NEWPASSWORD');
2188 # var newpasswordrep = document.getElementById('NEWPASSWORDREP');
2189 # // Hash plaintext password
2190 # newpassword.value = HashPlaintextNewPassword();
2191 # var secretkey = sessionStorage.getItem("CGIscriptorSECRET");
2193 # var encrypted = XOR_hex_strings(secretkey, newpassword.value);
2194 # newpassword.value = encrypted;
2195 # newpasswordrep.value = encrypted;
2197 # // XOR of hexadecimal strings of equal length
2198 # function XOR_hex_strings(hex1, hex2) {
2199 # var resultHex = "";
2200 # var maxlength = Math.max(hex1.length, hex2.length);
2202 # for(var i=0; i &lt; maxlength; ++i) {
2203 # var h1 = hex1.charAt(i);
2204 # if(! h1) h1='0';
2205 # var h2 = hex2.charAt(i);
2206 # if(! h2) h2 ='0';
2207 # var d1 = parseInt(h1,16);
2208 # var d2 = parseInt(h2,16);
2209 # var resultD = d1^d2;
2210 # resultHex = resultHex+resultD.toString(16);
2211 # };
2212 # return resultHex;
2213 # };
2215 # Password encryption based on $ENV{'CGIMasterKey'}.
2216 # Server side Perl code:
2218 # # Password encryption
2219 # my $masterkey = $ENV{'CGIMasterKey'}
2220 # my $hash1 = hash_string($masterkey.$serversalt);
2221 # my $CryptKey = hash_string($username.$hash1);
2222 # $password = XOR_hex_strings($CryptKey,$password);
2224 # # Key for HMAC signing
2225 # my $hash1 = hash_string($masterkey.$serversalt);
2226 # my $HMACKey = hash_string($username.$hash1);
2230 # USER EXTENSIONS
2232 # A CGIscriptor package is attached to the bottom of this file. With
2233 # this package you can personalize your version of CGIscriptor by
2234 # including often used perl routines. These subroutines can be
2235 # accessed by prefixing their names with CGIscriptor::, e.g.,
2236 # <SCRIPT LANGUAGE=PERL TYPE=text/ssperl>
2237 # CGIscriptor::ListDocs("/Books/*") # List all documents in /Books
2238 # </SCRIPT>
2239 # It already contains some useful subroutines for Document Management.
2240 # As it is a separate package, it has its own namespace, isolated from
2241 # both the evaluator and the main program. To access variables from
2242 # the document <SCRIPT></SCRIPT> blocks, use $CGIexecute::<var>.
2244 # Currently, the following functions are implemented
2245 # (precede them with CGIscriptor::, see below for more information)
2246 # - SAFEqx ('String') -> result of qx/"String"/ # Safe application of ``-quotes
2247 # Is used by text/osshell Shell scripts. Protects all CGI
2248 # (client-supplied) values with single quotes before executing the
2249 # commands (one of the few functions that also works WITHOUT CGIscriptor::
2250 # in front)
2251 # - defineCGIvariable ($name[, $default) -> 0/1 (i.e., failure/success)
2252 # Is used by the META tag to define and initialize CGI and ENV
2253 # name/value pairs. Tries to obtain an initializing value from (in order):
2254 # $ENV{$name}
2255 # The Query string
2256 # The default value given (if any)
2257 # (one of the few functions that also works WITHOUT CGIscriptor::
2258 # in front)
2259 # - CGIsafeFileName (FileName) -> FileName or ""
2260 # Check a string against the Allowed File Characters (and ../ /..).
2261 # Returns an empty string for unsafe filenames.
2262 # - CGIsafeEmailAddress (Email) -> Email or ""
2263 # Check a string against correct email address pattern.
2264 # Returns an empty string for unsafe addresses.
2265 # - RedirectShellScript ('CommandString') -> FILEHANDLER or undef
2266 # Open a named PIPE for SAFEqx to receive ALL shell scripts
2267 # - URLdecode (URL encoded string) -> plain string # Decode URL encoded argument
2268 # - URLencode (plain string) -> URL encoded string # Encode argument as URL code
2269 # - CGIparseValue (ValueName [, URL_encoded_QueryString]) -> Decoded value
2270 # Extract the value of a CGI variable from the global or a private
2271 # URL-encoded query (multipart POST raw, NOT decoded)
2272 # - CGIparseValueList (ValueName [, URL_encoded_QueryString])
2273 # -> List of decoded values
2274 # As CGIparseValue, but now assembles ALL values of ValueName into a list.
2275 # - CGIparseHeader (ValueName [, URL_encoded_QueryString]) -> Header
2276 # Extract the header of a multipart CGI variable from the global or a private
2277 # URL-encoded query ("" when not a multipart variable or absent)
2278 # - CGIparseForm ([URL_encoded_QueryString]) -> Decoded Form
2279 # Decode the complete global URL-encoded query or a private
2280 # URL-encoded query
2281 # - read_url(URL) # Returns the page from URL (with added base tag, both FTP and HTTP)
2282 # Uses main::GET_URL(URL, 1) to get at the command to read the URL.
2283 # - BrowseDirs(RootDirectory [, Pattern, Startdir, CGIname]) # print browsable directories
2284 # - ListDocs(Pattern [,ListType]) # Prints a nested HTML directory listing of
2285 # all documents, e.g., ListDocs("/*", "dl");.
2286 # - HTMLdocTree(Pattern [,ListType]) # Prints a nested HTML listing of all
2287 # local links starting from a given document, e.g.,
2288 # HTMLdocTree("/Welcome.html", "dl");
2291 # THE RESULTS STACK: @CGISCRIPTORRESULTS
2293 # If the pseudo-variable "$CGIscriptorResults" has been defined in a
2294 # META tag, all subsequent SCRIPT and META results are pushed
2295 # on the @CGIscriptorResults stack. This list is just another
2296 # Perl variable and can be used and manipulated like any other list.
2297 # $CGIscriptorResults[-1] is always the last result.
2298 # This is only of limited use, e.g., to use the results of an OS shell
2299 # script inside a Perl script. Will NOT contain the results of Pipes
2300 # or code from MIME-profiling.
2303 # USEFULL CGI PREDEFINED VARIABLES (DO NOT ASSIGN TO THESE)
2305 # $CGI_HOME - The DocumentRoot directory
2306 # $CGI_Decoded_QS - The complete decoded Query String
2307 # $CGI_Content_Length - The ACTUAL length of the Query String
2308 # $CGI_Date - Current date and time
2309 # $CGI_Year $CGI_Month $CGI_Day $CGI_WeekDay - Current Date
2310 # $CGI_Time - Current Time
2311 # $CGI_Hour $CGI_Minutes $CGI_Seconds - Current Time, split
2312 # GMT Date/Time:
2313 # $CGI_GMTYear $CGI_GMTMonth $CGI_GMTDay $CGI_GMTWeekDay $CGI_GMTYearDay
2314 # $CGI_GMTHour $CGI_GMTMinutes $CGI_GMTSeconds $CGI_GMTisdst
2317 # USEFULL CGI ENVIRONMENT VARIABLES
2319 # Variables accessible (in APACHE) as $ENV{<name>}
2320 # (see: "http://hoohoo.ncsa.uiuc.edu/cgi/env.html"):
2322 # QUERY_STRING - The query part of URL, that is, everything that follows the
2323 # question mark.
2324 # PATH_INFO - Extra path information given after the script name
2325 # PATH_TRANSLATED - Extra pathinfo translated through the rule system.
2326 # (This doesn't always make sense.)
2327 # REMOTE_USER - If the server supports user authentication, and the script is
2328 # protected, this is the username they have authenticated as.
2329 # REMOTE_HOST - The hostname making the request. If the server does not have
2330 # this information, it should set REMOTE_ADDR and leave this unset
2331 # REMOTE_ADDR - The IP address of the remote host making the request.
2332 # REMOTE_IDENT - If the HTTP server supports RFC 931 identification, then this
2333 # variable will be set to the remote user name retrieved from
2334 # the server. Usage of this variable should be limited to logging
2335 # only.
2336 # AUTH_TYPE - If the server supports user authentication, and the script
2337 # is protected, this is the protocol-specific authentication
2338 # method used to validate the user.
2339 # CONTENT_TYPE - For queries which have attached information, such as HTTP
2340 # POST and PUT, this is the content type of the data.
2341 # CONTENT_LENGTH - The length of the said content as given by the client.
2342 # SERVER_SOFTWARE - The name and version of the information server software
2343 # answering the request (and running the gateway).
2344 # Format: name/version
2345 # SERVER_NAME - The server's hostname, DNS alias, or IP address as it
2346 # would appear in self-referencing URLs
2347 # GATEWAY_INTERFACE - The revision of the CGI specification to which this
2348 # server complies. Format: CGI/revision
2349 # SERVER_PROTOCOL - The name and revision of the information protocol this
2350 # request came in with. Format: protocol/revision
2351 # SERVER_PORT - The port number to which the request was sent.
2352 # REQUEST_METHOD - The method with which the request was made. For HTTP,
2353 # this is "GET", "HEAD", "POST", etc.
2354 # SCRIPT_NAME - A virtual path to the script being executed, used for
2355 # self-referencing URLs.
2356 # HTTP_ACCEPT - The MIME types which the client will accept, as given by
2357 # HTTP headers. Other protocols may need to get this
2358 # information from elsewhere. Each item in this list should
2359 # be separated by commas as per the HTTP spec.
2360 # Format: type/subtype, type/subtype
2361 # HTTP_USER_AGENT - The browser the client is using to send the request.
2362 # General format: software/version library/version.
2365 # INSTRUCTIONS FOR RUNNING CGIscriptor ON UNIX
2367 # CGIscriptor.pl will run on any WWW server that runs Perl scripts, just add
2368 # a line like the following to your srm.conf file (Apache example):
2370 # ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
2372 # URL's that refer to http://www.your.address/SHTML/... will now be handled
2373 # by CGIscriptor.pl, which can use a private directory tree (default is the
2374 # DOCUMENT_ROOT directory tree, but it can be anywhere, see manual).
2376 # If your hosting ISP won't let you add ScriptAlias lines you can use
2377 # the following "rewrite"-based "scriptalias" in .htaccess
2378 # (from Gerd Franke)
2380 # RewriteEngine On
2381 # RewriteBase /
2382 # RewriteCond %{REQUEST_FILENAME} .html$
2383 # RewriteCond %{SCRIPT_FILENAME} !cgiscriptor.pl$
2384 # RewriteCond %{REQUEST_FILENAME} -f
2385 # RewriteRule ^(.*)$ /cgi-bin/cgiscriptor.pl/$1?&%{QUERY_STRING}
2387 # Everthing with the extension ".html" and not including "cgiscriptor.pl"
2388 # in the url and where the file "path/filename.html" exists is redirected
2389 # to "/cgi.bin/cgiscriptor.pl/path/filename.html?query".
2390 # The user configuration should get the same path-level as the
2391 # .htaccess-file:
2393 # # Just enter your own directory path here
2394 # $YOUR_HTML_FILES = "$ENV{'DOCUMENT_ROOT'}";
2395 # # use DOCUMENT_ROOT only, if .htaccess lies in the root-directory.
2397 # If this .htaccess goes in a specific directory, the path to this
2398 # directory must be added to $ENV{'DOCUMENT_ROOT'}.
2400 # The CGIscriptor file contains all documentation as comments. These
2401 # comments can be removed to speed up loading (e.g., `egrep -v '^#'
2402 # CGIscriptor.pl` > leanScriptor.pl). A bare bones version of
2403 # CGIscriptor.pl, lacking documentation, most comments, access control,
2404 # example functions etc. (but still with the copyright notice and some
2405 # minimal documentation) can be obtained by calling CGIscriptor.pl on the
2406 # command line with the '-slim' command line argument, e.g.,
2408 # >CGIscriptor.pl -slim > slimCGIscriptor.pl
2410 # CGIscriptor.pl can be run from the command line with <path> and <query> as
2411 # arguments, as `CGIscriptor.pl <path> <query>`, inside a perl script
2412 # with 'do CGIscriptor.pl' after setting $ENV{PATH_INFO}
2413 # and $ENV{QUERY_STRING}, or CGIscriptor.pl can be loaded with 'require
2414 # "/real-path/CGIscriptor.pl"'. In the latter case, requests are processed
2415 # by 'Handle_Request();' (again after setting $ENV{PATH_INFO} and
2416 # $ENV{QUERY_STRING}).
2418 # Using the command line execution option, CGIscriptor.pl can be used as a
2419 # document (meta-)preprocessor. If the first argument is '-', STDIN will be read.
2420 # For example:
2422 # > cat MyDynamicDocument.html | CGIscriptor.pl - '[QueryString]' > MyStaticFile.html
2424 # This command line will produce a STATIC file with the DYNAMIC content of
2425 # MyDocument.html "interpolated".
2427 # This option would be very dangerous when available over the internet.
2428 # If someone could sneak a 'http://www.your.domain/-' URL past your
2429 # server, CGIscriptor could EXECUTE any POSTED contend.
2430 # Therefore, for security reasons, STDIN will NOT be read
2431 # if ANY of the HTTP server environment variables is set (e.g.,
2432 # SERVER_PORT, SERVER_PROTOCOL, SERVER_NAME, SERVER_SOFTWARE,
2433 # HTTP_USER_AGENT, REMOTE_ADDR).
2434 # This block on processing STDIN on HTTP requests can be lifted by setting
2435 # $BLOCK_STDIN_HTTP_REQUEST = 0;
2436 # In the security configuration. Butbe carefull when doing this.
2437 # It can be very dangerous.
2439 # Running demo's and more information can be found at
2440 # http://www.fon.hum.uva.nl/~rob/OSS/OSS.html
2442 # A pocket-size HTTP daemon, CGIservlet.pl, is available from my web site or
2443 # CPAN that can use CGIscriptor.pl as the base of a µWWW server and
2444 # demonstrates its use.
2447 # PROCESSING NON-FILESYSTEM DATA
2449 # Normally, HTTP (WWW) requests map onto file that can be accessed
2450 # using the perl open() function. That is, the web server runs on top of
2451 # some directory structure. However, we can envission (and put to good
2452 # use) other systems that do not use a normal file system. The whole CGI
2453 # was developed to make dynamic document generation possible.
2455 # A special case is where we want to have it both: A normal web server
2456 # with normal "file data", but not a normal files system. For instance,
2457 # we want or normal Web Site to run directly from a RAM hash table or
2458 # other database, instead of from disk. But we do NOT want to code the
2459 # whole site structure in CGI.
2461 # CGIscriptor can do this. If the web server fills an environment variable
2462 # $ENV{'CGI_FILE_CONTENT'} with the content of the "file", then the content
2463 # of this variable is processed instead of opening a file. If this environment
2464 # variable has the value '-', the content of another environment variable,
2465 # $ENV{'CGI_DATA_ACCESS_CODE'} is executed as:
2466 # eval("\@_ = ($file_path); do {$ENV{'CGI_DATA_ACCESS_CODE'}};")
2467 # and the result is processed as if it was the content of the requested
2468 # file.
2469 # (actually, the names of the environment variables are user configurable,
2470 # they are stored in the local variables $CGI_FILE_CONTENT and
2471 # $CGI_DATA_ACCESS_CODE)
2473 # When using this mechanism, the SRC attribute mechanism will only partially work.
2474 # Only the "recursive" calls to CGIscriptor (the ProcessFile() function)
2475 # will work, the automagical execution of SRC files won't. (In this case,
2476 # the SRC attribute won't work either for other scripting languages)
2479 # NON-UNIX PLATFORMS
2481 # CGIscriptor.pl was mainly developed and tested on UNIX. However, as I
2482 # coded part of the time on an Apple Macintosh under MacPerl, I made sure
2483 # CGIscriptor did run under MacPerl (with command line options). But only
2484 # as an independend script, not as part of a HTTP server. I have used it
2485 # under Apache in Windows XP.
2487 ENDOFHELPTEXT
2488 exit;
2490 ###############################################################################
2492 # SECURITY CONFIGURATION
2494 # Special configurations related to SECURITY
2495 # (i.e., optional, see also environment variables below)
2497 # LOGGING
2498 # Log Clients and the requested paths (Redundant when loging Queries)
2500 $ClientLog = "./Client.log"; # (uncomment for use)
2502 # Format: Localtime | REMOTE_USER REMOTE_IDENT REMOTE_HOST REMOTE_ADDRESS \
2503 # PATH_INFO CONTENT_LENGTH (actually, the real query+post length)
2505 # Log Clients and the queries, the CGIQUERYDECODE is required if you want
2506 # to log queries. If you log Queries, the loging of Clients is redundant
2507 # (note that queries can be quite long, so this might not be a good idea)
2509 #$QueryLog = "./Query.log"; # (uncomment for use)
2511 # ACCESS CONTROL
2512 # the Access files should contain Hostnames or IP addresses,
2513 # i.e. REMOTE_HOST or REMOTE_ADDR, each on a separate line
2514 # optionally followed by one ore more file patterns, e.g., "edu /DEMO".
2515 # Matching is done "domain first". For example ".edu" matches all
2516 # clients whose "name" ends in ".edu" or ".EDU". The file pattern
2517 # "/DEMO" matches all paths that contain the strings "/DEMO" or "/demo"
2518 # (both matchings are done case-insensitive).
2519 # The name special symbol "-" matches ALL clients who do not supply a
2520 # REMOTE_HOST name, "*" matches all clients.
2521 # Lines starting with '-e' are evaluated. A non-zero return value indicates
2522 # a match. You can use $REMOTE_HOST, $REMOTE_ADDR, and $PATH_INFO. These
2523 # lines are evaluated in the program's own name-space. So DO NOT assign to
2524 # variables.
2526 # Accept the following users (remove comment # and adapt filename)
2527 $CGI_Accept = -s "$YOUR_SCRIPTS/ACCEPT.lis" ? "$YOUR_SCRIPTS/ACCEPT.lis" : ''; # (uncomment for use)
2529 # Reject requests from the following users (remove comment # and
2530 # adapt filename, this is only of limited use)
2531 $CGI_Reject = -s "$YOUR_SCRIPTS/REJECT.lis" ? "$YOUR_SCRIPTS/REJECT.lis" : ''; # (uncomment for use)
2533 # Empty lines or comment lines starting with '#' are ignored in both
2534 # $CGI_Accept and $CGI_Reject.
2536 # Block STDIN (i.e., '-') requests when servicing an HTTP request
2537 # Comment this out if you realy want to use STDIN in an on-line web server
2538 $BLOCK_STDIN_HTTP_REQUEST = 1;
2541 # End of security configuration
2543 ##################################################<<<<<<<<<<End Remove
2545 # PARSING CGI VALUES FROM THE QUERY STRING (USER CONFIGURABLE)
2547 # The CGI parse commands. These commands extract the values of the
2548 # CGI variables from the URL encoded Query String.
2549 # If you want to use your own CGI decoders, you can call them here
2550 # instead, using your own PATH and commenting/uncommenting the
2551 # appropriate lines
2553 # CGI parse command for individual values
2554 # (if $List > 0, returns a list value, if $List < 0, a hash table, this is optional)
2555 sub YOUR_CGIPARSE # ($Name [, $List]) -> Decoded value
2557 my $Name = shift;
2558 my $List = shift || 0;
2559 # Use one of the following by uncommenting
2560 if(!$List) # Simple value
2562 return CGIscriptor::CGIparseValue($Name) ;
2564 elsif($List < 0) # Hash tables
2566 return CGIscriptor::CGIparseValueHash($Name); # Defined in CGIscriptor below
2568 else # Lists
2570 return CGIscriptor::CGIparseValueList($Name); # Defined in CGIscriptor below
2573 # return `/PATH/cgiparse -value $Name`; # Shell commands
2574 # require "/PATH/cgiparse.pl"; return cgivalue($Name); # Library
2576 # Complete queries
2577 sub YOUR_CGIQUERYDECODE
2579 # Use one of the following by uncommenting
2580 return CGIscriptor::CGIparseForm(); # Defined in CGIscriptor below
2581 # return `/PATH/cgiparse -form`; # Shell commands
2582 # require "/PATH/cgiparse.pl"; return cgiform(); # Library
2585 # End of configuration
2587 #######################################################################
2589 # Translating input files.
2590 # Allows general and global conversions of files using Regular Expressions
2591 # Translations are applied in the order of definition.
2593 # Define:
2594 # my $TranslationPaths = 'pattern'; # Pattern matching PATH_INFO
2596 # push(@TranslationTable, ['pattern', 'replacement']);
2597 # e.g. (for Ruby Rails):
2598 # push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2599 # push(@TranslationTable, ['%>', '</SCRIPT>']);
2601 # Runs:
2602 # my $currentRegExp;
2603 # foreach $currentRegExp (keys(%TranslationTable))
2605 # my $currentRegExp;
2606 # foreach $currentRegExp (@TranslationTable)
2608 # my ($pattern, $replacement) = @$currentRegExp;
2609 # $$text =~ s!$pattern!$replacement!msg;
2610 # };
2611 # };
2613 # Configuration section
2615 #######################################################################
2617 # The file paths on which to apply the translation
2618 my $TranslationPaths = ''; # NO files
2619 #$TranslationPaths = '.'; # ANY file
2620 # $TranslationPaths = '\.html'; # HTML files
2622 my @TranslationTable = ();
2623 # Some legacy code
2624 push(@TranslationTable, ['\<\s*CGI\s+([^\>])*\>', '\<SCRIPT TYPE=\"text/ssperl\"\>$1\<\/SCRIPT>']);
2625 # Ruby Rails?
2626 push(@TranslationTable, ['<%=', '<SCRIPT TYPE="text/ssruby">']);
2627 push(@TranslationTable, ['%>', '</SCRIPT>']);
2629 sub performTranslation # (\$text)
2631 my $text = shift || return;
2632 if(@TranslationTable && $TranslationPaths && $ENV{'PATH_INFO'} =~ m!$TranslationPaths!)
2634 my $currentRegExp;
2635 foreach $currentRegExp (@TranslationTable)
2637 my ($pattern, $replacement) = @$currentRegExp;
2638 $$text =~ s!$pattern!$replacement!msg;
2643 #######################################################################
2645 # Seamless access to other (Scripting) Languages
2646 # TYPE='text/ss<interpreter>'
2648 # Configuration section
2650 #######################################################################
2652 # OTHER SCRIPTING LANGUAGES AT THE SERVER SIDE (MIME => OScommand)
2653 # Yes, it realy is this simple! (unbelievable, isn't it)
2654 # NOTE: Some interpreters require some filtering to obtain "clean" output
2656 %ScriptingLanguages = (
2657 "text/testperl" => 'perl', # Perl for testing
2658 "text/sspython" => 'python', # Python
2659 "text/ssruby" => 'ruby', # Ruby
2660 "text/sstcl" => 'tcl', # TCL
2661 "text/ssawk" => 'awk -f-', # Awk
2662 "text/sslisp" => # lisp (rep, GNU)
2663 'rep | tail +4 '."| egrep -v '> |^rep. |^nil\\\$'",
2664 "text/xlispstat" => # xlispstat
2665 'xlispstat | tail +7 ' ."| egrep -v '> \\\$|^NIL'",
2666 "text/ssprolog" => # Prolog (GNU)
2667 "gprolog | tail +4 | sed 's/^| ?- //'",
2668 "text/ssm4" => 'm4', # M4 macro's
2669 "text/sh" => 'sh', # Born shell
2670 "text/bash" => 'bash', # Born again shell
2671 "text/csh" => 'csh', # C shell
2672 "text/ksh" => 'ksh', # Korn shell
2673 "text/sspraat" => # Praat (sound/speech analysis)
2674 "praat - | sed 's/Praat > //g'",
2675 "text/ssr" => # R
2676 "R --vanilla --slave | sed 's/^[\[0-9\]*] //'",
2677 "text/ssrebol" => # REBOL
2678 "rebol --quiet|egrep -v '^[> ]* == '|sed 's/^\\s*\[> \]* //'",
2679 "text/postgresql" => 'psql 2>/dev/null',
2681 # Not real scripting, but the use of other applications
2682 "text/ssmailto" => "awk 'NF||F{F=1;print \\\$0;}'|mailto >/dev/null", # Send mail from server
2683 "text/ssdisplay" => 'cat', # Display, (interpolation)
2684 "text/sslogfile" => # Log to file, (interpolation)
2685 "awk 'NF||L {if(!L){L=tolower(\\\$1)~/^file:\\\$/ ? \\\$2 : \\\$1;}else{print \\\$0 >> L;};}'",
2687 "" => ""
2690 # To be able to access the CGI variables in your script, they
2691 # should be passed to the scripting language in a readable form
2692 # Here you can enter how they should be printed (the first %s
2693 # is replaced by the NAME of the CGI variable as it apears in the
2694 # META tag, the second by its VALUE).
2695 # For Perl this would be:
2696 # "text/testperl" => '$%s = "%s";',
2697 # which would be executed as
2698 # printf('$%s = "%s";', $CGI_NAME, $CGI_VALUE);
2700 # If the hash table value doesn't exist, nothing is done
2701 # (you have to parse the Environment variables yourself).
2702 # If it DOES exist but is empty (e.g., "text/sspraat" => '',)
2703 # Perl string interpolation of variables (i.e., $var, @array,
2704 # %hash) is performed. This means that $@%\ must be protected
2705 # with a \.
2707 %ScriptingCGIvariables = (
2708 "text/testperl" => "\$\%s = '\%s';", # Perl $VAR = 'value'; (for testing)
2709 "text/sspython" => "\%s = '\%s'", # Python VAR = 'value'
2710 "text/ssruby" => '@%s = "%s"', # Ruby @VAR = 'value'
2711 "text/sstcl" => 'set %s "%s"', # TCL set VAR "value"
2712 "text/ssawk" => '%s = "%s";', # Awk VAR = 'value';
2713 "text/sslisp" => '(setq %s "%s")', # Gnu lisp (rep) (setq VAR "value")
2714 "text/xlispstat" => '(setq %s "%s")', # xlispstat (setq VAR "value")
2715 "text/ssprolog" => '', # Gnu prolog (interpolated)
2716 "text/ssm4" => "define(`\%s', `\%s')", # M4 macro's define(`VAR', `value')
2717 "text/sh" => "\%s='\%s'", # Born shell VAR='value'
2718 "text/bash" => "\%s='\%s'", # Born again shell VAR='value'
2719 "text/csh" => "\$\%s='\%s';", # C shell $VAR = 'value';
2720 "text/ksh" => "\$\%s='\%s';", # Korn shell $VAR = 'value';
2722 "text/ssrebol" => '%s: copy "%s"', # REBOL VAR: copy "value"
2723 "text/sspraat" => '', # Praat (interpolation)
2724 "text/ssr" => '%s <- "%s";', # R VAR <- "value";
2725 "text/postgresql" => '', # PostgreSQL (interpolation)
2727 # Not real scripting, but the use of other applications
2728 "text/ssmailto" => '', # MAILTO, (interpolation)
2729 "text/ssdisplay" => '', # Display, (interpolation)
2730 "text/sslogfile" => '', # Log to file, (interpolation)
2732 "" => ""
2735 # If you want something added in front or at the back of each script
2736 # block as send to the interpreter add it here.
2737 # mime => "string", e.g., "text/sspython" => "python commands"
2738 %ScriptingPrefix = (
2739 "text/testperl" => "\# Prefix Code;", # Perl script testing
2740 "text/ssm4" => 'divert(0)', # M4 macro's (open STDOUT)
2742 "" => ""
2744 # If you want something added at the end of each script block
2745 %ScriptingPostfix = (
2746 "text/testperl" => "\# Postfix Code;", # Perl script testing
2747 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2749 "" => ""
2751 # If you need initialization code, directly after opening
2752 %ScriptingInitialization = (
2753 "text/testperl" => "\# Initialization Code;", # Perl script testing
2754 "text/ssawk" => 'BEGIN {', # Server Side awk scripts (VAR = "value")
2755 "text/sslisp" => '(prog1 nil ', # Lisp (rep)
2756 "text/xlispstat" => '(prog1 nil ', # xlispstat
2757 "text/ssm4" => 'divert(-1)', # M4 macro's (block STDOUT)
2759 "" => ""
2761 # If you need cleanup code before closing
2762 %ScriptingCleanup = (
2763 "text/testperl" => "\# Cleanup Code;", # Perl script testing
2764 "text/sspraat" => 'Quit',
2765 "text/ssawk" => '};', # Server Side awk scripts (VAR = "value")
2766 "text/sslisp" => '(princ "\n" standard-output)).', # Closing print to rep
2767 "text/xlispstat" => '(print ""))', # Closing print to xlispstat
2768 "text/postgresql" => '\q', # quit psql
2769 "text/ssdisplay" => "", # close cat
2771 "" => ""
2774 # End of configuration for foreign scripting languages
2776 ###############################################################################
2778 # Initialization Code
2781 sub Initialize_Request
2783 ###############################################################################
2785 # ENVIRONMENT VARIABLES
2787 # Use environment variables to configure CGIscriptor on a temporary basis.
2788 # If you define any of the configurable variables as environment variables,
2789 # these are used instead of the "hard coded" values above.
2791 $SS_PUB = $ENV{'SS_PUB'} || $YOUR_HTML_FILES;
2792 $SS_SCRIPT = $ENV{'SS_SCRIPT'} || $YOUR_SCRIPTS;
2795 # Substitution strings, these are used internally to handle the
2796 # directory separator strings, e.g., '~/' -> 'SS_PUB:' (Mac)
2797 $HOME_SUB = $SS_PUB;
2798 $SCRIPT_SUB = $SS_SCRIPT;
2801 # Make sure all script are reliably loaded
2802 push(@INC, $SS_SCRIPT);
2805 # Add the directory separator to the "home" directories.
2806 # (This is required for ~/ and ./ substitution)
2807 $HOME_SUB .= '/' if $HOME_SUB;
2808 $SCRIPT_SUB .= '/' if $SCRIPT_SUB;
2810 $CGI_HOME = $ENV{'DOCUMENT_ROOT'};
2811 $ENV{'PATH_TRANSLATED'} =~ /$ENV{'PATH_INFO'}/is;
2812 $CGI_HOME = $` unless $ENV{'DOCUMENT_ROOT'}; # Get the DOCUMENT_ROOT directory
2813 $default_values{'CGI_HOME'} = $CGI_HOME;
2814 $ENV{'HOME'} = $CGI_HOME;
2815 # Set SS_PUB and SS_SCRIPT as Environment variables (make them available
2816 # to the scripts)
2817 $ENV{'SS_PUB'} = $SS_PUB unless $ENV{'SS_PUB'};
2818 $ENV{'SS_SCRIPT'} = $SS_SCRIPT unless $ENV{'SS_SCRIPT'};
2820 $FilePattern = $ENV{'FilePattern'} || $FilePattern;
2821 $MaximumQuerySize = $ENV{'MaximumQuerySize'} || $MaximumQuerySize;
2822 $ClientLog = $ENV{'ClientLog'} || $ClientLog;
2823 $QueryLog = $ENV{'QueryLog'} || $QueryLog;
2824 $CGI_Accept = $ENV{'CGI_Accept'} || $CGI_Accept;
2825 $CGI_Reject = $ENV{'CGI_Reject'} || $CGI_Reject;
2827 # Parse file names
2828 $CGI_Accept =~ s@^\~/@$HOME_SUB@g if $CGI_Accept;
2829 $CGI_Reject =~ s@^\~/@$HOME_SUB@g if $CGI_Reject;
2830 $ClientLog =~ s@^\~/@$HOME_SUB@g if $ClientLog;
2831 $QueryLog =~ s@^\~/@$HOME_SUB@g if $QueryLog;
2833 $CGI_Accept =~ s@^\./@$SCRIPT_SUB@g if $CGI_Accept;
2834 $CGI_Reject =~ s@^\./@$SCRIPT_SUB@g if $CGI_Reject;
2835 $ClientLog =~ s@^\./@$SCRIPT_SUB@g if $ClientLog;
2836 $QueryLog =~ s@^\./@$SCRIPT_SUB@g if $QueryLog;
2838 @CGIscriptorResults = (); # A stack of results
2840 # end of Environment variables
2842 #############################################################################
2844 # Define and Store "standard" values
2846 # BEFORE doing ANYTHING check the size of Query String
2847 length($ENV{'QUERY_STRING'}) <= $MaximumQuerySize || dieHandler(2, "QUERY TOO LONG\n");
2849 # The Translated Query String and the Actual length of the (decoded)
2850 # Query String
2851 if($ENV{'QUERY_STRING'})
2853 # If this can contain '`"-quotes, be carefull to use it QUOTED
2854 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
2855 $default_values{CGI_Content_Length} = length($default_values{CGI_Decoded_QS});
2858 # Get the current Date and time and store them as default variables
2860 # Get Local Time
2861 $LocalTime = localtime;
2863 # CGI_Year CGI_Month CGI_Day CGI_WeekDay CGI_Time
2864 # CGI_Hour CGI_Minutes CGI_Seconds
2866 $default_values{CGI_Date} = $LocalTime;
2867 ($default_values{CGI_WeekDay},
2868 $default_values{CGI_Month},
2869 $default_values{CGI_Day},
2870 $default_values{CGI_Time},
2871 $default_values{CGI_Year}) = split(' ', $LocalTime);
2872 ($default_values{CGI_Hour},
2873 $default_values{CGI_Minutes},
2874 $default_values{CGI_Seconds}) = split(':', $default_values{CGI_Time});
2876 # GMT:
2877 # CGI_GMTYear CGI_GMTMonth CGI_GMTDay CGI_GMTWeekDay CGI_GMTYearDay
2878 # CGI_GMTHour CGI_GMTMinutes CGI_GMTSeconds CGI_GMTisdst
2880 ($default_values{CGI_GMTSeconds},
2881 $default_values{CGI_GMTMinutes},
2882 $default_values{CGI_GMTHour},
2883 $default_values{CGI_GMTDay},
2884 $default_values{CGI_GMTMonth},
2885 $default_values{CGI_GMTYear},
2886 $default_values{CGI_GMTWeekDay},
2887 $default_values{CGI_GMTYearDay},
2888 $default_values{CGI_GMTisdst}) = gmtime;
2892 # End of Initialize Request
2894 ###################################################################
2896 # SECURITY: ACCESS CONTROL
2898 # Check the credentials of each client (use pattern matching, domain first).
2899 # This subroutine will kill-off (die) the current process whenever access
2900 # is denied.
2902 sub Access_Control
2904 # >>>>>>>>>>Start Remove
2906 # ACCEPTED CLIENTS
2908 # Only accept clients which are authorized, reject all unnamed clients
2909 # if REMOTE_HOST is given.
2910 # If file patterns are given, check whether the user is authorized for
2911 # THIS file.
2912 if($CGI_Accept)
2914 # Use local variables, REMOTE_HOST becomes '-' if undefined
2915 my $REMOTE_HOST = $ENV{REMOTE_HOST} || '-';
2916 my $REMOTE_ADDR = $ENV{REMOTE_ADDR};
2917 my $PATH_INFO = $ENV{'PATH_INFO'};
2919 open(CGI_Accept, "<$CGI_Accept") || dieHandler(3, "$CGI_Accept: $!\n");
2920 $NoAccess = 1;
2921 while(<CGI_Accept>)
2923 next unless /\S/; # Skip empty lines
2924 next if /^\s*\#/; # Skip comments
2926 # Full expressions
2927 if(/^\s*-e\s/is)
2929 my $Accept = $'; # Get the expression
2930 $NoAccess &&= eval($Accept); # evaluate the expresion
2932 else
2934 my ($Accept, @FilePatternList) = split;
2935 if($Accept eq '*' # Always match
2936 ||$REMOTE_HOST =~ /\Q$Accept\E$/is # REMOTE_HOST matches
2937 || (
2938 $Accept =~ /^[0-9\.]+$/
2939 && $REMOTE_ADDR =~ /^\Q$Accept\E/ # IP address matches
2943 if($FilePatternList[0])
2945 foreach $Pattern (@FilePatternList)
2947 # Check whether this patterns is accepted
2948 $NoAccess &&= ($PATH_INFO !~ m@\Q$Pattern\E@is);
2951 else
2953 $NoAccess = 0; # No file patterns -> Accepted
2957 # Blocked
2958 last unless $NoAccess;
2960 close(CGI_Accept);
2961 if($NoAccess){ dieHandler(4, "No Access: $PATH_INFO\n");};
2965 # REJECTED CLIENTS
2967 # Reject named clients, accept all unnamed clients
2968 if($CGI_Reject)
2970 # Use local variables, REMOTE_HOST becomes '-' if undefined
2971 my $REMOTE_HOST = $ENV{'REMOTE_HOST'} || '-';
2972 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
2973 my $PATH_INFO = $ENV{'PATH_INFO'};
2975 open(CGI_Reject, "<$CGI_Reject") || dieHandler(5, "$CGI_Reject: $!\n");
2976 $NoAccess = 0;
2977 while(<CGI_Reject>)
2979 next unless /\S/; # Skip empty lines
2980 next if /^\s*\#/; # Skip comments
2982 # Full expressions
2983 if(/^-e\s/is)
2985 my $Reject = $'; # Get the expression
2986 $NoAccess ||= eval($Reject); # evaluate the expresion
2988 else
2990 my ($Reject, @FilePatternList) = split;
2991 if($Reject eq '*' # Always match
2992 ||$REMOTE_HOST =~ /\Q$Reject\E$/is # REMOTE_HOST matches
2993 ||($Reject =~ /^[0-9\.]+$/
2994 && $REMOTE_ADDR =~ /^\Q$Reject\E/is # IP address matches
2998 if($FilePatternList[0])
3000 foreach $Pattern (@FilePatternList)
3002 $NoAccess ||= ($PATH_INFO =~ m@\Q$Pattern\E@is);
3005 else
3007 $NoAccess = 1; # No file patterns -> Rejected
3011 last if $NoAccess;
3013 close(CGI_Reject);
3014 if($NoAccess){ dieHandler(6, "Request rejected: $PATH_INFO\n");};
3017 ##########################################################<<<<<<<<<<End Remove
3020 # Get the filename
3022 # Does the filename contain any illegal characters (e.g., |, >, or <)
3023 dieHandler(7, "Illegal request: $ENV{'PATH_INFO'}\n") if $ENV{'PATH_INFO'} =~ /[^$FileAllowedChars]/;
3024 # Does the pathname contain an illegal (blocked) "directory"
3025 dieHandler(8, "Illegal request: $ENV{'PATH_INFO'}\n") if $BlockPathAccess && $ENV{'PATH_INFO'} =~ m@$BlockPathAccess@; # Access is blocked
3026 # Does the pathname contain a direct referencer to BinaryMapFile
3027 dieHandler(9, "Illegal request: $ENV{'PATH_INFO'}\n") if $BinaryMapFile && $ENV{'PATH_INFO'} =~ m@\Q$BinaryMapFile\E@; # Access is blocked
3029 # SECURITY: Is PATH_INFO allowed?
3030 if($FilePattern && $ENV{'PATH_INFO'} && $ENV{'PATH_INFO'} ne '-' &&
3031 ($ENV{'PATH_INFO'} !~ m@($FilePattern)$@is))
3033 # Unsupported file types can be processed by a special raw-file
3034 if($BinaryMapFile)
3036 $ENV{'CGI_BINARY_FILE'} = $ENV{'PATH_INFO'};
3037 $ENV{'PATH_INFO'} = $BinaryMapFile;
3039 else
3041 dieHandler(10, "Illegal file\n");
3047 # End of Security Access Control
3050 ############################################################################
3052 # Get the POST part of the query and add it to the QUERY_STRING.
3055 sub Get_POST_part_of_query
3058 # If POST, Read data from stdin to QUERY_STRING
3059 if($ENV{'REQUEST_METHOD'} =~ /POST/is)
3061 # SECURITY: Check size of Query String
3062 $ENV{'CONTENT_LENGTH'} <= $MaximumQuerySize || dieHandler(11, "Query too long: $ENV{'CONTENT_LENGTH'}\n"); # Query too long
3063 my $QueryRead = 0;
3064 my $SystemRead = $ENV{'CONTENT_LENGTH'};
3065 $ENV{'QUERY_STRING'} .= '&' if length($ENV{'QUERY_STRING'}) > 0;
3066 while($SystemRead > 0)
3068 $QueryRead = sysread(STDIN, $Post, $SystemRead); # Limit length
3069 $ENV{'QUERY_STRING'} .= $Post;
3070 $SystemRead -= $QueryRead;
3072 # Update decoded Query String
3073 $default_values{CGI_Decoded_QS} = YOUR_CGIQUERYDECODE();
3074 $default_values{CGI_Content_Length} =
3075 length($default_values{CGI_Decoded_QS});
3079 # End of getting POST part of query
3082 ############################################################################
3084 # Start (HTML) output and logging
3085 # (if there are irregularities, it can kill the current process)
3088 sub Initialize_output
3090 # Construct the REAL file path (except for STDIN on the command line)
3091 my $file_path = $ENV{'PATH_INFO'} ne '-' ? $SS_PUB . $ENV{'PATH_INFO'} : '-';
3092 $file_path =~ s/\?.*$//; # Remove query
3093 # This is only necessary if your server does not catch ../ directives
3094 $file_path !~ m@\.\./@ || dieHandler(12, "Illegal ../ Construct\n"); # SECURITY: Do not allow ../ constructs
3096 # Block STDIN use (-) if CGIscriptor is servicing a HTTP request
3097 if($file_path eq '-')
3099 dieHandler(13, "STDIN request in On Line system\n") if $BLOCK_STDIN_HTTP_REQUEST
3100 && ($ENV{'SERVER_SOFTWARE'}
3101 || $ENV{'SERVER_NAME'}
3102 || $ENV{'GATEWAY_INTERFACE'}
3103 || $ENV{'SERVER_PROTOCOL'}
3104 || $ENV{'SERVER_PORT'}
3105 || $ENV{'REMOTE_ADDR'}
3106 || $ENV{'HTTP_USER_AGENT'});
3111 if($ClientLog)
3113 open(ClientLog, ">>$ClientLog");
3114 print ClientLog "$LocalTime | ",
3115 ($ENV{REMOTE_USER} || "-"), " ",
3116 ($ENV{REMOTE_IDENT} || "-"), " ",
3117 ($ENV{REMOTE_HOST} || "-"), " ",
3118 $ENV{REMOTE_ADDR}, " ",
3119 $ENV{PATH_INFO}, " ",
3120 $ENV{'CGI_BINARY_FILE'}, " ",
3121 ($default_values{CGI_Content_Length} || "-"),
3122 "\n";
3123 close(ClientLog);
3125 if($QueryLog)
3127 open(QueryLog, ">>$QueryLog");
3128 print QueryLog "$LocalTime\n",
3129 ($ENV{REMOTE_USER} || "-"), " ",
3130 ($ENV{REMOTE_IDENT} || "-"), " ",
3131 ($ENV{REMOTE_HOST} || "-"), " ",
3132 $ENV{REMOTE_ADDR}, ": ",
3133 $ENV{PATH_INFO}, " ",
3134 $ENV{'CGI_BINARY_FILE'}, "\n";
3136 # Write Query to Log file
3137 print QueryLog $default_values{CGI_Decoded_QS}, "\n\n";
3138 close(QueryLog);
3141 # Return the file path
3142 return $file_path;
3145 # End of Initialize output
3148 ############################################################################
3150 # Handle login access
3152 # Access is based on a valid session ticket.
3153 # Session tickets should be dependend on user name
3154 # and IP address. The patterns of URLs for which a
3155 # session ticket is needed and the login URL are stored in
3156 # %TicketRequiredPatterns as:
3157 # 'RegEx pattern' -> 'SessionPath\tPasswordPath\tLogin URL\tExpiration'
3160 sub Log_In_Access # () -> 0 = Access Allowed, Login page if access is not allowed
3162 # No patterns, no login
3163 goto Return unless %TicketRequiredPatterns;
3165 # Get and initialize values (watch out for stuff processed by BinaryMap files)
3166 my ($SessionPath, $PasswordsPath, $Login, $valid_duration) = ("", "", "", 0);
3167 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3168 my $REMOTE_ADDR = $ENV{'REMOTE_ADDR'};
3169 goto Return if $REMOTE_ADDR =~ /[^0-9\.]/;
3170 # Extract TICKETs, starting with returned cookies
3171 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3172 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3173 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3174 Get_All_Cookies();
3175 if(length(keys(%CGI_Cookies)) > 0)
3177 ${"CGIexecute::LOGINTICKET"} = $CGI_Cookies{'CGIscriptorLOGIN'}
3178 if $CGI_Cookies{'CGIscriptorLOGIN'} && $CGI_Cookies{'CGIscriptorLOGIN'} ne "-";
3179 $CGI_Cookies{'CGIscriptorLOGIN'} = "-";
3180 ${"CGIexecute::CHALLENGETICKET"} = $CGI_Cookies{'CGIscriptorCHALLENGE'}
3181 if $CGI_Cookies{'CGIscriptorCHALLENGE'} && $CGI_Cookies{'CGIscriptorCHALLENGE'} ne "-";
3182 $CGI_Cookies{'CGIscriptorCHALLENGE'} = "-";
3183 ${"CGIexecute::SESSIONTICKET"} = $CGI_Cookies{'CGIscriptorSESSION'}
3184 if $CGI_Cookies{'CGIscriptorSESSION'} && $CGI_Cookies{'CGIscriptorSESSION'} ne "-";
3185 $CGI_Cookies{'CGIscriptorSESSION'} = "-";
3187 # Get and check the tickets. Tickets are restricted to word-characters (alphanumeric+_+.)
3188 my $LOGINTICKET = ${"CGIexecute::LOGINTICKET"};
3189 goto Return if ($LOGINTICKET && $LOGINTICKET =~ /[^\w\.]/isg);
3190 my $SESSIONTICKET = ${"CGIexecute::SESSIONTICKET"};
3191 goto Return if ($SESSIONTICKET && $SESSIONTICKET =~ /[^\w\.]/isg);
3192 my $CHALLENGETICKET = ${"CGIexecute::CHALLENGETICKET"};
3193 goto Return if ($CHALLENGETICKET && $CHALLENGETICKET =~ /[^\w\.]/isg);
3194 # Look for a LOGOUT message
3195 my $LOGOUT = $ENV{QUERY_STRING} =~ /(^|\&)LOGOUT([\=\&]|$)/;
3196 # Username and password
3197 CGIexecute::defineCGIvariable('CGIUSERNAME', "");
3198 my $username = lc(${"CGIexecute::CGIUSERNAME"});
3199 goto Return if $username =~ m!^[^\w]!isg || $username =~ m![^\w \-]!isg;
3200 my $userfile = lc($username);
3201 $userfile =~ s/[^\w]/_/isg;
3202 CGIexecute::defineCGIvariable('PASSWORD', "");
3203 my $password = ${"CGIexecute::PASSWORD"};
3204 CGIexecute::defineCGIvariable('NEWUSERNAME', "");
3205 my $newuser = lc(${"CGIexecute::NEWUSERNAME"});
3206 CGIexecute::defineCGIvariable('NEWPASSWORD', "");
3207 my $newpassword = ${"CGIexecute::NEWPASSWORD"};
3209 foreach my $pattern (keys(%TicketRequiredPatterns))
3211 # Check BOTH the real PATH_INFO and the CGI_BINARY_FILE variable
3212 if($ENV{'PATH_INFO'} =~ m#$pattern# || $ENV{'CGI_BINARY_FILE'} =~ m#$pattern#)
3214 # Fall through a sieve of requirements
3215 ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3216 # If a LOGOUT is present, remove everything
3217 if($LOGOUT && !$LOGINTICKET)
3219 unlink "$SessionPath/$LOGINTICKET" if $LOGINTICKET && (-s "$SessionPath/$LOGINTICKET");
3220 $LOGINTICKET = "";
3221 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3222 $SESSIONTICKET = "";
3223 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3224 $CHALLENGETICKET = "";
3225 unlink "$SessionPath/$REMOTE_ADDR" if (-s "$SessionPath/$REMOTE_ADDR");
3226 $CHALLENGETICKET = "";
3227 goto Login;
3229 # Is there a change password request?
3230 if($newuser && $LOGINTICKET && $username)
3232 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3233 goto Login unless (-s "$PasswordsPath/$userfile");
3234 my $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3235 goto Login unless $ticket_valid;
3236 $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3237 goto Login unless $ticket_valid;
3239 my ($sessiontype, $currentticket) = ("", "");
3240 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE", $CHALLENGETICKET);}
3241 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION", $SESSIONTICKET);}
3242 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS", $REMOTE_ADDR);
3244 if($sessiontype)
3246 goto Login unless (-s "$SessionPath/$currentticket");
3247 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3248 goto Login unless $ticket_valid;
3250 # Authorize
3251 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
3252 goto Login unless $TMPTICKET;
3254 # Create a new user account
3255 CGIexecute::defineCGIvariable('NEWSESSION', "");
3256 my $newsession = ${"CGIexecute::NEWSESSION"};
3257 my $newaccount = create_newuser("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket",
3258 "$PasswordsPath/$userfile", $password, $newuser, $newpassword, $newsession);
3259 CGIexecute::defineCGIvariable('NEWACCOUNTTEXT', $newaccount);
3260 ${CGIexecute::NEWACCOUNTTEXT} = $newaccount;
3261 # NEWACCOUNTTEXT is NOT to be set by the query
3262 CGIexecute::ProtectCGIvariable('NEWACCOUNTTEXT');
3265 # Ready
3266 goto Return;
3268 # Is there a change password request?
3269 elsif($newpassword && $LOGINTICKET && $username)
3271 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3272 goto Login unless (-s "$PasswordsPath/$userfile");
3273 my $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3274 goto Login unless $ticket_valid;
3275 $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".", 1);
3276 goto Login unless $ticket_valid;
3278 my ($sessiontype, $currentticket) = ("", "");
3279 if($CHALLENGETICKET) {($sessiontype, $currentticket) = ("CHALLENGE", $CHALLENGETICKET);}
3280 elsif($SESSIONTICKET) {($sessiontype, $currentticket) = ("SESSION", $SESSIONTICKET);}
3281 elsif(-s "$SessionPath/$REMOTE_ADDR") {($sessiontype, $currentticket) = ("IPADDRESS", $REMOTE_ADDR);
3283 if($sessiontype)
3285 goto Login unless (-s "$SessionPath/$currentticket");
3286 my $ticket_valid = check_ticket_validity($sessiontype, "$SessionPath/$currentticket", $REMOTE_ADDR, $PATH_INFO);
3287 goto Login unless $ticket_valid;
3289 # Authorize
3290 change_password("$SessionPath/$LOGINTICKET", "$SessionPath/$currentticket", "$PasswordsPath/$userfile", $password, $newpassword);
3291 # After a change of password, you have to login again for a CHALLENGE
3292 if($CHALLENGETICKET){$CHALLENGETICKET = "";};
3293 # Ready
3294 goto Return;
3296 # Is there a login ticket of this name?
3297 elsif($LOGINTICKET)
3299 my $tickets_removed = remove_expired_tickets($SessionPath);
3300 goto Login unless (-s "$SessionPath/$LOGINTICKET");
3301 goto Login unless (-s "$PasswordsPath/$userfile");
3302 my $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3303 goto Login unless $ticket_valid;
3304 $ticket_valid = check_ticket_validity("LOGIN", "$SessionPath/$LOGINTICKET", $REMOTE_ADDR, ".");
3305 goto Login unless $ticket_valid;
3307 # Remove any lingering tickets
3308 unlink "$SessionPath/$SESSIONTICKET" if $SESSIONTICKET && (-s "$SessionPath/$SESSIONTICKET");
3309 $SESSIONTICKET = "";
3310 unlink "$SessionPath/$CHALLENGETICKET" if $CHALLENGETICKET && (-s "$SessionPath/$CHALLENGETICKET");
3311 $CHALLENGETICKET = "";
3314 # Authorize
3315 my $TMPTICKET = authorize_login("$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $password, $SessionPath);
3316 if($TMPTICKET)
3318 my $authorization = read_ticket("$PasswordsPath/$userfile");
3319 goto Login unless $authorization;
3320 # Session type is read from the userfile
3321 if($authorization->{"Session"} && $authorization->{"Session"}->[0] eq "CHALLENGE")
3323 # Create New Random CHALLENGETICKET
3324 $CHALLENGETICKET = $TMPTICKET;
3325 create_session_file("$SessionPath/$CHALLENGETICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3327 elsif($authorization->{"Session"} && $authorization->{"Session"}->[0] eq "IPADDRESS")
3329 create_session_file("$SessionPath/$REMOTE_ADDR", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3331 else
3333 # Extra hash to protect CHALLENGETICKET use
3334 $SESSIONTICKET = hash_string($TMPTICKET);
3335 $SESSIONTICKET = hash_string($SESSIONTICKET.$TMPTICKET);
3336 create_session_file("$SessionPath/$SESSIONTICKET", "$SessionPath/$LOGINTICKET", "$PasswordsPath/$userfile", $PATH_INFO);
3337 $SETCOOKIELIST{"CGIscriptorSESSION"} = "-";
3338 $TMPTICKET = $SESSIONTICKET;
3341 # Login ticket file has been used, remove it
3342 unlink($loginfile);
3344 # Is there a session ticket of this name?
3345 # CHALLENGE
3346 if($CHALLENGETICKET)
3348 # Do not log into a CHALLENGE account if the SESSION cookie is present
3349 # Uncomment when $SESSIONTICKET does not receive an extra hash
3350 #goto Login if $SESSIONTICKET =~ /\S/;
3351 goto Login unless (-s "$SessionPath/$CHALLENGETICKET");
3352 my $ticket_valid = check_ticket_validity("CHALLENGE", "$SessionPath/$CHALLENGETICKET", $REMOTE_ADDR, $PATH_INFO);
3353 goto Login unless $ticket_valid;
3355 my $oldchallenge = read_ticket("$SessionPath/$CHALLENGETICKET");
3356 goto Login unless $oldchallenge;
3357 # Check whether the login still exists
3358 my $userfile = lc($oldchallenge->{"Username"}->[0]);
3359 $userfile =~ s/[^\w]/_/isg;
3360 goto Login unless (-s "$PasswordsPath/$userfile");
3362 $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3363 goto Login unless $ticket_valid;
3365 my $NEWCHALLENGETICKET = "";
3366 $NEWCHALLENGETICKET = copy_challenge_file("$SessionPath/$CHALLENGETICKET", "$PasswordsPath/$userfile", $SessionPath);
3367 # Sessionticket is available to scripts, do NOT set the cookie
3368 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3369 goto Return;
3371 # IPADDRESS
3372 elsif(-s "$SessionPath/$REMOTE_ADDR")
3374 my $ticket_valid = check_ticket_validity("IPADDRESS", "$SessionPath/$REMOTE_ADDR", $REMOTE_ADDR, $PATH_INFO);
3375 goto Login unless $ticket_valid;
3376 # Check whether the login still exists
3377 my $currentsessionticket = read_ticket("$SessionPath/$REMOTE_ADDR");
3378 my $userfile = lc($currentsessionticket->{"Username"}->[0]);
3379 $userfile =~ s/[^\w]/_/isg;
3380 goto Login unless (-s "$PasswordsPath/$userfile");
3382 $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3383 goto Login unless $ticket_valid;
3385 goto Return;
3387 # SESSION
3388 elsif($SESSIONTICKET)
3390 goto Login unless (-s "$SessionPath/$SESSIONTICKET");
3391 my $ticket_valid = check_ticket_validity("SESSION", "$SessionPath/$SESSIONTICKET", $REMOTE_ADDR, $PATH_INFO);
3392 goto Login unless $ticket_valid;
3394 # Check whether the login still exists
3395 my $currentsessionticket = read_ticket("$SessionPath/$SESSIONTICKET");
3396 my $userfile = lc($currentsessionticket->{"Username"}->[0]);
3397 $userfile =~ s/[^\w]/_/isg;
3398 goto Login unless (-s "$PasswordsPath/$userfile");
3400 $ticket_valid = check_ticket_validity("PASSWORD", "$PasswordsPath/$userfile", $REMOTE_ADDR, $PATH_INFO);
3401 goto Login unless $ticket_valid;
3403 # Sessionticket is available to scripts
3404 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3405 goto Return;
3408 goto Login;
3409 goto Return;
3412 Return:
3413 # The Masterkey should NOT be accessible by the parsed files
3414 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3415 return 0;
3417 Login:
3418 create_login_file($PasswordsPath, $SessionPath, $REMOTE_ADDR);
3419 # Note, cookies are set only ONCE
3420 $SETCOOKIELIST{"CGIscriptorLOGIN"} = "-";
3421 # The Masterkey should NOT be accessible by the parsed files
3422 $ENV{'CGIMasterKey'} = "" if $ENV{'CGIMasterKey'};
3423 return "$YOUR_HTML_FILES/$Login";
3426 sub authorize_login # ($loginfile, $authorizationfile, $password, $SessionPath) => SESSIONTICKET First two arguments are file paths
3428 my $loginfile = shift || "";
3429 my $authorizationfile = shift || "";
3430 my $password = shift || "";
3431 my $SessionPath = shift || "";
3433 # Get Login session ticket
3434 my $loginticket = read_ticket($loginfile);
3435 return 0 unless $loginticket;
3436 # Get User credentials for authorization
3437 my $authorization = read_ticket($authorizationfile);
3438 return 0 unless $authorization;
3440 # Get Randomsalt
3441 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3442 return "" unless $Randomsalt;
3444 my $storedpassword = $authorization->{'Password'}->[0];
3445 return "" unless $storedpassword;
3446 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3447 return "" unless $password eq $Hashedpassword;
3449 # Extract Session Ticket
3450 my $loginsession = $loginticket->{'Session'}->[0];
3451 my $sessionticket = hash_string($storedpassword.$loginsession);
3452 chomp($sessionticket);
3453 $sessionticket = "" if -x "$SessionPath/$sessionticket";
3455 # No lingering password variables
3456 $Hashedpassword = $Randomsalt;
3457 $password = $Randomsalt;
3458 $authorization->{'Password'}->[0] = $Randomsalt;
3460 return $sessionticket;
3463 sub change_password # ($loginfile, $sessionfile, $authorizationfile, $password, $newpassword) First three arguments are file paths
3465 my $loginfile = shift || "";
3466 my $sessionfile = shift || "";
3467 my $authorizationfile = shift || "";
3468 my $password = shift || "";
3469 my $newpassword = shift || "";
3470 # Get Login session ticket
3471 my $loginticket = read_ticket($loginfile);
3472 return "" unless $loginticket;
3473 # Login ticket file has been used, remove it
3474 unlink($loginfile);
3475 # Get Randomsalt
3476 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3477 return "" unless $Randomsalt;
3478 my $LoginID = $loginticket->{'Session'}->[0];
3479 return "" unless $LoginID;
3481 # Get session ticket
3482 my $sessionticket = read_ticket($sessionfile);
3483 return "" unless $sessionticket;
3485 # Get User credentials for authorization
3486 my $authorization = read_ticket($authorizationfile);
3487 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3489 my $storedpassword = $authorization->{'Password'}->[0];
3490 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3491 return "" unless $password eq $Hashedpassword;
3492 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3494 # Decrypt the $newpassword
3495 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3496 return "" unless $decryptedPassword;
3497 # Authorization succeeded, change password
3498 $authorization->{'Password'}->[0] = $decryptedPassword;
3499 # Write out
3500 write_ticket($authorizationfile, $authorization, $authorization->{'Salt'}->[0]);
3502 # No lingering password variables
3503 $decryptedPassword = $Randomsalt;
3504 $secretkey = $Randomsalt;
3505 $storedpassword = $Randomsalt;
3506 $Hashedpassword = $Randomsalt;
3507 $authorization->{'Password'}->[0] = $Randomsalt;
3509 return $newpassword;
3511 # First three arguments are file paths
3512 sub create_newuser # ($loginfile, $sessionfile, $authorizationfile, $password, $newuser, $newpassword, $newsession) -> account text
3514 my $loginfile = shift || "";
3515 my $sessionfile = shift || "";
3516 my $authorizationfile = shift || "";
3517 my $password = shift || "";
3518 my $newuser = shift || "";
3519 my $newpassword = shift || "";
3520 my $newsession = shift || "";
3522 # Get Login session ticket
3523 my $loginticket = read_ticket($loginfile);
3524 return "" unless $loginticket;
3525 # Login ticket file has been used, remove it
3526 unlink($loginfile);
3527 # Get Randomsalt
3528 my $Randomsalt = $loginticket->{'Randomsalt'}->[0];
3529 return "" unless $Randomsalt;
3530 my $LoginID = $loginticket->{'Session'}->[0];
3531 return "" unless $LoginID;
3533 # Get session ticket
3534 my $sessionticket = read_ticket($sessionfile);
3535 return "" unless $sessionticket;
3536 # Get User credentials for authorization
3537 my $authorization = read_ticket($authorizationfile);
3538 return "" unless $authorization && lc($authorization->{'Username'}->[0]) eq lc($sessionticket->{'Username'}->[0]);
3539 my $sessionkey = $sessionticket->{'Key'}->[0];
3540 my $serversalt = $authorization->{'Salt'}->[0];
3541 return "" unless $serversalt;
3543 my $storedpassword = $authorization->{'Password'}->[0];
3544 my $Hashedpassword = hash_string($storedpassword.$Randomsalt);
3545 return "" unless $password eq $Hashedpassword;
3546 my $secretkey = hash_string($storedpassword.$LoginID.$Randomsalt);
3548 # Decrypt the $newpassword
3549 my $decryptedPassword = XOR_hex_strings($secretkey, $newpassword);
3550 return "" unless $decryptedPassword;
3552 # Authorization succeeded, create new account
3553 my $newaccount = {};
3554 $newaccount->{'Type'} = ['PASSWORD'];
3555 $newaccount->{'Username'} = [$newuser];
3556 $newaccount->{'Password'} = [$decryptedPassword];
3557 $newaccount->{'Salt'} = [$serversalt];
3558 $newaccount->{'Session'} = ['SESSION'];
3559 if($newsession eq 'IPADDRESS'){$newaccount->{'Session'} = ['IPADDRESS'];};
3560 if($newsession eq 'CHALLENGE'){$newaccount->{'Session'} = ['CHALLENGE'];};
3561 my $timesec = time();
3562 my $gmt_date = gmtime();
3563 $newaccount->{'Time'} = [$timesec];
3564 $newaccount->{'Date'} = [$gmt_date];
3566 # AllowedPaths
3567 my $NewAllowedPaths = "";
3568 my $PATH_INFO = $ENV{'CGI_BINARY_FILE'} ? $ENV{'CGI_BINARY_FILE'} : $ENV{'PATH_INFO'};
3569 my $currentRoot = "";
3570 $currentRoot = $1 if $PATH_INFO =~ m!^([\w\-\. /]+)!isg;
3571 $currentRoot =~ s![^/]+$!!isg;
3572 if($currentRoot)
3574 $currentRoot .= '/' unless $currentRoot =~ m!/$!;
3575 my $newpath = "^".${currentRoot}.'[\w\-]+\.html?';
3576 $NewAllowedPaths .= 'AllowedPaths: ^'.${currentRoot}.'[\w\-]+\.html?'."\n";
3577 $newaccount->{'AllowedPaths'} = [$newpath];
3579 else
3581 # Tricky PATH_INFO, deny all
3582 $NewAllowedPaths .= "DeniedPaths: ^/\n";
3583 $newaccount->{'DeniedPaths'} = ["DeniedPaths: ^/\n"];
3586 # Construct home directory path
3587 my $FullHomeDirectoryPath = "";
3588 my $currentHome = lc($newuser);
3589 if($currentHome && $currentHome !~ /^\s*\#/)
3591 $currentHome =~ s![^\w]!_!isg;
3592 my $newpath = "^${currentRoot}$currentHome/";
3593 push(@{$newaccount->{'AllowedPaths'}}, $newpath);
3594 # Create home directory
3595 $FullHomeDirectoryPath = $ENV{'HOME'}.${currentRoot}.$currentHome;
3598 # Allowed Paths
3599 CGIexecute::defineCGIvariable('ALLOWEDPATHS', "");
3600 my $allowedpaths = ${"CGIexecute::ALLOWEDPATHS"};
3601 if($allowedpaths && $allowedpaths !~ /^\s*\#/)
3603 $allowedpaths =~ s![^\^\w\./\;\+\*\?\[\]\$]!!isg;
3604 my @pathlist = split(/\;/, $allowedpaths);
3605 foreach my $entry (@pathlist)
3607 push(@{$newaccount->{'AllowedPaths'}}, "^".${currentRoot}.$entry);
3611 # Allowed IP addresses
3612 CGIexecute::defineCGIvariable('IPADDRESS', "");
3613 my $ipaddress = ${"CGIexecute::IPADDRESS"};
3614 if($ipaddress && $ipaddress !~ /^\s*\#/)
3616 $ipaddress =~ s![^\d\.\;]!!isg;
3617 my @iplist = split(/\;/, $ipaddress);
3618 foreach my $entry (@iplist)
3620 next unless $entry =~ /\d/;
3621 next if $entry =~ /^\s*\#/;
3622 $entry =~ s/\./\\./g;
3623 push(@{$newaccount->{'IPaddress'}}, $entry);
3627 # Capabilities
3628 CGIexecute::defineCGIvariable('NEWCAPABILITIES', "");
3629 my $capabilities = ${"CGIexecute::NEWCAPABILITIES"};
3630 if($capabilities && $capabilities !~ /^\W*\#/)
3632 $capabilities =~ s!\#.*$!!isg;
3633 $capabilities =~ s![^\w\s]!!isg;
3634 my @caplist = split(/\s/, $capabilities);
3635 foreach my $entry (@caplist)
3637 next unless $entry =~ /\w/;
3638 next if $entry =~ /^\s*\#/;
3639 push(@{$newaccount->{'Capabilities'}}, $entry);
3643 # Sign the new ticket
3644 my $Signature = SignTicketWithMasterkey($newaccount, $newaccount->{'Salt'}->[0]);
3646 # Write
3647 my $datetime = gmtime();
3648 my $newuserfile = "";
3649 if(grep(/^CreateUser$/, @{$authorization->{'Capabilities'}}))
3651 my $newuserfilename = lc($newuser);
3652 $newuserfilename =~ s/[^\w]/_/isg;
3653 $newuserfile = $authorizationfile;
3654 $newuserfile =~ s![^/]*$!!isg;
3655 $newuserfile .= $newuserfilename;
3656 if(-s $newuserfile)
3658 $newuserfile = "";
3660 elsif($FullHomeDirectoryPath && !(-d $FullHomeDirectoryPath || -s $FullHomeDirectoryPath))
3662 if(-d "$ENV{'HOME'}${currentRoot}.SkeletonDir")
3664 `cp -r '$ENV{'HOME'}${currentRoot}.SkeletonDir' '$FullHomeDirectoryPath'`;
3666 elsif(-d "$ENV{'HOME'}${currentRoot}SkeletonDir")
3668 `cp -r '$ENV{'HOME'}${currentRoot}SkeletonDir' '$FullHomeDirectoryPath'`;
3670 elsif(-s "$ENV{'HOME'}${currentRoot}UserIndex.html")
3672 mkdir $FullHomeDirectoryPath;
3673 `cp '$ENV{'HOME'}${currentRoot}UserIndex.html' '$FullHomeDirectoryPath/index.html'`;
3675 elsif(-s "$ENV{'HOME'}${currentRoot}index.html")
3677 mkdir $FullHomeDirectoryPath;
3678 `cp '$ENV{'HOME'}${currentRoot}index.html' '$FullHomeDirectoryPath/index.html'`;
3684 my $newaccounttext = write_ticket($newuserfile, $newaccount, $serversalt);
3686 # Re-encrypt the new password for transmission
3687 if($newaccounttext =~ /^(Password\:\s+)(\S+)\s*$/)
3689 my $passwordvalue = $1;
3690 my $reencryptedpassword = XOR_hex_strings($secretkey, $passwordvalue);
3691 my $encryptedpasswordline = "<span id='newaccount'>$reencryptedpassword</span>";
3692 $newaccounttext =~ s/^(Password\:\s+)(\S+)\s*$/\1$encryptedpasswordline/gim;
3694 # No lingering passwords
3695 $passwordvalue = $serversalt;
3697 return $newaccounttext;
3700 # Copy a Challenge ticket file to a new name which is the hash of the new $CHALLENGETICKET and the password
3701 sub copy_challenge_file #($oldchallengefile, $authorizationfile, $sessionpath) -> $CHALLENGETICKET
3703 my $oldchallengefile = shift || "";
3704 my $authorizationfile = shift || "";
3705 my $sessionpath = shift || "";
3706 $sessionpath =~ s!/+$!!g;
3708 # Get Login session ticket
3709 my $oldchallenge = read_ticket($oldchallengefile);
3710 return "" unless $oldchallenge;
3712 # Get Authorization (user) session file
3713 my $authorization = read_ticket($authorizationfile);
3714 return "" unless $authorization;
3715 my $storedpassword = $authorization->{'Password'}->[0];
3716 return "" unless $storedpassword;
3717 my $challengekey = $oldchallenge->{'Key'}->[0];
3718 return "" unless $challengekey;
3720 # Create Random Hash Salt
3721 my $NEWCHALLENGETICKET = get_random_hex();;
3722 my $newchallengefile = hash_string($challengekey.$NEWCHALLENGETICKET);
3723 return "" unless $newchallengefile;
3725 $ENV{'CHALLENGETICKET'} = $NEWCHALLENGETICKET;
3726 CGIexecute::defineCGIvariable('CHALLENGETICKET', "");
3727 ${"CGIexecute::CHALLENGETICKET"} = $NEWCHALLENGETICKET;
3729 # Write Session Ticket
3730 open(OLDCHALLENGE, "<$oldchallengefile") || die "<$oldchallengefile: $!\n";
3731 my @OldChallengeLines = <OLDCHALLENGE>;
3732 close(OLDCHALLENGE);
3733 # Old file should now be removed
3734 unlink($oldchallengefile);
3736 open(SESSION, ">$sessionpath/$newchallengefile") || die "$sessionpath/$newchallengefile: $!\n";
3737 foreach $line (@OldChallengeLines)
3739 print SESSION $line;
3741 close(SESSION);
3743 # No lingering passwords
3744 $storedpassword = $oldchallenge;
3746 return $NEWCHALLENGETICKET;
3749 sub create_login_file #($PasswordDir, $SessionDir, $IPaddress)
3751 my $PasswordDir = shift || "";
3752 my $SessionDir = shift || "";
3753 my $IPaddress = shift || "";
3755 # Create Login Ticket
3756 my $LOGINTICKET= get_random_hex ();
3758 # Create Random Hash Salt
3759 my $RANDOMSALT= get_random_hex();
3761 # Create SALT file if it does not exist
3762 # Remove this, including test account for life system
3763 unless(-d "$SessionDir")
3765 `mkdir -p "$SessionDir"`;
3767 unless(-d "$PasswordDir")
3769 `mkdir -p "$PasswordDir"`;
3771 # Create SERVERSALT and default test account
3772 my $SERVERSALT = "";
3773 unless(-s "$PasswordDir/SALT")
3775 $SERVERSALT= get_random_hex();
3776 open(SALTFILE, ">$PasswordDir/SALT") || die ">$PasswordDir/SALT: $!\n";
3777 print SALTFILE "$SERVERSALT\n";
3778 close(SALTFILE);
3780 # Update test account (should be removed in live system)
3781 my @alltestusers = ("test", "testip", "testchallenge", "admin");
3782 foreach my $testuser (@alltestusers)
3784 if(-s "$PasswordDir/$testuser")
3786 my $plainpassword = $testuser eq 'admin' ? "There is no password like more password" : "testing";
3788 my $storedpassword = hash_string(${plainpassword}.${testuser}.${SERVERSALT});
3789 # Encrypt the new password with the MasterKey
3790 my $authorization = read_ticket("$PasswordDir/$testuser") || return "";
3791 $authorization->{'Salt'} = [$SERVERSALT];
3792 $authorization->{'Type'} = ['INACTIVE PASSWORD'] if $testuser eq 'admin';
3793 set_password($authorization, $SERVERSALT, $plainpassword);
3794 write_ticket("$PasswordDir/$testuser", $authorization, $SERVERSALT);
3795 # No lingering passwords
3796 $storedpassword = $SERVERSALT;
3797 $plainpassword = $SERVERSALT;
3802 # Read in site Salt
3803 open(SALTFILE, "<$PasswordDir/SALT") || die "$PasswordDir/SALT: $!\n";
3804 $SERVERSALT=<SALTFILE>;
3805 close(SALTFILE);
3806 chomp($SERVERSALT);
3808 # Create login session ticket
3809 my $datetime = gmtime();
3810 my $timesec = time();
3811 my $loginticket = {};
3812 $loginticket->{Type} = ['LOGIN'];
3813 $loginticket->{IPaddress} = [$IPaddress];
3814 $loginticket->{Salt} = [$SERVERSALT];
3815 $loginticket->{Session} = [$LOGINTICKET];
3816 $loginticket->{Randomsalt} = [$RANDOMSALT];
3817 $loginticket->{Expires} = ['+600s'];
3818 $loginticket->{Date} = ["$datetime UTC"];
3819 $loginticket->{Time} = [$timesec];
3820 write_ticket("$SessionDir/$LOGINTICKET", $loginticket, $SERVERSALT);
3822 # Set global variables
3823 # $SERVERSALT
3824 $ENV{'SERVERSALT'} = $SERVERSALT;
3825 CGIexecute::defineCGIvariable('SERVERSALT', "");
3826 ${"CGIexecute::SERVERSALT"} = $SERVERSALT;
3828 # $SESSIONTICKET
3829 $ENV{'SESSIONTICKET'} = $SESSIONTICKET;
3830 CGIexecute::defineCGIvariable('SESSIONTICKET', "");
3831 ${"CGIexecute::SESSIONTICKET"} = $SESSIONTICKET;
3833 # $RANDOMSALT
3834 $ENV{'RANDOMSALT'} = $RANDOMSALT;
3835 CGIexecute::defineCGIvariable('RANDOMSALT', "");
3836 ${"CGIexecute::RANDOMSALT"} = $RANDOMSALT;
3838 # $LOGINTICKET
3839 $ENV{'LOGINTICKET'} = $LOGINTICKET;
3840 CGIexecute::defineCGIvariable('LOGINTICKET', "");
3841 ${"CGIexecute::LOGINTICKET"} = $LOGINTICKET;
3843 return $ENV{'LOGINTICKET'};
3846 sub create_session_file #($sessionfile, $loginfile, $authorizationfile, $path) -> Is $loginfile deleted? 0/1
3848 my $sessionfile = shift || "";
3849 my $loginfile = shift || "";
3850 my $authorizationfile = shift || "";
3851 my $path = shift || "";
3853 # Get Login session ticket
3854 my $loginticket = read_ticket($loginfile);
3855 return unlink($loginfile) unless $loginticket;
3857 # Get Authorization (user) session file
3858 my $authorization = read_ticket($authorizationfile);
3859 return unlink($loginfile) unless $authorization;
3861 # For a Session or a Challenge, we need a stored key
3862 my $sessionkey = "";
3863 my $secretkey = "";
3864 if($authorization->{'Session'} && $authorization->{'Session'}->[0] ne 'IPADDRESS')
3866 my $storedpassword = $authorization->{'Password'}->[0];
3867 my $loginticketid = $loginticket->{'Session'}->[0];
3868 my $randomsalt = $loginticket->{'Randomsalt'}->[0];
3869 $sessionkey = hash_string($storedpassword.$loginticketid);
3870 $secretkey = hash_string($storedpassword.$loginticketid.$randomsalt);
3871 # No lingering passwords
3872 $storedpassword = $loginticketid;
3874 # Get Session id
3875 my $sessionid = "";
3876 if($sessionfile =~ m!([^/]+)$!)
3878 $sessionid = $1;
3881 # Convert Authorization content to Session content
3882 my $sessionContent = {};
3883 my $SessionType = $authorization->{'Session'}->[0] ? $authorization->{'Session'}->[0] : "SESSION";
3884 $sessionContent->{Type} = [$SessionType];
3885 $sessionContent->{Username} = [lc($authorization->{'Username'}->[0])];
3886 $sessionContent->{Session} = [$sessionid];
3887 $sessionContent->{Time} = [time];
3888 # Limit communication to the login IP address, except for Tor like situations with VariableREMOTE_ADDR
3889 $sessionContent->{IPaddress} = ['.'];
3890 if($sessionContent->{Type}->[0] eq 'CHALLENGE' && grep(/^VariableREMOTE_ADDR$/, @{$authorization->{'Capabilities'}}))
3892 $sessionContent->{IPaddress} = $authorization->{'IPaddress'} if $authorization->{'IPaddress'};
3894 else
3896 $sessionContent->{IPaddress} = $loginticket->{'IPaddress'};
3898 $sessionContent->{Salt} = $authorization->{'Salt'};
3899 $sessionContent->{Randomsalt} = $loginticket->{'Randomsalt'};
3900 $sessionContent->{AllowedPaths} = $authorization->{'AllowedPaths'};
3901 $sessionContent->{DeniedPaths} = $authorization->{'DeniedPaths'};
3902 $sessionContent->{Expires} = $authorization->{'MaxLifetime'};
3903 $sessionContent->{Capabilities} = $authorization->{'Capabilities'};
3904 foreach my $pattern (keys(%TicketRequiredPatterns))
3906 if($path =~ m#$pattern#)
3908 my ($SessionPath, $PasswordsPath, $Login, $validtime) = split(/\t/, $TicketRequiredPatterns{$pattern});
3909 push(@{$sessionContent->{Expires}}, $validtime);
3912 $sessionContent->{Key} = [$sessionkey] if $sessionkey;
3913 $sessionContent->{Secretkey} = [$secretkey] if $secretkey;
3914 $sessionContent->{Date} = [gmtime()." UTC"];
3916 # Write Session Ticket
3917 write_ticket($sessionfile, $sessionContent, $authorization->{'Salt'}->[0]);
3919 # Login file should now be removed
3920 return unlink($loginfile);
3923 sub check_ticket_validity # ($type, $ticketfile, $address, $path [, $unsigned])
3925 my $type = shift || "SESSION";
3926 my $ticketfile = shift || "";
3927 my $address = shift || "";
3928 my $path = shift || "";
3929 my $unsigned = shift || 0;
3931 # Is there a session ticket of this name?
3932 return 0 unless -s "$ticketfile";
3934 # There is a session ticket, is it linked to this IP address?
3935 my $ticket = read_ticket($ticketfile);
3936 unless($ticket)
3938 print STDERR "Ticket expired or empty: $ticketfile\n";
3939 return;
3942 # Is this the right type of ticket
3943 unless($ticket && $ticket->{'Type'}->[0] eq $type)
3945 print STDERR "Wrong ticket type: $ticket->{'Type'}->[0] eq $type\n";
3946 return;
3949 # Does the IP address match?
3950 my $IPmatches = @{$ticket->{"IPaddress"}} ? 0 : 1;
3951 for $IPpattern (@{$ticket->{"IPaddress"}})
3953 ++$IPmatches if $address =~ m#^$IPpattern#ig;
3955 if($address && ! $IPmatches)
3957 print STDERR "Wrong REMOTE ADDR for $ticket->{'Username'}->[0]: $ticket->{'IPaddress'}->[0] vs $address\n";
3958 return 0;
3961 # Is the path denied
3962 my $Pathmatches = 0;
3963 foreach $Pathpattern (@{$ticket->{"DeniedPaths"}})
3965 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3967 return 0 if @{$ticket->{"DeniedPaths"}} && $Pathmatches;
3969 # Is the path allowed
3970 $Pathmatches = 0;
3971 foreach $Pathpattern (@{$ticket->{"AllowedPaths"}})
3973 ++$Pathmatches if $path =~ m#$Pathpattern#ig;
3975 return 0 unless !@{$ticket->{"AllowedPaths"}} || $Pathmatches;
3977 # Check signature if not told to use an unsigned ticket (dangerous)
3978 my $Signature = TicketSignature($ticket, $ticket->{'Salt'}->[0]);
3979 if((! $unsigned) && $Signature && $Signature ne $ticket->{'Signature'}->[0])
3981 print STDERR "Invalid signature for $ticket->{'Type'}: $ticket->{'Username'}\n$ticketfile\n";
3982 return 0;
3985 # Make login values available (will also protect against resetting by query)
3986 $ENV{"LOGINUSERNAME"} = lc($ticket->{'Username'}->[0]);
3987 $ENV{"LOGINIPADDRESS"} = $address;
3988 $ENV{"LOGINPATH"} = $path;
3989 $ENV{"SESSIONTYPE"} = $type unless $type eq "PASSWORD";
3991 # Set Capabilities, if present
3992 if($ticket->{'Username'}->[0] && @{$ticket->{'Capabilities'}})
3994 $ENV{'CAPABILITIES'} = $ticket->{'Username'}->[0];
3995 CGIexecute::defineCGIvariableList('CAPABILITIES', "");
3996 @{"CGIexecute::CAPABILITIES"} = @{$ticket->{'Capabilities'}};
3997 # Capabilities should not be changed anymore by CGI query!
3999 # Capabilities are NOT to be set by the query
4000 CGIexecute::ProtectCGIvariable('CAPABILITIES');
4002 return 1;
4006 sub remove_expired_tickets # ($path) -> number of tickets removed
4008 my $path = shift || "";
4009 return 0 unless $path;
4010 $path =~ s!/+$!!g;
4011 my $removed_tickets = 0;
4012 my @ticketlist = glob("$path/*");
4013 foreach my $ticketfile (@ticketlist)
4015 my $ticket = read_ticket($ticketfile);
4016 unless($ticket)
4018 unlink $ticketfile;
4019 ++$removed_tickets;
4022 return $removed_tickets;
4025 sub set_password # ($ticket, $salt, $plainpassword) -> $password
4027 my $ticket = shift || "";
4028 my $salt = shift || "";
4029 my $plainpassword = shift || "";
4031 my $user = lc($ticket->{'Username'}->[0]);
4032 return "" unless $user;
4033 $salt = $ticket->{'Salt'}->[0] unless $salt;
4035 my $storedpassword = hash_string(${plainpassword}.${user}.${salt});
4036 $ticket->{'Password'} = [$storedpassword];
4037 $ticket->{'Salt'} = [$salt];
4038 # No lingering passwords
4039 $storedpassword = $salt;
4040 $plainpassword = $salt;
4042 return $ticket->{'Password'}->[0];
4045 sub write_ticket # ($ticketfile, $ticket, $salt [, $masterkey]) -> &%ticket
4047 my $ticketfile = shift || "";
4048 my $ticket = shift || "";
4049 my $salt = shift || "";
4050 my $masterkey = shift || $ENV{'CGIMasterKey'};
4052 # Encrypt password
4053 EncryptTicketWithMasterKey($ticket, $salt, $masterkey);
4055 # Sign the new ticket
4056 my $signature = SignTicketWithMasterkey($ticket, $salt, $masterkey);
4058 # Create ordered list with labels
4059 my @orderlist = ('Type', 'Username', 'Password', 'IPaddress', 'AllowedPaths', 'DeniedPaths',
4060 'Expires', 'Capabilities', 'Salt', 'Session', 'Randomsalt',
4061 'Date', 'Time', 'Signature', 'Key', 'Secretkey');
4062 my @labellist = keys(%{$ticket});
4063 foreach my $label (@orderlist)
4065 @labellist = grep(!/\b$label\b/, @labellist);
4068 # Create ticket in text
4069 my $TicketText = "";
4070 foreach my $label (@orderlist, @labellist)
4072 next unless exists($ticket->{$label}) && $ticket->{$label}->[0];
4073 foreach my $value (@{$ticket->{$label}})
4075 $TicketText .= "$label: $value\n";
4078 if($ticketfile)
4080 open(TICKET, ">$ticketfile") || die "$ticketfile: $!\n";
4081 print TICKET $TicketText;
4082 close(TICKET);
4085 return $TicketText;
4088 # Note, read_ticket will return 0 if the ticket has expired!
4089 sub read_ticket # ($ticketfile [, $salt, $masterkey]) -> &%ticket
4091 my $ticketfile = shift || "";
4092 my $serversalt = shift || "";
4093 my $masterkey = shift || $ENV{'CGIMasterKey'};
4095 my $ticket = {};
4096 if($ticketfile && -s $ticketfile)
4098 open(TICKETFILE, "<$ticketfile") || die "$ticketfile: $!\n";
4099 my @alllines = <TICKETFILE>;
4100 close(TICKETFILE);
4101 foreach my $currentline (@alllines)
4103 # Skip empty lines and comments
4104 next unless $currentline =~ /\S/;
4105 next if $currentline =~ /^\s*\#/;
4107 if($currentline =~ /^\s*(\S[^\:]+)\:\s+(.*)\s*$/)
4109 my $Label = $1;
4110 my $Value = $2;
4111 $ticket->{$Label} = () unless exists($ticket->{$Label});
4112 push(@{$ticket->{$Label}}, $Value);
4116 if($masterkey && exists($ticket->{'Password'}) && $ticket->{'Password'}->[0])
4118 # Use the ServerSalt stored in the ticket, if present
4119 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4121 $serversalt = $ticket->{Salt}->[0];
4123 # Decrypt all passwords
4124 DecryptTicketWithMasterKey($ticket, $serversalt, $masterkey) ||
4125 die "Decryption failed: DecryptTicketWithMasterKey ($ticket, $serversalt)\n";
4128 # Check whether the ticket has expired
4129 if(exists($ticket->{Expires}))
4131 my $StartTime = 0;
4132 if(exists($ticket->{Time}) && $ticket->{Time}->[0] > 0)
4134 $StartTime = [(sort(@{$ticket->{Time}}))]->[0];
4136 else
4138 # Get SessionTicket file stats
4139 my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)
4140 = stat($ticketfile);
4141 $StartTime = $ctime;
4143 foreach my $Value (@{$ticket->{'Expires'}})
4145 # Recalculate expire date from relative time
4146 if($Value =~ /^\+/)
4148 if($Value =~ /^\+(\d+)\s*d(ays)?\s*$/)
4150 $ExpireTime = 24*3600*$1;
4152 elsif($Value =~ /^\+(\d+)\s*m(inutes)?\s*$/)
4154 $ExpireTime = 60*$1;
4156 elsif($Value =~ /^\+(\d+)\s*h(ours)?\s*$/)
4158 $ExpireTime = 3600*$1;
4160 elsif($Value =~ /^\+(\d+)\s*s(econds)?\s*$/)
4162 $ExpireTime = $1;
4164 elsif($Value =~ /^\+(\d+)\s*$/)
4166 $ExpireTime = $1;
4169 my $absoluteTime = $Value =~ /^\+/ ? $StartTime + $ExpireTime : $Value;
4170 return 0 unless $absoluteTime > time;
4172 @{$ticket->{Expires}} = sort(@{$ticket->{Expires}});
4174 return $ticket;
4177 # Set up a valid ticket from a given text file
4178 # Use from command line. DO NOT USE ONLINE
4179 # Watch out for passwords that get stored in the history file
4181 # perl CGIscriptor.pl --managelogin [options] [files]
4182 # Options:
4183 # salt={file or saltvalue}
4184 # masterkey={file or plaintext}
4185 # newmasterkey={file or plaintext}
4186 # password={file or palintext}
4188 # Followed by one or more file names.
4189 # Options can be interspersed between filenames,
4190 # e.g., password='plaintext'
4191 # Note that passwords are only used once!
4193 sub setup_ticket_file # (@ARGV)
4195 # Stop when run on-line
4196 return if $ENV{'PATH_INFO'} || $ENV{'QUERY_STRING'};
4198 my %Settings = ();
4199 foreach my $input (@_)
4201 if($input =~ /^([\w]+)\=/)
4203 my $name = lc($1);
4204 my $value = $';
4205 chomp($value);
4207 if($value !~ m![^\w\.\~\/\:\-]! && $value !~ /^[\-\.]/ && -s "$value" && ! -d "$value")
4209 # Warn about reading a value from file
4210 print STDERR "Read '$name' from: '$value'\n";
4211 open(INPUTVALUE, "<$value") || die "$value: $!\n";
4212 $value = <INPUTVALUE>;
4213 chomp($value);
4216 $value =~ s/(^\'([^\']*)\'$)/\1/g;
4217 $value =~ s/(^\"([^\"]*)\"$)/\1/g;
4218 $Settings{$name} = $value;
4220 elsif($input !~ m![^\w\.\~\/\:\-]!i && $input !~ /^[\-\.]/i && -s $input)
4222 # We MUST have a salt
4223 $Settings{'salt'} = $ticket->{'Salt'}->[0] unless $Settings{'salt'};
4225 # Set the new masterkey to the old masterkey if there is no new masterkey
4226 $Settings{'newmasterkey'} = $Settings{'masterkey'} unless exists($Settings{'newmasterkey'});
4228 # Get the ticket
4229 my $ticket = read_ticket($input, $Settings{'salt'}, $Settings{'masterkey'});
4231 # Set a new password from plaintext
4232 $ticket->{'Salt'}->[0] = $Settings{'salt'} if $Settings{'salt'} && $Settings{'password'};
4233 set_password ($ticket, $Settings{'salt'}, $Settings{'password'}) if $Settings{'password'};
4234 # Write the ticket back to file
4235 write_ticket($input, $ticket, $Settings{'salt'}, $Settings{'newmasterkey'});
4237 # A password is only used once
4238 $Settings{'password'} = "";
4243 # Add a signature from $masterkey to a ticket in the label $signlabel
4244 sub SignTicketWithMasterkey # ($ticket, $serversalt [, $masterkey, $signlabel]) -> $Signature
4246 my $ticket = shift || return 0;
4247 my $serversalt = shift || "";
4248 my $masterkey = shift || $ENV{'CGIMasterKey'};
4249 my $signlabel = shift || 'Signature';
4251 my $Signature = TicketSignature($ticket, $serversalt, $masterkey);
4253 $ticket->{$signlabel} = [$Signature] if $Signature;
4255 return $Signature;
4258 # Determine ticket signature
4259 sub TicketSignature # ($ticket, $serversalt [, $masterkey]) -> $Signature
4261 my $ticket = shift || return 0;
4262 my $serversalt = shift || "";
4263 my $masterkey = shift || $ENV{'CGIMasterKey'};
4264 my $Signature = "";
4266 if($masterkey)
4268 # If the ServerSalt is not stored in the ticket, the SALT file has to be found
4269 if(!$serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4271 $serversalt = $ticket->{Salt}->[0];
4273 # Sign
4274 if($serversalt)
4276 my $username = lc($ticket->{'Username'}->[0]);
4277 my $hash1 = hash_string(${masterkey}.${serversalt});
4278 # The order of $username.$hash1 should be different than in DecryptTicketWithMasterKey
4279 my $CryptKey = hash_string($username.${'hash1'});
4280 my $SignText = "Type: ".$ticket->{'Type'}->[0]."\n";
4281 my @tmp = sort(@{$ticket->{'Username'}});
4282 $SignText .= "Username: @tmp\n";
4283 @tmp = sort(@{$ticket->{'IPaddress'}});
4284 $SignText .= "IPaddress: @tmp\n";
4285 @tmp = sort(@{$ticket->{'AllowedPaths'}});
4286 $SignText .= "AllowedPaths: @tmp\n";
4287 @tmp = sort(@{$ticket->{'DeniedPaths'}});
4288 $SignText .= "DeniedPaths: @tmp\n";
4289 @tmp = sort(@{$ticket->{'Session'}});
4290 $SignText .= "Session: @tmp\n";
4291 @tmp = sort(@{$ticket->{'Time'}});
4292 $SignText .= "Time: @tmp\n";
4293 @tmp = sort(@{$ticket->{'Expires'}});
4294 $SignText .= "Expires: @tmp\n";
4295 @tmp = sort(@{$ticket->{'Capabilities'}});
4296 $SignText .= "Capabilities: @tmp\n";
4297 @tmp = sort(@{$ticket->{'MaxLifetime'}});
4298 $SignText .= "MaxLifetime: @tmp\n";
4299 $Signature = HMAC_hex($CryptKey, $SignText);
4302 return $Signature;
4305 # Decrypts a password list IN PLACE
4306 sub DecryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4308 my $ticket = shift || return 0;
4309 my $serversalt = shift || "";
4310 my $masterkey = shift || $ENV{'CGIMasterKey'};
4312 if($masterkey && exists($ticket->{Password}) && $ticket->{Password}->[0])
4314 # If the ServerSalt is not given, read it from the the ticket
4315 if(! $serversalt && exists($ticket->{Salt}) && $ticket->{Salt}->[0])
4317 $serversalt = $ticket->{Salt}->[0];
4319 # Decrypt password(s)
4320 if($serversalt)
4322 my $hash1 = hash_string(${masterkey}.${serversalt});
4323 my $username = lc($ticket->{'Username'}->[0]);
4324 # The order of $hash1.$username should be different than in TicketSignature
4325 my $CryptKey = hash_string(${'hash1'}.$username);
4326 foreach my $password (@{$ticket->{Password}})
4328 $password = XOR_hex_strings($CryptKey,$password);
4332 return $ticket->{'Password'};
4334 sub EncryptTicketWithMasterKey # ($ticket, $serversalt [, $masterkey]) -> \@password_list
4336 DecryptTicketWithMasterKey(@_);
4339 # Implement HMAC signature hash.
4340 # Blocksize is length in HEX characters, NOT bytes
4341 sub HMAC_hex # ($key, $message [, $blocksizehex]) -> $hex
4343 my $key = shift || "";
4344 my $message = shift || "";
4345 my $blocksizehex = shift || length($key);
4346 $key = hash_string($key) if length($key) > $blocksizehex;
4348 my $innerkey = XOR_hex_byte ($key, "36");
4349 my $outerkey = XOR_hex_byte ($key, "5c");
4350 my $innerhash = hash_string($innerkey.$message);
4351 my $outerhash = hash_string($outerkey.$innerhash);
4353 return $outerhash;
4356 # XOR input with equally long string of repeated 2 hex character (byte)
4357 # string. Input must have even number of hex characters
4358 sub XOR_hex_byte # ($hex1, $hexbyte) -> $hex
4360 my $hex1 = shift || "";
4361 my $hexbyte = shift || "";
4362 my $bytelength = length($hexbyte);
4363 my $hex2 = $hex1;
4364 $hex2 =~ s/.{$bytelength}/$hexbyte/ig;
4365 return XOR_hex_strings($hex1, $hex2);
4368 sub XOR_hex_strings # ($hex1, $hex2) -> $hex
4370 my $hex1 = shift || "";
4371 my $hex2 = shift || "";
4372 my @hex1list = split('', $hex1);
4373 my @hex2list = split('', $hex2);
4374 my @hexresultlist = ();
4375 for(my $i; $i < scalar(@hex1list); ++$i)
4377 my $d1 = hex($hex1list[$i]);
4378 my $d2 = hex($hex2list[$i]);
4379 my $dresult = ($d1 ^ $d2);
4380 $hexresultlist[$i] = sprintf("%x", $dresult);
4382 $hexresult = join('', @hexresultlist);
4383 return $hexresult;
4386 # End of Handle login access
4389 ############################################################################
4391 # Handle foreign interpreters (i.e., scripting languages)
4393 # Insert perl code to execute scripts in foreign scripting languages.
4394 # Actually, the scripts inside the <SCRIPT></SCRIPT> blocks are piped
4395 # into an interpreter.
4396 # The code presented here is fairly confusing because it
4397 # actually writes perl code code to the output.
4399 # A table with the file handles
4400 %SCRIPTINGINPUT = ();
4402 # A function to clean up Client delivered CGI parameter values
4403 # (i.e., quote all odd characters)
4404 %SHRUBcharacterTR =
4406 "\'" => '&#39;',
4407 "\`" => '&#96;',
4408 "\"" => '&quot;',
4409 '&' => '&amper;',
4410 "\\" => '&#92;'
4413 sub shrubCGIparameter # ($String) -> Cleaned string
4415 my $String = shift || "";
4417 # Change all quotes [`'"] into HTML character entities
4418 my ($Char, $Transcript) = ('&', $SHRUBcharacterTR{'&'});
4420 # Protect &
4421 $String =~ s/\Q$Char\E/$Transcript/isg if $Transcript;
4423 while( ($Char, $Transcript) = each %SHRUBcharacterTR)
4425 next if $Char eq '&';
4426 $String =~ s/\Q$Char\E/$Transcript/isg;
4429 # Replace newlines
4430 $String =~ s/[\n]/\\n/g;
4431 # Replace control characters with their backslashed octal ordinal numbers
4432 $String =~ s/([^\S \t])/(sprintf("\\0%o", ord($1)))/eisg; #
4433 $String =~ s/([\x00-\x08\x0A-\x1F])/(sprintf("\\0%o", ord($1)))/eisg; #
4435 return $String;
4439 # The initial open statements: Open a pipe to the foreign script interpreter
4440 sub OpenForeignScript # ($ContentType) -> $DirectivePrefix
4442 my $ContentType = lc(shift) || return "";
4443 my $NewDirective = "";
4445 return $NewDirective if($SCRIPTINGINPUT{$ContentType});
4447 # Construct a unique file handle name
4448 $SCRIPTINGFILEHANDLE = uc($ContentType);
4449 $SCRIPTINGFILEHANDLE =~ s/\W/\_/isg;
4450 $SCRIPTINGINPUT{$ContentType} = $SCRIPTINGFILEHANDLE
4451 unless $SCRIPTINGINPUT{$ContentType};
4453 # Create the relevant script: Open the pipe to the interpreter
4454 $NewDirective .= <<"BLOCKCGISCRIPTOROPEN";
4455 # Open interpreter for '$ContentType'
4456 # Open pipe to interpreter (if it isn't open already)
4457 open($SCRIPTINGINPUT{$ContentType}, "|$ScriptingLanguages{$ContentType}") || main::dieHandler(14, "$ContentType: \$!\\n");
4458 BLOCKCGISCRIPTOROPEN
4460 # Insert Initialization code and CGI variables
4461 $NewDirective .= InitializeForeignScript($ContentType);
4463 # Ready
4464 return $NewDirective;
4468 # The final closing code to stop the interpreter
4469 sub CloseForeignScript # ($ContentType) -> $DirectivePrefix
4471 my $ContentType = lc(shift) || return "";
4472 my $NewDirective = "";
4474 # Do nothing unless the pipe realy IS open
4475 return "" unless $SCRIPTINGINPUT{$ContentType};
4477 # Initial comment
4478 $NewDirective .= "\# Close interpreter for '$ContentType'\n";
4481 # Write the Postfix code
4482 $NewDirective .= CleanupForeignScript($ContentType);
4484 # Create the relevant script: Close the pipe to the interpreter
4485 $NewDirective .= <<"BLOCKCGISCRIPTORCLOSE";
4486 close($SCRIPTINGINPUT{$ContentType}) || main::dieHandler(15, \"$ContentType: \$!\\n\");
4487 select(STDOUT); \$|=1;
4489 BLOCKCGISCRIPTORCLOSE
4491 # Remove the file handler of the foreign script
4492 delete($SCRIPTINGINPUT{$ContentType});
4494 return $NewDirective;
4498 # The initialization code for the foreign script interpreter
4499 sub InitializeForeignScript # ($ContentType) -> $DirectivePrefix
4501 my $ContentType = lc(shift) || return "";
4502 my $NewDirective = "";
4504 # Add initialization code
4505 if($ScriptingInitialization{$ContentType})
4507 $NewDirective .= <<"BLOCKCGISCRIPTORINIT";
4508 # Initialization Code for '$ContentType'
4509 # Select relevant output filehandle
4510 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4512 # The Initialization code (if any)
4513 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}INITIALIZATIONCODE';
4514 $ScriptingInitialization{$ContentType}
4515 ${ContentType}INITIALIZATIONCODE
4517 BLOCKCGISCRIPTORINIT
4520 # Add all CGI variables defined
4521 if(exists($ScriptingCGIvariables{$ContentType}))
4523 # Start writing variable definitions to the Interpreter
4524 if($ScriptingCGIvariables{$ContentType})
4526 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEF";
4527 # CGI variables (from the %default_values table)
4528 print $SCRIPTINGINPUT{$ContentType} << '${ContentType}CGIVARIABLES';
4529 BLOCKCGISCRIPTORVARDEF
4532 my ($N, $V);
4533 foreach $N (keys(%default_values))
4535 # Determine whether the parameter has been defined
4536 # (the eval is a workaround to get at the variable value)
4537 next unless eval("defined(\$CGIexecute::$N)");
4539 # Get the value from the EXECUTION environment
4540 $V = eval("\$CGIexecute::$N");
4541 # protect control characters (i.e., convert them to \0.. form)
4542 $V = shrubCGIparameter($V);
4544 # Protect interpolated variables
4545 eval("\$CGIexecute::$N = '$V';") unless $ScriptingCGIvariables{$ContentType};
4547 # Print the actual declaration for this scripting language
4548 if($ScriptingCGIvariables{$ContentType})
4550 $NewDirective .= sprintf($ScriptingCGIvariables{$ContentType}, $N, $V);
4551 $NewDirective .= "\n";
4555 # Stop writing variable definitions to the Interpreter
4556 if($ScriptingCGIvariables{$ContentType})
4558 $NewDirective .= <<"BLOCKCGISCRIPTORVARDEFEND";
4559 ${ContentType}CGIVARIABLES
4560 BLOCKCGISCRIPTORVARDEFEND
4565 $NewDirective .= << "BLOCKCGISCRIPTOREND";
4567 # Select STDOUT filehandle
4568 select(STDOUT); \$|=1;
4570 BLOCKCGISCRIPTOREND
4572 return $NewDirective;
4576 # The cleanup code for the foreign script interpreter
4577 sub CleanupForeignScript # ($ContentType) -> $DirectivePrefix
4579 my $ContentType = lc(shift) || return "";
4580 my $NewDirective = "";
4582 # Return if not needed
4583 return $NewDirective unless $ScriptingCleanup{$ContentType};
4585 # Create the relevant script: Open the pipe to the interpreter
4586 $NewDirective .= <<"BLOCKCGISCRIPTORSTOP";
4587 # Cleanup Code for '$ContentType'
4588 # Select relevant output filehandle
4589 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4590 # Print Cleanup code to foreign script
4591 print $SCRIPTINGINPUT{$ContentType} <<'${ContentType}SCRIPTSTOP';
4592 $ScriptingCleanup{$ContentType}
4593 ${ContentType}SCRIPTSTOP
4595 # Select STDOUT filehandle
4596 select(STDOUT); \$|=1;
4597 BLOCKCGISCRIPTORSTOP
4599 return $NewDirective;
4603 # The prefix code for each <script></script> block
4604 sub PrefixForeignScript # ($ContentType) -> $DirectivePrefix
4606 my $ContentType = lc(shift) || return "";
4607 my $NewDirective = "";
4609 # Return if not needed
4610 return $NewDirective unless $ScriptingPrefix{$ContentType};
4612 my $Quote = "\'";
4613 # If the CGIvariables parameter is defined, but empty, interpolate
4614 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4615 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4616 !$ScriptingCGIvariables{$ContentType};
4618 # Add initialization code
4619 $NewDirective .= <<"BLOCKCGISCRIPTORPREFIX";
4620 # Prefix Code for '$ContentType'
4621 # Select relevant output filehandle
4622 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4624 # The block Prefix code (if any)
4625 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}PREFIXCODE$Quote;
4626 $ScriptingPrefix{$ContentType}
4627 ${ContentType}PREFIXCODE
4628 # Select STDOUT filehandle
4629 select(STDOUT); \$|=1;
4630 BLOCKCGISCRIPTORPREFIX
4632 return $NewDirective;
4636 # The postfix code for each <script></script> block
4637 sub PostfixForeignScript # ($ContentType) -> $DirectivePrefix
4639 my $ContentType = lc(shift) || return "";
4640 my $NewDirective = "";
4642 # Return if not needed
4643 return $NewDirective unless $ScriptingPostfix{$ContentType};
4645 my $Quote = "\'";
4646 # If the CGIvariables parameter is defined, but empty, interpolate
4647 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4648 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4649 !$ScriptingCGIvariables{$ContentType};
4651 # Create the relevant script: Open the pipe to the interpreter
4652 $NewDirective .= <<"BLOCKCGISCRIPTORPOSTFIX";
4653 # Postfix Code for '$ContentType'
4654 # Select filehandle to interpreter
4655 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4656 # Print postfix code to foreign script
4657 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SCRIPTPOSTFIX$Quote;
4658 $ScriptingPostfix{$ContentType}
4659 ${ContentType}SCRIPTPOSTFIX
4660 # Select STDOUT filehandle
4661 select(STDOUT); \$|=1;
4662 BLOCKCGISCRIPTORPOSTFIX
4664 return $NewDirective;
4667 sub InsertForeignScript # ($ContentType, $directive, @SRCfile) -> $NewDirective
4669 my $ContentType = lc(shift) || return "";
4670 my $directive = shift || return "";
4671 my @SRCfile = @_;
4672 my $NewDirective = "";
4674 my $Quote = "\'";
4675 # If the CGIvariables parameter is defined, but empty, interpolate
4676 # code string (i.e., $var .= << "END" i.s.o. $var .= << 'END')
4677 $Quote = '"' if exists($ScriptingCGIvariables{$ContentType}) &&
4678 !$ScriptingCGIvariables{$ContentType};
4680 # Create the relevant script
4681 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4682 # Insert Code for '$ContentType'
4683 # Select filehandle to interpreter
4684 select($SCRIPTINGINPUT{$ContentType}); \$|=1;
4685 BLOCKCGISCRIPTORINSERT
4687 # Use SRC feature files
4688 my $ThisSRCfile;
4689 while($ThisSRCfile = shift(@_))
4691 # Handle blocks
4692 if($ThisSRCfile =~ /^\s*\{\s*/)
4694 my $Block = $';
4695 $Block = $` if $Block =~ /\s*\}\s*$/;
4696 $NewDirective .= <<"BLOCKCGISCRIPTORSRCBLOCK";
4697 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}SRCBLOCKCODE$Quote;
4698 $Block
4699 ${ContentType}SRCBLOCKCODE
4700 BLOCKCGISCRIPTORSRCBLOCK
4702 next;
4705 # Handle files
4706 $NewDirective .= <<"BLOCKCGISCRIPTORSRCFILES";
4707 # Read $ThisSRCfile
4708 open(SCRIPTINGSOURCE, "<$ThisSRCfile") || main::dieHandler(16, "$ThisSRCfILE: \$!");
4709 while(<SCRIPTINGSOURCE>)
4711 print $SCRIPTINGINPUT{$ContentType} \$_;
4713 close(SCRIPTINGSOURCE);
4715 BLOCKCGISCRIPTORSRCFILES
4719 # Add the directive
4720 if($directive)
4722 $NewDirective .= <<"BLOCKCGISCRIPTORINSERT";
4723 print $SCRIPTINGINPUT{$ContentType} <<$Quote${ContentType}DIRECTIVECODE$Quote;
4724 $directive
4725 ${ContentType}DIRECTIVECODE
4726 BLOCKCGISCRIPTORINSERT
4730 $NewDirective .= <<"BLOCKCGISCRIPTORSELECT";
4731 # Select STDOUT filehandle
4732 select(STDOUT); \$|=1;
4733 BLOCKCGISCRIPTORSELECT
4735 # Ready
4736 return $NewDirective;
4739 sub CloseAllForeignScripts # Call CloseForeignScript on all open scripts
4741 my $ContentType;
4742 foreach $ContentType (keys(%SCRIPTINGINPUT))
4744 my $directive = CloseForeignScript($ContentType);
4745 print STDERR "\nDirective $CGI_Date: ", $directive;
4746 CGIexecute->evaluate($directive);
4751 # End of handling foreign (external) scripting languages.
4753 ############################################################################
4755 # A subroutine to handle "nested" quotes, it cuts off the leading
4756 # item or quoted substring
4757 # E.g.,
4758 # ' A_word and more words' -> @('A_word', ' and more words')
4759 # '"quoted string" The rest' -> @('quoted string', ' The rest')
4760 # (this is needed for parsing the <TAGS> and their attributes)
4761 my $SupportedQuotes = "\'\"\`\(\{\[";
4762 my %QuotePairs = ('('=>')','['=>']','{'=>'}'); # Brackets
4763 sub ExtractQuotedItem # ($String) -> @($QuotedString, $RestOfString)
4765 my @Result = ();
4766 my $String = shift || return @Result;
4768 if($String =~ /^\s*([\w\/\-\.]+)/is)
4770 push(@Result, $1, $');
4772 elsif($String =~ /^\s*(\\?)([\Q$SupportedQuotes\E])/is)
4774 my $BackSlash = $1 || "";
4775 my $OpenQuote = $2;
4776 my $CloseQuote = $OpenQuote;
4777 $CloseQuote = $QuotePairs{$OpenQuote} if $QuotePairs{$OpenQuote};
4779 if($BackSlash)
4781 $String =~ /^\s*\\\Q$OpenQuote\E/i;
4782 my $Onset = $';
4783 $Onset =~ /\\\Q$CloseQuote\E/i;
4784 my $Rest = $';
4785 my $Item = $`;
4786 push(@Result, $Item, $Rest);
4789 else
4791 $String =~ /^\s*\Q$OpenQuote\E([^\Q$CloseQuote\E]*)\Q$CloseQuote\E/i;
4792 push(@Result, $1, $');
4795 else
4797 push(@Result, "", $String);
4799 return @Result;
4802 # Now, start with the real work
4804 # Control the output of the Content-type: text/html\n\n message
4805 my $SupressContentType = 0;
4807 # Process a file
4808 sub ProcessFile # ($file_path)
4810 my $file_path = shift || return 0;
4813 # Generate a unique file handle (for recursions)
4814 my @SRClist = ();
4815 my $FileHandle = "file";
4816 my $n = 0;
4817 while(!eof($FileHandle.$n)) {++$n;};
4818 $FileHandle .= $n;
4820 # Start HTML output
4821 # Use the default Content-type if this is NOT a raw file
4822 unless(($RawFilePattern && $ENV{'PATH_INFO'} =~ m@($RawFilePattern)$@i)
4823 || $SupressContentType)
4825 $ENV{'PATH_INFO'} =~ m@($FilePattern)$@i;
4826 my $ContentType = $ContentTypeTable{$1};
4827 print "Content-type: $ContentType\n";
4828 if(%SETCOOKIELIST && keys(%SETCOOKIELIST))
4830 foreach my $name (keys(%SETCOOKIELIST))
4832 my $value = $SETCOOKIELIST{$name};
4833 print "Set-Cookie: $name=$value\n";
4835 # Cookies are set only ONCE
4836 %SETCOOKIELIST = ();
4838 print "\n";
4839 $SupressContentType = 1; # Content type has been printed
4843 # Get access to the actual data. This can be from RAM (by way of an
4844 # environment variable) or by opening a file.
4846 # Handle the use of RAM images (file-data is stored in the
4847 # $CGI_FILE_CONTENTS environment variable)
4848 # Note that this environment variable will be cleared, i.e., it is strictly for
4849 # single-use only!
4850 if($ENV{$CGI_FILE_CONTENTS})
4852 # File has been read already
4853 $_ = $ENV{$CGI_FILE_CONTENTS};
4854 # Sorry, you have to do the reading yourself (dynamic document creation?)
4855 # NOTE: you must read the whole document at once
4856 if($_ eq '-')
4858 $_ = eval("\@_=('$file_path'); do{$ENV{$CGI_DATA_ACCESS_CODE}}");
4860 else # Clear environment variable
4862 $ENV{$CGI_FILE_CONTENTS} = '-';
4865 # Open Only PLAIN TEXT files (or STDIN) and NO executable files (i.e., scripts).
4866 # THIS IS A SECURITY FEATURE!
4867 elsif($file_path eq '-' || (-e "$file_path" && -r _ && -T _ && -f _ && ! (-x _ || -X _) ))
4869 open($FileHandle, $file_path) || dieHandler(17, "<h2>File not found</h2>\n");
4870 push(@OpenFiles, $file_path);
4871 $_ = <$FileHandle>; # Read first line
4873 else
4875 print "<h2>File not found</h2>\n";
4876 dieHandler(18, "$file_path\n");
4879 $| = 1; # Flush output buffers
4881 # Initialize variables
4882 my $METAarguments = ""; # The CGI arguments from the latest META tag
4883 my @METAvalues = (); # The ''-quoted CGI values from the latest META tag
4884 my $ClosedTag = 0; # <TAG> </TAG> versus <TAG/>
4887 # Send document to output
4888 # Process the requested document.
4889 # Do a loop BEFORE reading input again (this catches the RAM/Database
4890 # type of documents).
4891 do {
4894 # Handle translations if needed
4896 performTranslation(\$_) if $TranslationPaths;
4898 # Catch <SCRIPT LANGUAGE="PERL" TYPE="text/ssperl" > directives in $_
4899 # There can be more than 1 <SCRIPT> or META tags on a line
4900 while(/\<\s*(SCRIPT|META|DIV|INS)\s/is)
4902 my $directive = "";
4903 # Store rest of line
4904 my $Before = $`;
4905 my $ScriptTag = $&;
4906 my $After = $';
4907 my $TagType = uc($1);
4908 # The before part can be send to the output
4909 print $Before;
4911 # Read complete Tag from after and/or file
4912 until($After =~ /([^\\])\>/)
4914 $After .= <$FileHandle>;
4915 performTranslation(\$After) if $TranslationPaths;
4918 if($After =~ /([^\\])\>/)
4920 $ScriptTag .= $`.$&; # Keep the Script Tag intact
4921 $After = $';
4923 else
4925 dieHandler(19, "Closing > not found\n");
4928 # The tag could be closed by />, we handle this in the XML way
4929 # and don't process any content (we ignore whitespace)
4930 $ClosedTag = ($ScriptTag =~ m@[^\\]/\s*\>\s*$@) ? 1 : 0;
4933 # TYPE or CLASS?
4934 my $TypeName = ($TagType =~ /META/is) ? "CONTENT" : "TYPE";
4935 $TypeName = "CLASS" if $TagType eq 'DIV' || $TagType eq 'INS';
4937 # Parse <SCRIPT> or <META> directive
4938 # If NOT (TYPE|CONTENT)="text/ssperl" (i.e., $ServerScriptContentType),
4939 # send the line to the output and go to the next loop
4940 my $CurrentContentType = "";
4941 if($ScriptTag =~ /(^|\s)$TypeName\s*=\s*/is)
4943 my ($Type) = ExtractQuotedItem($');
4944 $Type =~ /^\s*([\w\/\-]+)\s*[\,\;]?/;
4945 $CurrentContentType = lc($1); # Note: mime-types are "case-less"
4946 # CSS classes are aliases of $ServerScriptContentType
4947 if($TypeName eq "CLASS" && $CurrentContentType eq $ServerScriptContentClass)
4949 $CurrentContentType = $ServerScriptContentType;
4954 # Not a known server-side content type, print and continue
4955 unless(($CurrentContentType =~
4956 /$ServerScriptContentType|$ShellScriptContentType/is) ||
4957 $ScriptingLanguages{$CurrentContentType})
4959 print $ScriptTag;
4960 $_ = $After;
4961 next;
4965 # A known server-side content type, evaluate
4967 # First, handle \> and \<
4968 $ScriptTag =~ s/\\\>/\>/isg;
4969 $ScriptTag =~ s/\\\</\</isg;
4971 # Extract the CGI, SRC, ID, IF and UNLESS attributes
4972 my %ScriptTagAttributes = ();
4973 while($ScriptTag =~ /(^|\s)(CGI|IF|UNLESS|SRC|ID)\s*=\s*/is)
4975 my $Attribute = $2;
4976 my $Rest = $';
4977 my $Value = "";
4978 ($Value, $ScriptTag) = ExtractQuotedItem($Rest);
4979 $ScriptTagAttributes{uc($Attribute)} = $Value;
4983 # The attribute used to define the CGI variables
4984 # Extract CGI-variables from
4985 # <META CONTENT="text/ssperl; CGI='' SRC=''">
4986 # <SCRIPT TYPE='text/ssperl' CGI='' SRC=''>
4987 # <DIV CLASS='ssperl' CGI='' SRC='' ID=""> tags
4988 # <INS CLASS='ssperl' CGI='' SRC='' ID=""> tags
4989 if($ScriptTagAttributes{'CGI'})
4991 @ARGV = (); # Reset ARGV
4992 $ARGC = 0;
4993 $METAarguments = ""; # Reset the META CGI arguments
4994 @METAvalues = ();
4995 my $Meta_CGI = $ScriptTagAttributes{'CGI'};
4997 # Process default values of variables ($<name> = 'default value')
4998 # Allowed quotes are '', "", ``, (), [], and {}
4999 while($Meta_CGI =~ /(^\s*|[^\\])([\$\@\%]?)([\w\-]+)\s*/is)
5001 my $varType = $2 || '$'; # Variable or list
5002 my $name = $3; # The Name
5003 my $default = "";
5004 $Meta_CGI = $';
5006 if($Meta_CGI =~ /^\s*\=\s*/is)
5008 # Locate (any) default value
5009 ($default, $Meta_CGI) = ExtractQuotedItem($'); # Cut the parameter from the CGI
5011 $RemainingTag = $Meta_CGI;
5014 # Define CGI (or ENV) variable, initalize it from the
5015 # Query string or the default value
5017 # Also construct the @ARGV and @_ arrays. This allows other (SRC=) Perl
5018 # scripts to access the CGI arguments defined in the META tag
5019 # (Not for CGI inside <SCRIPT> tags)
5020 if($varType eq '$')
5022 CGIexecute::defineCGIvariable($name, $default)
5023 || dieHandler(20, "INVALID CGI name/value pair ($name, $default)\n");
5024 push(@METAvalues, "'".${"CGIexecute::$name"}."'");
5025 # Add value to the @ARGV list
5026 push(@ARGV, ${"CGIexecute::$name"});
5027 ++$ARGC;
5029 elsif($varType eq '@')
5031 CGIexecute::defineCGIvariableList($name, $default)
5032 || dieHandler(21, "INVALID CGI name/value list pair ($name, $default)\n");
5033 push(@METAvalues, "'".join("'", @{"CGIexecute::$name"})."'");
5034 # Add value to the @ARGV list
5035 push(@ARGV, @{"CGIexecute::$name"});
5036 $ARGC = scalar(@CGIexecute::ARGV);
5038 elsif($varType eq '%')
5040 CGIexecute::defineCGIvariableHash($name, $default)
5041 || dieHandler(22, "INVALID CGI name/value hash pair ($name, $default)\n");
5042 my @PairList = map {"$_ => ".${"CGIexecute::$name"}{$_}} keys(%{"CGIexecute::$name"});
5043 push(@METAvalues, "'".join("'", @PairList)."'");
5044 # Add value to the @ARGV list
5045 push(@ARGV, %{"CGIexecute::$name"});
5046 $ARGC = scalar(@CGIexecute::ARGV);
5049 # Store the values for internal and later use
5050 $METAarguments .= "$varType".$name.","; # A string of CGI variable names
5052 push(@METAvalues, "\'".eval("\"$varType\{CGIexecute::$name\}\"")."\'"); # ALWAYS add '-quotes around values
5057 # The IF (conditional execution) Attribute
5058 # Evaluate the condition and stop unless it evaluates to true
5059 if($ScriptTagAttributes{'IF'})
5061 my $IFcondition = $ScriptTagAttributes{'IF'};
5063 # Convert SCRIPT calls, ./<script>
5064 $IFcondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5066 # Convert FILE calls, ~/<file>
5067 $IFcondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5069 # Block execution if necessary
5070 unless(CGIexecute->evaluate($IFcondition))
5072 %ScriptTagAttributes = ();
5073 $CurrentContentType = "";
5077 # The UNLESS (conditional execution) Attribute
5078 # Evaluate the condition and stop if it evaluates to true
5079 if($ScriptTagAttributes{'UNLESS'})
5081 my $UNLESScondition = $ScriptTagAttributes{'UNLESS'};
5083 # Convert SCRIPT calls, ./<script>
5084 $UNLESScondition =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5086 # Convert FILE calls, ~/<file>
5087 $UNLESScondition =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5089 # Block execution if necessary
5090 if(CGIexecute->evaluate($UNLESScondition))
5092 %ScriptTagAttributes = ();
5093 $CurrentContentType = "";
5097 # The SRC (Source File) Attribute
5098 # Extract any source script files and add them in
5099 # front of the directive
5100 # The SRC list should be emptied
5101 @SRClist = ();
5102 my $SRCtag = "";
5103 my $Prefix = 1;
5104 my $PrefixDirective = "";
5105 my $PostfixDirective = "";
5106 # There is a SRC attribute
5107 if($ScriptTagAttributes{'SRC'})
5109 $SRCtag = $ScriptTagAttributes{'SRC'};
5110 # Remove "file://" prefixes
5111 $SRCtag =~ s@([^\w\/\\]|^)file\://([^\s\/\@\=])@$1$2@gis;
5112 # Expand script filenames "./Script"
5113 $SRCtag =~ s@([^\w\/\\]|^)\./([^\s\/\@\=])@$1$SCRIPT_SUB/$2@gis;
5114 # Expand script filenames "~/Script"
5115 $SRCtag =~ s@([^\w\/\\]|^)\~/([^\s\/\@\=])@$1$HOME_SUB/$2@gis;
5118 # File source tags
5119 while($SRCtag =~ /\S/is)
5121 my $SRCdirective = "";
5123 # Pseudo file, just a switch to go from PREFIXING to POSTFIXING
5124 # SRC files
5125 if($SRCtag =~ /^[\s\;\,]*(POSTFIX|PREFIX)([^$FileAllowedChars]|$)/is)
5127 my $InsertionPlace = $1;
5128 $SRCtag = $2.$';
5130 $Prefix = $InsertionPlace =~ /POSTFIX/i ? 0 : 1;
5131 # Go to next round
5132 next;
5134 # {}-blocks are just evaluated by "do"
5135 elsif($SRCtag =~ /^[\s\;\,]*\{/is)
5137 my $SRCblock = $';
5138 if($SRCblock =~ /\}[\s\;\,]*([^\}]*)$/is)
5140 $SRCblock = $`;
5141 $SRCtag = $1.$';
5142 # SAFEqx shell script blocks
5143 if($CurrentContentType =~ /$ShellScriptContentType/is)
5145 # Handle ''-quotes inside the script
5146 $SRCblock =~ s/[\']/\\$&/gis;
5148 $SRCblock = "print do { SAFEqx(\'".$SRCblock."\'); };'';";
5149 $SRCdirective .= $SRCblock."\n";
5151 # do { SRCblocks }
5152 elsif($CurrentContentType =~ /$ServerScriptContentType/is)
5154 $SRCblock = "print do { $SRCblock };'';";
5155 $SRCdirective .= $SRCblock."\n";
5157 else # The interpreter should handle this
5159 push(@SRClist, "{ $SRCblock }");
5163 else
5164 { dieHandler(23, "Closing \} missing\n");};
5166 # Files are processed as Text or Executable files
5167 elsif($SRCtag =~ /[\s\;\,]*([$FileAllowedChars]+)[\;\,\s]*/is)
5169 my $SrcFile = $1;
5170 $SRCtag = $';
5172 # We are handling one of the external interpreters
5173 if($ScriptingLanguages{$CurrentContentType})
5175 push(@SRClist, $SrcFile);
5177 # We are at the start of a DIV tag, just load all SRC files and/or URL's
5178 elsif($TagType eq 'DIV' || $TagType eq 'INS') # All files are prepended in DIV's
5180 # $SrcFile is a URL pointing to an HTTP or FTP server
5181 if($SrcFile =~ m!^([a-z]+)\://!)
5183 my $URLoutput = CGIscriptor::read_url($SrcFile);
5184 $SRCdirective .= $URLoutput;
5186 # SRC file is an existing file
5187 elsif(-e "$SrcFile")
5189 open(DIVSOURCE, "<$SrcFile") || dieHandler(24, "<$SrcFile: $!\n");
5190 my $Content;
5191 while(sysread(DIVSOURCE, $Content, 1024) > 0)
5193 $SRCdirective .= $Content;
5195 close(DIVSOURCE);
5198 # Executable files are executed as
5199 # `$SrcFile 'ARGV[0]' 'ARGV[1]'`
5200 elsif(-x "$SrcFile")
5202 $SRCdirective .= "print \`$SrcFile @METAvalues\`;'';\n";
5204 # Handle 'standard' files, using ProcessFile
5205 elsif((-T "$SrcFile" || $ENV{$CGI_FILE_CONTENTS})
5206 && $SrcFile =~ m@($FilePattern)$@) # A recursion
5209 # Do not process still open files because it can lead
5210 # to endless recursions
5211 if(grep(/^$SrcFile$/, @OpenFiles))
5212 { dieHandler(25, "$SrcFile allready opened (endless recursion)\n")};
5213 # Prepare meta arguments
5214 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5215 # Process the file
5216 $SRCdirective .= "main::ProcessFile(\'$SrcFile\');'';\n";
5218 elsif($SrcFile =~ m!^([a-z]+)\://!) # URL's are loaded and printed
5220 $SRCdirective .= GET_URL($SrcFile);
5222 elsif(-T "$SrcFile") # Textfiles are "do"-ed (Perl execution)
5224 $SRCdirective .= '@ARGV = (' .$METAarguments.");\n" if $METAarguments;
5225 $SRCdirective .= "do \'$SrcFile\';'';\n";
5227 else # This one could not be resolved (should be handled by BinaryMapFile)
5229 $SRCdirective .= 'print "'.$SrcFile.' cannot be used"'."\n";
5234 # Postfix or Prefix
5235 if($Prefix)
5237 $PrefixDirective .= $SRCdirective;
5239 else
5241 $PostfixDirective .= $SRCdirective;
5244 # The prefix should be handled immediately
5245 $directive .= $PrefixDirective;
5246 $PrefixDirective = "";
5250 # Handle the content of the <SCRIPT></SCRIPT> tags
5251 # Do not process the content of <SCRIPT/>
5252 if($TagType =~ /SCRIPT/is && !$ClosedTag) # The <SCRIPT> TAG
5254 my $EndScriptTag = "";
5256 # Execute SHELL scripts with SAFEqx()
5257 if($CurrentContentType =~ /$ShellScriptContentType/is)
5259 $directive .= "SAFEqx(\'";
5262 # Extract Program
5263 while($After !~ /\<\s*\/SCRIPT[^\>]*\>/is && !eof($FileHandle))
5265 $After .= <$FileHandle>;
5266 performTranslation(\$After) if $TranslationPaths;
5269 if($After =~ /\<\s*\/SCRIPT[^\>]*\>/is)
5271 $directive .= $`;
5272 $EndScriptTag = $&;
5273 $After = $';
5275 else
5277 dieHandler(26, "Missing </SCRIPT> end tag in $ENV{'PATH_INFO'}\n");
5280 # Process only when content should be executed
5281 if($CurrentContentType)
5284 # Remove all comments from Perl scripts
5285 # (NOT from OS shell scripts)
5286 $directive =~ s/[^\\\$]\#[^\n\f\r]*([\n\f\r])/$1/g
5287 if $CurrentContentType =~ /$ServerScriptContentType/i;
5289 # Convert SCRIPT calls, ./<script>
5290 $directive =~ s@([\W]|^)\./([\S])@$1$SCRIPT_SUB$2@g;
5292 # Convert FILE calls, ~/<file>
5293 $directive =~ s@([\W])\~/([\S])@$1$HOME_SUB$2@g;
5295 # Execute SHELL scripts with SAFEqx(), closing bracket
5296 if($CurrentContentType =~ /$ShellScriptContentType/i)
5298 # Handle ''-quotes inside the script
5299 $directive =~ /SAFEqx\(\'/;
5300 $directive = $`.$&;
5301 my $Executable = $';
5302 $Executable =~ s/[\']/\\$&/gs;
5304 $directive .= $Executable."\');"; # Closing bracket
5307 else
5309 $directive = "";
5312 # Handle the content of the <DIV></DIV> tags
5313 # Do not process the content of <DIV/>
5314 elsif(($TagType eq 'DIV' || $TagType eq 'INS') && !$ClosedTag) # The <DIV> TAGs
5316 my $EndScriptTag = "";
5318 # Extract Text
5319 while($After !~ /\<\s*\/$TagType[^\>]*\>/is && !eof($FileHandle))
5321 $After .= <$FileHandle>;
5322 performTranslation(\$After) if $TranslationPaths;
5325 if($After =~ /\<\s*\/$TagType[^\>]*\>/is)
5327 $directive .= $`;
5328 $EndScriptTag = $&;
5329 $After = $';
5331 else
5333 dieHandler(27, "Missing </$TagType> end tag in $ENV{'PATH_INFO'}\n");
5336 # Add the Postfixed directives (but only when it contains something printable)
5337 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5338 $PostfixDirective = "";
5341 # Process only when content should be handled
5342 if($CurrentContentType)
5345 # Get the name (ID), and clean it (i.e., remove anything that is NOT part of
5346 # a valid Perl name). Names should not contain $, but we can handle it.
5347 my $name = $ScriptTagAttributes{'ID'};
5348 $name =~ /^\s*[\$\@\%]?([\w\-]+)/;
5349 $name = $1;
5351 # Assign DIV contents to $NAME value OUTSIDE the CGI values!
5352 CGIexecute::defineCGIexecuteVariable($name, $directive);
5353 $directive = "";
5356 # Nothing to execute
5357 $directive = "";
5361 # Handle Foreign scripting languages
5362 if($ScriptingLanguages{$CurrentContentType})
5364 my $newDirective = "";
5365 $newDirective .= OpenForeignScript($CurrentContentType); # Only if not already done
5366 $newDirective .= PrefixForeignScript($CurrentContentType);
5367 $newDirective .= InsertForeignScript($CurrentContentType, $directive, @SRClist);
5368 $newDirective .= PostfixForeignScript($CurrentContentType);
5369 $newDirective .= CloseForeignScript($CurrentContentType); # This shouldn't be necessary
5371 $newDirective .= '"";';
5373 $directive = $newDirective;
5377 # Add the Postfixed directives (but only when it contains something printable)
5378 $directive .= "\n".$PostfixDirective if $PostfixDirective =~ /\S/;
5379 $PostfixDirective = "";
5382 # EXECUTE the script and print the results
5384 # Use this to debug the program
5385 # print STDERR "Directive $CGI_Date: \n", $directive, "\n\n";
5387 my $Result = CGIexecute->evaluate($directive) if $directive; # Evaluate as PERL code
5388 $Result =~ s/\n$//g; # Remove final newline
5390 # Print the Result of evaluating the directive
5391 # (this will handle LARGE, >64 kB output)
5392 my $BytesWritten = 1;
5393 while($Result && $BytesWritten)
5395 $BytesWritten = syswrite(STDOUT, $Result, 64);
5396 $Result = substr($Result, $BytesWritten);
5398 # print $Result; # Could be used instead of above code
5400 # Store result if wanted, i.e., if $CGIscriptorResults has been
5401 # defined in a <META> tag.
5402 push(@CGIexecute::CGIscriptorResults, $Result)
5403 if exists($default_values{'CGIscriptorResults'});
5405 # Process the rest of the input line (this could contain
5406 # another directive)
5407 $_ = $After;
5409 print $_;
5410 } while(<$FileHandle>); # Read and Test AFTER first loop!
5412 close ($FileHandle);
5413 dieHandler(28, "Error in recursion\n") unless pop(@OpenFiles) == $file_path;
5417 ###############################################################################
5419 # Call the whole package
5421 sub Handle_Request
5423 my $file_path = "";
5425 # Initialization Code
5426 Initialize_Request();
5428 # SECURITY: ACCESS CONTROL
5429 Access_Control();
5431 # Read the POST part of the query, if there is one
5432 Get_POST_part_of_query();
5434 # Start (HTML) output and logging
5435 $file_path = Initialize_output();
5437 # Check login access or divert to login procedure
5438 $Use_Login = Log_In_Access();
5439 $file_path = $Use_Login if $Use_Login;
5441 # Record which files are still open (to avoid endless recursions)
5442 my @OpenFiles = ();
5444 # Record whether the default HTML ContentType has already been printed
5445 # but only if the SERVER uses HTTP or some other protocol that might interpret
5446 # a content MIME type.
5448 $SupressContentType = !("$ENV{'SERVER_PROTOCOL'}" =~ /($ContentTypeServerProtocols)/i);
5450 # Process the specified file
5451 ProcessFile($file_path) if $file_path ne $SS_PUB;
5453 # Cleanup all open external (foreign) interpreters
5454 CloseAllForeignScripts();
5457 "" # SUCCESS
5460 # Make a single call to handle an (empty) request
5461 Handle_Request();
5464 # END OF PACKAGE MAIN
5467 ####################################################################################
5469 # The CGIEXECUTE PACKAGE
5471 ####################################################################################
5473 # Isolate the evaluation of directives as PERL code from the rest of the program.
5474 # Remember that each package has its own name space.
5475 # Note that only the FIRST argument of execute->evaluate is actually evaluated,
5476 # all other arguments are accessible inside the first argument as $_[0] to $_[$#_].
5478 package CGIexecute;
5480 sub evaluate
5482 my $self = shift;
5483 my $directive = shift;
5484 $directive = eval($directive);
5485 warn $@ if $@; # Write an error message to STDERR
5486 $directive; # Return value of directive
5490 # defineCGIexecuteVariable($name [, $value]) -> 0/1
5492 # Define and intialize variables inside CGIexecute
5493 # Does no sanity checking, for internal use only
5495 sub defineCGIexecuteVariable # ($name [, $value]) -> 0/1
5497 my $name = shift || return 0; # The Name
5498 my $value = shift || ""; # The value
5500 ${$name} = $value;
5502 return 1;
5505 # Protect certain CGI variables values when set internally
5506 # If not defined internally, there will be no variable set AT ALL
5507 my %CGIprotectedVariable = ();
5508 sub ProtectCGIvariable # ($name) -> 0/1
5510 my $name = shift || "";
5511 return 0 unless $name && $name =~ /\w/;
5513 ++$CGIprotectedVariable{$name};
5515 return $CGIprotectedVariable{$name};
5518 # defineCGIvariable($name [, $default]) -> 0/1
5520 # Define and intialize CGI variables
5521 # Tries (in order) $ENV{$name}, the Query string and the
5522 # default value.
5523 # Removes all '-quotes etc.
5525 sub defineCGIvariable # ($name [, $default]) -> 0/1
5527 my $name = shift || return 0; # The Name
5528 my $default = shift || ""; # The default value
5530 # Protect variables set internally
5531 return 1 if !$name || exists($CGIprotectedVariable{$name});
5533 # Remove \-quoted characters
5534 $default =~ s/\\(.)/$1/g;
5535 # Store default values
5536 $::default_values{$name} = $default if $default;
5538 # Process variables
5539 my $temp = undef;
5540 # If there is a user supplied value, it replaces the
5541 # default value.
5543 # Environment values have precedence
5544 if(exists($ENV{$name}))
5546 $temp = $ENV{$name};
5548 # Get name and its value from the query string
5549 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5551 $temp = ::YOUR_CGIPARSE($name);
5553 # Defined values must exist for security
5554 elsif(!exists($::default_values{$name}))
5556 $::default_values{$name} = undef;
5559 # SECURITY, do not allow '- and `-quotes in
5560 # client values.
5561 # Remove all existing '-quotes
5562 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5563 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
5564 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
5565 # If $temp is empty, use the default value (if it exists)
5566 unless($temp =~ /\S/ || length($temp) > 0) # I.e., $temp is empty
5568 $temp = $::default_values{$name};
5569 # Remove all existing '-quotes
5570 $temp =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5571 $temp =~ s/[\']/&#8217;/igs; # Remove all single quotes
5572 $temp =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
5574 else # Store current CGI values and remove defaults
5576 $::default_values{$name} = $temp;
5578 # Define the CGI variable and its value (in the execute package)
5579 ${$name} = $temp;
5581 # return SUCCES
5582 return 1;
5585 sub defineCGIvariableList # ($name [, $default]) -> 0/1)
5587 my $name = shift || return 0; # The Name
5588 my $default = shift || ""; # The default value
5590 # Protect variables set internally
5591 return 1 if !$name || exists($CGIprotectedVariable{$name});
5593 # Defined values must exist for security
5594 if(!exists($::default_values{$name}))
5596 $::default_values{$name} = $default;
5599 my @temp = ();
5602 # For security:
5603 # Environment values have precedence
5604 if(exists($ENV{$name}))
5606 push(@temp, $ENV{$name});
5608 # Get name and its values from the query string
5609 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5611 push(@temp, ::YOUR_CGIPARSE($name, 1)); # Extract LIST
5613 else
5615 push(@temp, $::default_values{$name});
5619 # SECURITY, do not allow '- and `-quotes in
5620 # client values.
5621 # Remove all existing '-quotes
5622 @temp = map {s/([\r\f]+\n)/\n/g; $_} @temp; # Only \n is allowed
5623 @temp = map {s/[\']/&#8217;/igs; $_} @temp; # Remove all single quotes
5624 @temp = map {s/[\`]/&#8216;/igs; $_} @temp; # Remove all backtick quotes
5626 # Store current CGI values and remove defaults
5627 $::default_values{$name} = $temp[0];
5629 # Define the CGI variable and its value (in the execute package)
5630 @{$name} = @temp;
5632 # return SUCCES
5633 return 1;
5636 sub defineCGIvariableHash # ($name [, $default]) -> 0/1) Note: '$name{""} = $default';
5638 my $name = shift || return 0; # The Name
5639 my $default = shift || ""; # The default value
5641 # Protect variables set internally
5642 return 1 if !$name || exists($CGIprotectedVariable{$name});
5644 # Defined values must exist for security
5645 if(!exists($::default_values{$name}))
5647 $::default_values{$name} = $default;
5650 my %temp = ();
5653 # For security:
5654 # Environment values have precedence
5655 if(exists($ENV{$name}))
5657 $temp{""} = $ENV{$name};
5659 # Get name and its values from the query string
5660 elsif($ENV{QUERY_STRING} =~ /$name/) # $name is in the query string
5662 %temp = ::YOUR_CGIPARSE($name, -1); # Extract HASH table
5664 elsif($::default_values{$name} ne "")
5666 $temp{""} = $::default_values{$name};
5670 # SECURITY, do not allow '- and `-quotes in
5671 # client values.
5672 # Remove all existing '-quotes
5673 my $Key;
5674 foreach $Key (keys(%temp))
5676 $temp{$Key} =~ s/([\r\f]+\n)/\n/g; # Only \n is allowed
5677 $temp{$Key} =~ s/[\']/&#8217;/igs; # Remove all single quotes
5678 $temp{$Key} =~ s/[\`]/&#8216;/igs; # Remove all backtick quotes
5681 # Store current CGI values and remove defaults
5682 $::default_values{$name} = $temp{""};
5684 # Define the CGI variable and its value (in the execute package)
5685 %{$name} = ();
5686 my $tempKey;
5687 foreach $tempKey (keys(%temp))
5689 ${$name}{$tempKey} = $temp{$tempKey};
5692 # return SUCCES
5693 return 1;
5697 # SAFEqx('CommandString')
5699 # A special function that is a safe alternative to backtick quotes (and qx//)
5700 # with client-supplied CGI values. All CGI variables are surrounded by
5701 # single ''-quotes (except between existing \'\'-quotes, don't try to be
5702 # too smart). All variables are then interpolated. Simple (@) lists are
5703 # expanded with join(' ', @List), and simple (%) hash tables expanded
5704 # as a list of "key=value" pairs. Complex variables, e.g., @$var, are
5705 # evaluated in a scalar context (e.g., as scalar(@$var)). All occurrences of
5706 # $@% that should NOT be interpolated must be preceeded by a "\".
5707 # If the first line of the String starts with "#! interpreter", the
5708 # remainder of the string is piped into interpreter (after interpolation), i.e.,
5709 # open(INTERPRETER, "|interpreter");print INTERPRETER remainder;
5710 # just like in UNIX. There are some problems with quotes. Be carefull in
5711 # using them. You do not have access to the output of any piped (#!)
5712 # process! If you want such access, execute
5713 # <SCRIPT TYPE="text/osshell">echo "script"|interpreter</SCRIPT> or
5714 # <SCRIPT TYPE="text/ssperl">$resultvar = SAFEqx('echo "script"|interpreter');
5715 # </SCRIPT>.
5717 # SAFEqx ONLY WORKS WHEN THE STRING ITSELF IS SURROUNDED BY SINGLE QUOTES
5718 # (SO THAT IT IS NOT INTERPOLATED BEFORE IT CAN BE PROTECTED)
5719 sub SAFEqx # ('String') -> result of executing qx/"String"/
5721 my $CommandString = shift;
5722 my $NewCommandString = "";
5724 # Only interpolate when required (check the On/Off switch)
5725 unless($CGIscriptor::NoShellScriptInterpolation)
5728 # Handle existing single quotes around CGI values
5729 while($CommandString =~ /\'[^\']+\'/s)
5731 my $CurrentQuotedString = $&;
5732 $NewCommandString .= $`;
5733 $CommandString = $'; # The remaining string
5734 # Interpolate CGI variables between quotes
5735 # (e.g., '$CGIscriptorResults[-1]')
5736 $CurrentQuotedString =~
5737 s/(^|[^\\])([\$\@])((\w*)([\{\[][\$\@\%]?[\:\w\-]+[\}\]])*)/if(exists($main::default_values{$4})){
5738 "$1".eval("$2$3")}else{"$&"}/egs;
5740 # Combine result with previous result
5741 $NewCommandString .= $CurrentQuotedString;
5743 $CommandString = $NewCommandString.$CommandString;
5745 # Select known CGI variables and surround them with single quotes,
5746 # then interpolate all variables
5747 $CommandString =~
5748 s/(^|[^\\])([\$\@\%]+)((\w*)([\{\[][\w\:\$\"\-]+[\}\]])*)/
5749 if($2 eq '$' && exists($main::default_values{$4}))
5750 {"$1\'".eval("\$$3")."\'";}
5751 elsif($2 eq '@'){$1.join(' ', @{"$3"});}
5752 elsif($2 eq '%'){my $t=$1;map {$t.=" $_=".${"$3"}{$_}}
5753 keys(%{"$3"});$t}
5754 else{$1.eval("${2}$3");
5755 }/egs;
5757 # Remove backslashed [$@%]
5758 $CommandString =~ s/\\([\$\@\%])/$1/gs;
5761 # Debugging
5762 # return $CommandString;
5764 # Handle UNIX style "#! shell command\n" constructs as
5765 # a pipe into the shell command. The output cannot be tapped.
5766 my $ReturnValue = "";
5767 if($CommandString =~ /^\s*\#\!([^\f\n\r]+)[\f\n\r]/is)
5769 my $ShellScripts = $';
5770 my $ShellCommand = $1;
5771 open(INTERPRETER, "|$ShellCommand") || dieHandler(29, "\'$ShellCommand\' PIPE not opened: &!\n");
5772 select(INTERPRETER);$| = 1;
5773 print INTERPRETER $ShellScripts;
5774 close(INTERPRETER);
5775 select(STDOUT);$| = 1;
5777 # Shell scripts which are redirected to an existing named pipe.
5778 # The output cannot be tapped.
5779 elsif($CGIscriptor::ShellScriptPIPE)
5781 CGIscriptor::printSAFEqxPIPE($CommandString);
5783 else # Plain ``-backtick execution
5785 # Execute the commands
5786 $ReturnValue = qx/$CommandString/;
5788 return $ReturnValue;
5791 ####################################################################################
5793 # The CGIscriptor PACKAGE
5795 ####################################################################################
5797 # Isolate the evaluation of CGIscriptor functions, i.e., those prefixed with
5798 # "CGIscriptor::"
5800 package CGIscriptor;
5803 # The Interpolation On/Off switch
5804 my $NoShellScriptInterpolation = undef;
5805 # The ShellScript redirection pipe
5806 my $ShellScriptPIPE = undef;
5808 # Open a named PIPE for SAFEqx to receive ALL shell scripts
5809 sub RedirectShellScript # ('CommandString')
5811 my $CommandString = shift || undef;
5813 if($CommandString)
5815 $ShellScriptPIPE = "ShellScriptNamedPipe";
5816 open($ShellScriptPIPE, "|$CommandString")
5817 || main::dieHandler(30, "\'|$CommandString\' PIPE open failed: $!\n");
5819 else
5821 close($ShellScriptPIPE);
5822 $ShellScriptPIPE = undef;
5824 return $ShellScriptPIPE;
5827 # Print to redirected shell script pipe
5828 sub printSAFEqxPIPE # ("String") -> print return value
5830 my $String = shift || undef;
5832 select($ShellScriptPIPE); $| = 1;
5833 my $returnvalue = print $ShellScriptPIPE ($String);
5834 select(STDOUT); $| = 1;
5836 return $returnvalue;
5839 # a pointer to CGIexecute::SAFEqx
5840 sub SAFEqx # ('String') -> result of qx/"String"/
5842 my $CommandString = shift;
5843 return CGIexecute::SAFEqx($CommandString);
5847 # a pointer to CGIexecute::defineCGIvariable
5848 sub defineCGIvariable # ($name[, $default]) ->0/1
5850 my $name = shift;
5851 my $default = shift;
5852 return CGIexecute::defineCGIvariable($name, $default);
5856 # a pointer to CGIexecute::defineCGIvariable
5857 sub defineCGIvariableList # ($name[, $default]) ->0/1
5859 my $name = shift;
5860 my $default = shift;
5861 return CGIexecute::defineCGIvariableList($name, $default);
5865 # a pointer to CGIexecute::defineCGIvariable
5866 sub defineCGIvariableHash # ($name[, $default]) ->0/1
5868 my $name = shift;
5869 my $default = shift;
5870 return CGIexecute::defineCGIvariableHash($name, $default);
5874 # Decode URL encoded arguments
5875 sub URLdecode # (URL encoded input) -> string
5877 my $output = "";
5878 my $char;
5879 my $Value;
5880 foreach $Value (@_)
5882 my $EncodedValue = $Value; # Do not change the loop variable
5883 # Convert all "+" to " "
5884 $EncodedValue =~ s/\+/ /g;
5885 # Convert all hexadecimal codes (%FF) to their byte values
5886 while($EncodedValue =~ /\%([0-9A-F]{2})/i)
5888 $output .= $`.chr(hex($1));
5889 $EncodedValue = $';
5891 $output .= $EncodedValue; # The remaining part of $Value
5893 $output;
5896 # Encode arguments as URL codes.
5897 sub URLencode # (input) -> URL encoded string
5899 my $output = "";
5900 my $char;
5901 my $Value;
5902 foreach $Value (@_)
5904 my @CharList = split('', $Value);
5905 foreach $char (@CharList)
5907 if($char =~ /\s/)
5908 { $output .= "+";}
5909 elsif($char =~ /\w\-/)
5910 { $output .= $char;}
5911 else
5913 $output .= uc(sprintf("%%%2.2x", ord($char)));
5917 $output;
5920 # Extract the value of a CGI variable from the URL-encoded $string
5921 # Also extracts the data blocks from a multipart request. Does NOT
5922 # decode the multipart blocks
5923 sub CGIparseValue # (ValueName [, URL_encoded_QueryString [, \$QueryReturnReference]]) -> Decoded value
5925 my $ValueName = shift;
5926 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
5927 my $ReturnReference = shift || undef;
5928 my $output = "";
5930 if($QueryString =~ /(^|\&)$ValueName\=([^\&]*)(\&|$)/)
5932 $output = URLdecode($2);
5933 $$ReturnReference = $' if ref($ReturnReference);
5935 # Get multipart POST or PUT methods
5936 elsif($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
5938 my $MultipartType = $2;
5939 my $BoundaryString = $3;
5940 # Remove the boundary-string
5941 my $temp = $QueryString;
5942 $temp =~ /^\Q--$BoundaryString\E/m;
5943 $temp = $';
5945 # Identify the newline character(s), this is the first character in $temp
5946 my $NewLine = "\r\n"; # Actually, this IS the correct one
5947 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
5949 # Is this correct??? I have to check.
5950 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
5951 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
5952 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
5953 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
5956 # search through all data blocks
5957 while($temp =~ /^\Q--$BoundaryString\E/m)
5959 my $DataBlock = $`;
5960 $temp = $';
5961 # Get the empty line after the header
5962 $DataBlock =~ /$NewLine$NewLine/;
5963 $Header = $`;
5964 $output = $';
5965 my $Header = $`;
5966 $output = $';
5968 # Remove newlines from the header
5969 $Header =~ s/$NewLine/ /g;
5971 # Look whether this block is the one you are looking for
5972 # Require the quotes!
5973 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
5975 my $i;
5976 for($i=length($NewLine); $i; --$i)
5978 chop($output);
5980 # OK, get out
5981 last;
5983 # reinitialize the output
5984 $output = "";
5986 $$ReturnReference = $temp if ref($ReturnReference);
5988 elsif($QueryString !~ /(^|\&)$ValueName\=/) # The value simply isn't there
5990 return undef;
5991 $$ReturnReference = undef if ref($ReturnReference);
5993 else
5995 print "ERROR: $ValueName $main::ENV{'CONTENT_TYPE'}\n";
5997 return $output;
6001 # Get a list of values for the same ValueName. Uses CGIparseValue
6003 sub CGIparseValueList # (ValueName [, URL_encoded_QueryString]) -> List of decoded values
6005 my $ValueName = shift;
6006 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6007 my @output = ();
6008 my $RestQueryString;
6009 my $Value;
6010 while($QueryString &&
6011 (($Value = CGIparseValue($ValueName, $QueryString, \$RestQueryString))
6012 || defined($Value)))
6014 push(@output, $Value);
6015 $QueryString = $RestQueryString; # QueryString is consumed!
6017 # ready, return list with values
6018 return @output;
6021 sub CGIparseValueHash # (ValueName [, URL_encoded_QueryString]) -> Hash table of decoded values
6023 my $ValueName = shift;
6024 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6025 my $RestQueryString;
6026 my %output = ();
6027 while($QueryString && $QueryString =~ /(^|\&)$ValueName([\w]*)\=/)
6029 my $Key = $2;
6030 my $Value = CGIparseValue("$ValueName$Key", $QueryString, \$RestQueryString);
6031 $output{$Key} = $Value;
6032 $QueryString = $RestQueryString; # QueryString is consumed!
6034 # ready, return list with values
6035 return %output;
6038 sub CGIparseForm # ([URL_encoded_QueryString]) -> Decoded Form (NO multipart)
6040 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6041 my $output = "";
6043 $QueryString =~ s/\&/\n/g;
6044 $output = URLdecode($QueryString);
6046 $output;
6049 # Extract the header of a multipart CGI variable from the POST input
6050 sub CGIparseHeader # (ValueName [, URL_encoded_QueryString]) -> Decoded value
6052 my $ValueName = shift;
6053 my $QueryString = shift || $main::ENV{'QUERY_STRING'};
6054 my $output = "";
6056 if($main::ENV{'CONTENT_TYPE'} =~ m@(multipart/([\w\-]+)\;\s+boundary\=([\S]+))@i)
6058 my $MultipartType = $2;
6059 my $BoundaryString = $3;
6060 # Remove the boundary-string
6061 my $temp = $QueryString;
6062 $temp =~ /^\Q--$BoundaryString\E/m;
6063 $temp = $';
6065 # Identify the newline character(s), this is the first character in $temp
6066 my $NewLine = "\r\n"; # Actually, this IS the correct one
6067 unless($temp =~ /^(\-\-|\r\n)/) # However, you never realy can be sure
6069 $NewLine = "\n" if $temp =~ /^([\n])/; # Single Line Feed
6070 $NewLine = "\r" if $temp =~ /^([\r])/; # Single Return
6071 $NewLine = "\r\n" if $temp =~ /^(\r\n)/; # Double (CRLF, the correct one)
6072 $NewLine = "\n\r" if $temp =~ /^(\n\r)/; # Double
6075 # search through all data blocks
6076 while($temp =~ /^\Q--$BoundaryString\E/m)
6078 my $DataBlock = $`;
6079 $temp = $';
6080 # Get the empty line after the header
6081 $DataBlock =~ /$NewLine$NewLine/;
6082 $Header = $`;
6083 my $Header = $`;
6085 # Remove newlines from the header
6086 $Header =~ s/$NewLine/ /g;
6088 # Look whether this block is the one you are looking for
6089 # Require the quotes!
6090 if($Header =~ /name\s*=\s*[\"\']$ValueName[\"\']/m)
6092 $output = $Header;
6093 last;
6095 # reinitialize the output
6096 $output = "";
6099 return $output;
6103 # Checking variables for security (e.g., file names and email addresses)
6104 # File names are tested against the $::FileAllowedChars and $::BlockPathAccess variables
6105 sub CGIsafeFileName # FileName -> FileName or ""
6107 my $FileName = shift || "";
6108 return "" if $FileName =~ m?[^$::FileAllowedChars]?;
6109 return "" if $FileName =~ m!(^|/|\:)[\-\.]!;
6110 return "" if $FileName =~ m@\.\.\Q$::DirectorySeparator\E@; # Higher directory not allowed
6111 return "" if $FileName =~ m@\Q$::DirectorySeparator\E\.\.@; # Higher directory not allowed
6112 return "" if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@; # Invisible (blocked) file
6114 return $FileName;
6117 sub CGIsafeEmailAddress # email -> email or ""
6119 my $Email = shift || "";
6120 return "" unless $Email =~ m/^[\w\.\-]+[\@][\w\.\-\:]+$/;
6121 return $Email;
6124 # Get a URL from the web. Needs main::GET_URL($URL) function
6125 # (i.e., curl, snarf, or wget)
6126 sub read_url # ($URL) -> page/file
6128 my $URL = shift || return "";
6130 # Get the commands to read the URL, do NOT add a print command
6131 my $URL_command = main::GET_URL($URL, 1);
6132 # execute the commands, i.e., actually read it
6133 my $URLcontent = CGIexecute->evaluate($URL_command);
6135 # Ready, return the content.
6136 return $URLcontent;
6139 ################################################>>>>>>>>>>Start Remove
6141 # BrowseAllDirs(Directory, indexfile)
6143 # usage:
6144 # <SCRIPT TYPE='text/ssperl'>
6145 # CGIscriptor::BrowseAllDirs('Sounds', 'index.html', '\.wav$')
6146 # </SCRIPT>
6148 # Allows to browse all directories. Stops at '/'. If the directory contains
6149 # an indexfile, eg, index.html, that file will be used instead. Files must match
6150 # the $Pattern, if it is given. Default is
6151 # CGIscriptor::BrowseAllDirs('/', 'index.html', '')
6153 sub BrowseAllDirs # (Directory, indexfile, $Pattern) -> Print HTML code
6155 my $Directory = shift || '/';
6156 my $indexfile = shift || 'index.html';
6157 my $Pattern = shift || '';
6158 $Directory =~ s!/$!!g;
6160 # If the index directory exists, use that one
6161 if(-s "$::CGI_HOME$Directory/$indexfile")
6163 return main::ProcessFile("$::CGI_HOME$Directory/$indexfile");
6166 # No indexfile, continue
6167 my @DirectoryList = glob("$::CGI_HOME$Directory");
6168 $CurrentDirectory = shift(@DirectoryList);
6169 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6170 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6171 print "<h1>";
6172 print "$CurrentDirectory" if $CurrentDirectory;
6173 print "</h1>\n";
6175 opendir(BROWSE, "$::CGI_HOME$Directory") || main::dieHandler(31, "$::CGI_HOME$Directory $!");
6176 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6178 # Print directories
6179 my $file;
6180 print "<pre><ul TYPE='NONE'>\n";
6181 foreach $file (@AllFiles)
6183 next unless -d "$::CGI_HOME$Directory/$file";
6184 # Check whether this file should be visible
6185 next if $::BlockPathAccess &&
6186 "$Directory/$file/" =~ m@$::BlockPathAccess@;
6187 print "<dt><a href='$Directory/$file'>$file</a></dt>\n";
6189 print "</ul></pre>\n";
6191 # Print files
6192 print "<pre><ul TYPE='CIRCLE'>\n";
6193 my $TotalSize = 0;
6194 foreach $file (@AllFiles)
6196 next if $file =~ /^\./;
6197 next if -d "$::CGI_HOME$Directory/$file";
6198 next if -l "$::CGI_HOME$Directory/$file";
6199 # Check whether this file should be visible
6200 next if $::BlockPathAccess &&
6201 "$Directory/$file" =~ m@$::BlockPathAccess@;
6203 if(!$Pattern || $file =~ m@$Pattern@)
6205 my $Date = localtime($^T - (-M "$::CGI_HOME$Directory/$file")*3600*24);
6206 my $Size = -s "$::CGI_HOME$Directory/$file";
6207 $Size = sprintf("%6.0F kB", $Size/1024);
6208 my $Type = `file $::CGI_HOME$Directory/$file`;
6209 $Type =~ s@\s*$::CGI_HOME$Directory/$file\s*\:\s*@@ig;
6210 chomp($Type);
6212 print "<li>";
6213 print "<a href='$Directory/$file'>";
6214 printf("%-40s", "$file</a>");
6215 print "\t$Size\t$Date\t$Type";
6216 print "</li>\n";
6219 print "</ul></pre>";
6221 return 1;
6225 ################################################
6227 # BrowseDirs(RootDirectory [, Pattern, Start])
6229 # usage:
6230 # <SCRIPT TYPE='text/ssperl'>
6231 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', 'Speech', 'DIRECTORY')
6232 # </SCRIPT>
6234 # Allows to browse subdirectories. Start should be relative to the RootDirectory,
6235 # e.g., the full path of the directory 'Speech' is '~/Sounds/Speech'.
6236 # Only files which fit /$Pattern/ and directories are displayed.
6237 # Directories down or up the directory tree are supplied with a
6238 # GET request with the name of the CGI variable in the fourth argument (default
6239 # is 'BROWSEDIRS'). So the correct call for a subdirectory could be:
6240 # CGIscriptor::BrowseDirs('Sounds', '\.aifc$', $DIRECTORY, 'DIRECTORY')
6242 sub BrowseDirs # (RootDirectory [, Pattern, Start, CGIvariable, HTTPserver]) -> Print HTML code
6244 my $RootDirectory = shift; # || return 0;
6245 my $Pattern = shift || '\S';
6246 my $Start = shift || "";
6247 my $CGIvariable = shift || "BROWSEDIRS";
6248 my $HTTPserver = shift || '';
6250 $Start = CGIscriptor::URLdecode($Start); # Sometimes, too much has been encoded
6251 $Start =~ s@//+@/@g;
6252 $Start =~ s@[^/]+/\.\.@@ig;
6253 $Start =~ s@^\.\.@@ig;
6254 $Start =~ s@/\.$@@ig;
6255 $Start =~ s!/+$!!g;
6256 $Start .= "/" if $Start;
6258 my @Directory = glob("$::CGI_HOME/$RootDirectory/$Start");
6259 $CurrentDirectory = shift(@Directory);
6260 $CurrentDirectory = $' if $CurrentDirectory =~ m@(/\.\./)+@;
6261 $CurrentDirectory =~ s@^$::CGI_HOME@@g;
6262 print "<h1>";
6263 print "$CurrentDirectory" if $CurrentDirectory;
6264 print "</h1>\n";
6265 opendir(BROWSE, "$::CGI_HOME/$RootDirectory/$Start") || main::dieHandler(31, "$::CGI_HOME/$RootDirectory/$Start $!");
6266 my @AllFiles = sort grep(!/^([\.]+[^\.]|\~)/, readdir(BROWSE));
6268 # Print directories
6269 my $file;
6270 print "<pre><ul TYPE='NONE'>\n";
6271 foreach $file (@AllFiles)
6273 next unless -d "$::CGI_HOME/$RootDirectory/$Start$file";
6274 # Check whether this file should be visible
6275 next if $::BlockPathAccess &&
6276 "/$RootDirectory/$Start$file/" =~ m@$::BlockPathAccess@;
6278 my $NewURL = $Start ? "$Start$file" : $file;
6279 $NewURL = CGIscriptor::URLencode($NewURL);
6280 print "<dt><a href='";
6281 print "$ENV{SCRIPT_NAME}" if $ENV{SCRIPT_NAME} !~ m@[^\w+\-/]@;
6282 print "$ENV{PATH_INFO}?$CGIvariable=$NewURL'>$file</a></dt>\n";
6284 print "</ul></pre>\n";
6286 # Print files
6287 print "<pre><ul TYPE='CIRCLE'>\n";
6288 my $TotalSize = 0;
6289 foreach $file (@AllFiles)
6291 next if $file =~ /^\./;
6292 next if -d "$::CGI_HOME/$RootDirectory/$Start$file";
6293 next if -l "$::CGI_HOME/$RootDirectory/$Start$file";
6294 # Check whether this file should be visible
6295 next if $::BlockPathAccess &&
6296 "$::CGI_HOME/$RootDirectory/$Start$file" =~ m@$::BlockPathAccess@;
6298 if($file =~ m@$Pattern@)
6300 my $Date = localtime($^T - (-M "$::CGI_HOME/$RootDirectory/$Start$file")*3600*24);
6301 my $Size = -s "$::CGI_HOME/$RootDirectory/$Start$file";
6302 $Size = sprintf("%6.0F kB", $Size/1024);
6303 my $Type = `file $::CGI_HOME/$RootDirectory/$Start$file`;
6304 $Type =~ s@\s*$::CGI_HOME/$RootDirectory/$Start$file\s*\:\s*@@ig;
6305 chomp($Type);
6307 print "<li>";
6308 if($HTTPserver =~ /^\s*[\.\~]\s*$/)
6310 print "<a href='$RootDirectory/$Start$file'>";
6312 elsif($HTTPserver)
6314 print "<a href='$HTTPserver/$RootDirectory/$Start$file'>";
6316 printf("%-40s", "$file</a>") if $HTTPserver;
6317 printf("%-40s", "$file") unless $HTTPserver;
6318 print "\t$Size\t$Date\t$Type";
6319 print "</li>\n";
6322 print "</ul></pre>";
6324 return 1;
6328 # ListDocs(Pattern [,ListType])
6330 # usage:
6331 # <SCRIPT TYPE=text/ssperl>
6332 # CGIscriptor::ListDocs("/*", "dl");
6333 # </SCRIPT>
6335 # This subroutine is very usefull to manage collections of independent
6336 # documents. The resulting list will display the tree-like directory
6337 # structure. If this routine is too slow for online use, you can
6338 # store the result and use a link to that stored file.
6340 # List HTML and Text files with title and first header (HTML)
6341 # or filename and first meaningfull line (general text files).
6342 # The listing starts at the ServerRoot directory. Directories are
6343 # listed recursively.
6345 # You can change the list type (default is dl).
6346 # e.g.,
6347 # <dt><a href=<file.html>>title</a>
6348 # <dd>First Header
6349 # <dt><a href=<file.txt>>file.txt</a>
6350 # <dd>First meaningfull line of text
6352 sub ListDocs # ($Pattern [, prefix]) e.g., ("/Books/*", [, "dl"])
6354 my $Pattern = shift;
6355 $Pattern =~ /\*/;
6356 my $ListType = shift || "dl";
6357 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6358 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6359 my @FileList = glob("$::CGI_HOME$Pattern");
6360 my ($FileName, $Path, $Link);
6362 # Print List markers
6363 print "<$ListType>\n";
6365 # Glob all files
6366 File: foreach $FileName (@FileList)
6368 # Check whether this file should be visible
6369 next if $::BlockPathAccess && $FileName =~ m@$::BlockPathAccess@;
6371 # Recursively list files in all directories
6372 if(-d $FileName)
6374 $FileName =~ m@([^/]*)$@;
6375 my $DirName = $1;
6376 print "<$Prefix>$DirName\n";
6377 $Pattern =~ m@([^/]*)$@;
6378 &ListDocs("$`$DirName/$1", $ListType);
6379 next;
6381 # Use textfiles
6382 elsif(-T "$FileName")
6384 open(TextFile, $FileName) || next;
6386 # Ignore all other file types
6387 else
6388 { next;};
6390 # Get file path for link
6391 $FileName =~ /$::CGI_HOME/;
6392 print "<$Prefix><a href=$URL_root$'>";
6393 # Initialize all variables
6394 my $Line = "";
6395 my $TitleFound = 0;
6396 my $Caption = "";
6397 my $Title = "";
6398 # Read file and step through
6399 while(<TextFile>)
6401 chop $_;
6402 $Line = $_;
6403 # HTML files
6404 if($FileName =~ /\.ht[a-zA-Z]*$/i)
6406 # Catch Title
6407 while(!$Title)
6409 if($Line =~ m@<title>([^<]*)</title>@i)
6411 $Title = $1;
6412 $Line = $';
6414 else
6416 $Line .= <TextFile> || goto Print;
6417 chop $Line;
6420 # Catch First Header
6421 while(!$Caption)
6423 if($Line =~ m@</h1>@i)
6425 $Caption = $`;
6426 $Line = $';
6427 $Caption =~ m@<h1>@i;
6428 $Caption = $';
6429 $Line = $`.$Caption.$Line;
6431 else
6433 $Line .= <TextFile> || goto Print;
6434 chop $Line;
6438 # Other text files
6439 else
6441 # Title equals file name
6442 $FileName =~ /([^\/]+)$/;
6443 $Title = $1;
6444 # Catch equals First Meaningfull line
6445 while(!$Caption)
6447 if($Line =~ /[A-Z]/ &&
6448 ($Line =~ /subject|title/i || $Line =~ /^[\w,\.\s\?\:]+$/)
6449 && $Line !~ /Newsgroup/ && $Line !~ /\:\s*$/)
6451 $Line =~ s/\<[^\>]+\>//g;
6452 $Caption = $Line;
6454 else
6456 $Line = <TextFile> || goto Print;
6460 Print: # Print title and subject
6461 print "$Title</a>\n";
6462 print "<dd>$Caption\n" if $ListType eq "dl";
6463 $TitleFound = 0;
6464 $Caption = "";
6465 close TextFile;
6466 next File;
6469 # Print Closing List Marker
6470 print "</$ListType>\n";
6471 ""; # Empty return value
6475 # HTMLdocTree(Pattern [,ListType])
6477 # usage:
6478 # <SCRIPT TYPE=text/ssperl>
6479 # CGIscriptor::HTMLdocTree("/Welcome.html", "dl");
6480 # </SCRIPT>
6482 # The following subroutine is very usefull for checking large document
6483 # trees. Starting from the root (s), it reads all files and prints out
6484 # a nested list of links to all attached files. Non-existing or misplaced
6485 # files are flagged. This is quite a file-i/o intensive routine
6486 # so you would not like it to be accessible to everyone. If you want to
6487 # use the result, save the whole resulting page to disk and use a link
6488 # to this file.
6490 # HTMLdocTree takes an HTML file or file pattern and constructs nested lists
6491 # with links to *local* files (i.e., only links to the local server are
6492 # followed). The list entries are the document titles.
6493 # If the list type is <dl>, the first <H1> header is used too.
6494 # For each file matching the pattern, a list is made recursively of all
6495 # HTML documents that are linked from it and are stored in the same directory
6496 # or a sub-directory. Warnings are given for missing files.
6497 # The listing starts for the ServerRoot directory.
6498 # You can change the default list type <dl> (<dl>, <ul>, <ol>).
6500 %LinkUsed = ();
6502 sub HTMLdocTree # ($Pattern [, listtype])
6503 # e.g., ("/Welcome.html", [, "ul"])
6505 my $Pattern = shift;
6506 my $ListType = shift || "dl";
6507 my $Prefix = lc($ListType) eq "dl" ? "dt" : "li";
6508 my $URL_root = "http://$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}";
6509 my ($Filename, $Path, $Link);
6510 my %LocalLinks = {};
6512 # Read files (glob them for expansion of wildcards)
6513 my @FileList = glob("$::CGI_HOME$Pattern");
6514 foreach $Path (@FileList)
6516 # Get URL_path
6517 $Path =~ /$::CGI_HOME/;
6518 my $URL_path = $';
6519 # Check whether this file should be visible
6520 next if $::BlockPathAccess && $URL_path =~ m@$::BlockPathAccess@;
6522 my $Title = $URL_path;
6523 my $Caption = "";
6524 # Current file should not be used again
6525 ++$LinkUsed{$URL_path};
6526 # Open HTML doc
6527 unless(open(TextFile, $Path))
6529 print "<$Prefix>$Title <blink>(not found)</blink><br>\n";
6530 next;
6532 while(<TextFile>)
6534 chop $_;
6535 $Line = $_;
6536 # Catch Title
6537 while($Line =~ m@<title>@i)
6539 if($Line =~ m@<title>([^<]*)</title>@i)
6541 $Title = $1;
6542 $Line = $';
6544 else
6546 $Line .= <TextFile>;
6547 chop $Line;
6550 # Catch First Header
6551 while(!$Caption && $Line =~ m@<h1>@i)
6553 if($Line =~ m@</h[1-9]>@i)
6555 $Caption = $`;
6556 $Line = $';
6557 $Caption =~ m@<h1>@i;
6558 $Caption = $';
6559 $Line = $`.$Caption.$Line;
6561 else
6563 $Line .= <TextFile>;
6564 chop $Line;
6567 # Catch and print Links
6568 while($Line =~ m@<a href\=([^>]*)>@i)
6570 $Link = $1;
6571 $Line = $';
6572 # Remove quotes
6573 $Link =~ s/\"//g;
6574 # Remove extras
6575 $Link =~ s/[\#\?].*$//g;
6576 # Remove Servername
6577 if($Link =~ m@(http://|^)@i)
6579 $Link = $';
6580 # Only build tree for current server
6581 next unless $Link =~ m@$::ENV{'SERVER_NAME'}|^/@;
6582 # Remove server name and port
6583 $Link =~ s@^[^\/]*@@g;
6585 # Store the current link
6586 next if $LinkUsed{$Link} || $Link eq $URL_path;
6587 ++$LinkUsed{$Link};
6588 ++$LocalLinks{$Link};
6592 close TextFile;
6593 print "<$Prefix>";
6594 print "<a href=http://";
6595 print "$::ENV{'SERVER_NAME'}\:$::ENV{'SERVER_PORT'}$URL_path>";
6596 print "$Title</a>\n";
6597 print "<br>$Caption\n"
6598 if $Caption && $Caption ne $Title && $ListType =~ /dl/i;
6599 print "<$ListType>\n";
6600 foreach $Link (keys(%LocalLinks))
6602 &HTMLdocTree($Link, $ListType);
6604 print "</$ListType>\n";
6608 ###########################<<<<<<<<<<End Remove
6610 # Make require happy
6613 =head1 NAME
6615 CGIscriptor -
6617 =head1 DESCRIPTION
6619 A flexible HTML 4 compliant script/module for CGI-aware
6620 embeded Perl, shell-scripts, and other scripting languages,
6621 executed at the server side.
6623 =head1 README
6625 Executes embeded Perl code in HTML pages with easy
6626 access to CGI variables. Also processes embeded shell
6627 scripts and scripts in any other language with an
6628 interactive interpreter (e.g., in-line Python, Tcl,
6629 Ruby, Awk, Lisp, Xlispstat, Prolog, M4, R, REBOL, Praat,
6630 sh, bash, csh, ksh).
6632 CGIscriptor is very flexible and hides all the specifics
6633 and idiosyncrasies of correct output and CGI coding and naming.
6634 CGIscriptor complies with the W3C HTML 4.0 recommendations.
6636 This Perl program will run on any WWW server that runs
6637 Perl scripts, just add a line like the following to your
6638 srm.conf file (Apache example):
6640 ScriptAlias /SHTML/ /real-path/CGIscriptor.pl/
6642 URL's that refer to http://www.your.address/SHTML/... will
6643 now be handled by CGIscriptor.pl, which can use a private
6644 directory tree (default is the DOCUMENT_ROOT directory tree,
6645 but it can be anywhere).
6647 =head1 PREREQUISITES
6650 =head1 COREQUISITES
6653 =pod OSNAMES
6655 Linux, *BSD, *nix, MS WinXP
6657 =pod SCRIPT CATEGORIES
6659 Servers
6663 =cut