96e39998fe8a7ab061992afccee2df548db2ce40
[mailer.git] / inc / libs / security_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 09/20/2005 *
4  * ===================                          Last change: 09/20/2005 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : security_functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : Secure all GET, POST and COOKIE data             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle GET, POST und COOKIE-Daten sichern          *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Run only once this security check/exchange
40 if (defined('__SECURITY')) return;
41
42 // Some security stuff...
43 if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
44         die();
45 } // END - if
46
47 /**
48  * Function to secure input strings
49  *
50  * @param       $str    The unsecured string
51  * @param       $strip  Strip tags
52  * @return      $str    A (hopefully) secured string against XSS and other bad things
53  */
54 function secureString ($str, $strip = true, $encode = false) {
55         // Shall we strip HTML code?
56         if ($strip === true) $str = strip_tags($str);
57
58         // Trim string
59         $str = trim($str);
60
61         // Encode in entities if requested
62         if ($encode === true) {
63                 // Encode in entities (this breakes UTF-8!)
64                 $str = htmlentities($str, ENT_QUOTES);
65         } // END - if
66
67         // Return result
68         return $str;
69 }
70
71 // Runtime/GPC quoting is off now...
72 set_magic_quotes_runtime(false);
73 ini_set('magic_quotes_gpc', false); // This may not work on some systems
74
75 // Check if important arrays are found and define them if missing
76 if (!isset($_SERVER)) {
77         global $_SERVER;
78         $_SERVER = $GLOBALS['_SERVER'];
79 } // END - if
80
81 if (!isset($_GET)) {
82         global $_GET;
83         $_GET = $GLOBALS['_GET'];
84 } // END - if
85
86 if (!isset($_POST)) {
87         global $_POST;
88         $_POST = $GLOBALS['_POST'];
89 } // END - if
90
91 // Include IP-Filter here
92 //require("/usr/share/php/ipfilter.php");
93
94 // Generate arrays which holds the relevante chars to replace
95 $GLOBALS['security_chars'] = array(
96         // The chars we are looking for...
97         'from' => array('{', '}', '/', '.', "'", '$', '(', ')', '{--', '--}', '{?', '?}', '%', ';', '[', ']', ':', '--'),
98         // ... and we will replace to.
99         'to'   => array(
100                 '{OPEN_ANCHOR2}',
101                 '{CLOSE_ANCHOR2}',
102                 '{SLASH}',
103                 '{DOT}',
104                 '{QUOT}',
105                 '{DOLLAR}',
106                 '{OPEN_ANCHOR}',
107                 '{CLOSE_ANCHOR}',
108                 '{OPEN_TEMPLATE}',
109                 '{CLOSE_TEMPLATE}',
110                 '{OPEN_CONFIG}',
111                 '{CLOSE_CONFIG}',
112                 '{PER}',
113                 '{SEMI}',
114                 '{OPEN_INDEX}',
115                 '{CLOSE_INDEX}',
116                 '{DBL_DOT}',
117                 '{COMMENT}'
118         ),
119 );
120
121 // Characters allowed in URLs
122 //
123 // Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
124 //       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
125 $GLOBALS['url_chars'] = array(
126         // Search for these secured characters
127         'to'   => array('{SLASH}', '{DOT}', '{PER}', '{DBL_DOT}', '{COMMENT}'),
128         // Replace with these characters
129         'from' => array('/', '.', '%', ':', '--')
130 );
131
132 // Overworked security part:
133 if (is_array($_GET)) {
134         foreach ($_GET as $seckey => $secvalue) {
135                 if (is_array($secvalue)) {
136                         // Throw arrays away...
137                         unset($_GET[$seckey]);
138                 } else {
139                         // Only variables are allowed (non-array) but we secure them all!
140                         foreach ($GLOBALS['security_chars']['from'] as $key => $char) {
141                                 // Pass all through
142                                 $_GET[$seckey] = str_replace($char  , $GLOBALS['security_chars']['to'][$key], $_GET[$seckey]);
143                         } // END - foreach
144
145                         // Strip all other out
146                         $_GET[$seckey] = secureString($_GET[$seckey]);
147                 }
148         } // END - foreach
149 } // END - if
150
151 // Activate caching or transparent compressing when it is not already done
152 if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), 'Mozilla')))) {
153         if ((extension_loaded('zlib')) && (function_exists('ob_start'))) {
154                 // Start caching
155                 $GLOBALS['php_caching'] = 'on';
156                 ob_start();
157         } else {
158                 // Extension not loaded or required function is missing
159                 $GLOBALS['php_caching'] = '404';
160         }
161 } else {
162         // Old PHP version
163         $GLOBALS['php_caching'] = 'old';
164 }
165
166 // At last secure the $_SERVER['PHP_SELF'] element
167 $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
168
169 // Split it up into path and filename
170 $phpSelfDirectory = dirname($_SERVER['PHP_SELF']);
171 $phpSelfFile      = basename($_SERVER['PHP_SELF']);
172
173 // Check for a .php inside the $phpSelfDirectory...
174 while (ereg('.php', $phpSelfDirectory)) {
175         // Correct the dirname
176         $phpSelfDirectory = substr($phpSelfDirectory, 0, (strpos($phpSelfDirectory, '.php') + 4));
177         // Rewrite filename...
178         $phpSelfFile = basename($phpSelfDirectory);
179         // ... and dirname
180         $phpSelfDirectory = dirname($phpSelfDirectory);
181 } // END - while
182
183 // Put both together again and let's pray it is secured now...
184 $_SERVER['PHP_SELF'] = $phpSelfDirectory . '/' . $phpSelfFile;
185
186 // Remove uneccessary variables
187 unset($phpSelfDirectory);
188 unset($phpSelfFile);
189
190 // Security system loaded...
191 define('__SECURITY', 1);
192
193 // [EOF]
194 ?>