79599e4558dd6ace5280466af69a3b894f3ac18d
[mailer.git] / inc / libs / security_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (ereg(basename(__FILE__), $_SERVER['PHP_SELF']))
36 {
37         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
38         require($INC);
39 }
40
41 /**
42  * Function to secure input strings
43  *
44  * @param       $str    The unsecured string
45  * @return      $str    A (hopefully) secured string against HTML and other things
46  */
47 function secureString ($str) {
48         $str = trim(strip_tags($str));
49         $str = htmlentities($str, ENT_QUOTES);
50         return $str;
51 }
52
53 // Run only once this security check/exchange
54 if (defined('__SECURITY')) return;
55
56 // Fatal messages goes here
57 global $FATAL;
58 $FATAL = array();
59
60 // Runtime quoting is off now...
61 set_magic_quotes_runtime(false);
62
63 // Unregister all global variables because of vultures and surpress failed attemps
64 @import_request_variables('');
65
66 // Error reporting level
67 @error_reporting(E_ALL | E_STRICT);
68
69 // Check if important arrays are found and define them if missing
70 if (!isset($_SERVER))
71 {
72         global $_SERVER;
73         $_SERVER = $GLOBALS['_SERVER'];
74 }
75 if (!isset($_GET))
76 {
77         global $_GET;
78         $_GET = $GLOBALS['_GET'];
79 }
80 if (!isset($_POST))
81 {
82         global $_POST;
83         $_POST = $GLOBALS['_POST'];
84 }
85 if (!isset($_SESSION))
86 {
87         global $_SESSION;
88         $_SESSION = $GLOBALS['_COOKIE'];
89 }
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 global $SEC_CHARS, $URL_CHARS;
96 $SEC_CHARS = array(
97         // The chars we are looking for...
98         'from' => array("{", "}", "/", ".", "'", "$", "(", ")", "{--", "--}", "%", ";", "[", "]", ":", "--"),
99         // ... and we will replace to.
100         'to'   => array(
101                 "{OPEN_ANCHOR2}",
102                 "{CLOSE_ANCHOR2}",
103                 "{SLASH}",
104                 "{DOT}",
105                 "{QUOT}",
106                 "{DOLLAR}",
107                 "{OPEN_ANCHOR}",
108                 "{CLOSE_ANCHOR}",
109                 "{OPEN_TEMPLATE}",
110                 "{CLOSE_TEMPLATE}",
111                 "{PER}",
112                 "{SEMI}",
113                 "{OPEN_INDEX}",
114                 "{CLOSE_INDEX}",
115                 "{DBL_DOT}",
116                 "{COMMENT}"
117         ),
118 );
119
120 // Characters allowed in URLs
121 //
122 // Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
123 //       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
124 $URL_CHARS = array(
125         // Search for these secured characters
126         'to'   => array("{SLASH}", "{DOT}", "{PER}", "{DBL_DOT}", "{COMMENT}"),
127         // Replace with these characters
128         'from' => array("/", ".", "%", ":", "--")
129 );
130
131 // Overworked security part:
132 if (is_array($_GET)) {
133         foreach ($_GET as $seckey=>$secvalue)
134         {
135                 if (is_array($secvalue))
136                 {
137                         // Throw arrays away...
138                         unset($_GET[$seckey]);
139                 }
140                  else
141                 {
142                         // Only variables are allowed (non-array) but we secure them all!
143                         foreach ($SEC_CHARS['from'] as $key=>$char)
144                         {
145                                 // Pass all through
146                                 $_GET[$seckey] = str_replace($char  , $SEC_CHARS['to'][$key], $_GET[$seckey]);
147                         }
148
149                         // Strip all other out
150                         $_GET[$seckey] = strip_tags($_GET[$seckey]);
151                 }
152         }
153 }
154
155 if (basename($_SERVER['PHP_SELF']) != "install.php")
156 {
157         // And POST data
158         foreach ($_POST as $seckey=>$secvalue)
159         {
160                 if (!is_array($secvalue))
161                 {
162                         // Only variables are allowed (non-array) to be secured...
163                         foreach ($SEC_CHARS['from'] as $key=>$char)
164                         {
165                                 // Pass all through
166                                 $_POST[$seckey] = str_replace($char  , $SEC_CHARS['to'][$key], $_POST[$seckey]);
167                         }
168
169                         // Strip all other out
170                         $_POST[$seckey] = strip_tags($_POST[$seckey]);
171                 }
172         }
173
174         // ... and finally cookies
175         foreach ($_SESSION as $seckey=>$secvalue)
176         {
177                 if (is_array($secvalue))
178                 {
179                         // Throw arrays away...
180                         unset($_SESSION[$seckey]);
181                 }
182                  else
183                 {
184                         // Only variables are allowed (non-array) but we secure them all!
185                         foreach ($SEC_CHARS['from'] as $key=>$char)
186                         {
187                                 // Pass all through
188                                 $_SESSION[$seckey] = str_replace($char  , $SEC_CHARS['to'][$key], $_SESSION[$seckey]);
189                         }
190
191                         // Strip all other out
192                         $_SESSION[$seckey] = strip_tags($_SESSION[$seckey]);
193                 }
194         }
195 }
196
197 // Activate caching or transparent compressing when it is not already done
198 if (!defined('_OB_CACHING'))
199 {
200         if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), "Mozilla"))))
201         {
202                 if ((extension_loaded('zlib')) && (function_exists('ob_start')))
203                 {
204                         // Start caching
205                         define('_OB_CACHING', "on");
206                         ob_start();
207                 }
208                  else
209                 {
210                         // Extension not loaded or required function is missing
211                         define('_OB_CACHING', "404");
212                 }
213         }
214          else
215         {
216                 // Old PHP version
217                 define('_OB_CACHING', "old");
218         }
219 }
220
221 // At last secure the $_SERVER['PHP_SELF'] element
222 $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
223
224 // Split it up into path and filename
225 $SELF_DIR  = dirname($_SERVER['PHP_SELF']);
226 $SELF_FILE = basename($_SERVER['PHP_SELF']);
227
228 // Check for a .php inside the $SELF_DIR...
229 while (ereg(".php", $SELF_DIR))
230 {
231         // Correct the dirname
232         $SELF_DIR = substr($SELF_DIR, 0, (strpos($SELF_DIR, ".php") + 4));
233         // Rewrite filename...
234         $SELF_FILE = basename($SELF_DIR);
235         // ... and dirname
236         $SELF_DIR = dirname($SELF_DIR);
237 }
238
239 // Put both together again and let's pray it is secured now...
240 $_SERVER['PHP_SELF'] = $SELF_DIR."/".$SELF_FILE;
241
242 // Remove uneccessary variables
243 unset($SELF_DIR);
244 unset($SELF_FILE);
245
246 // Security system loaded...
247 define('__SECURITY', "1");
248
249 //
250 ?>