Renamed function so it might be more understandable
[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  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Run only once this security check/replacement
39 if (defined('__SECURITY')) return;
40
41 // Some security stuff...
42 if (strpos($_SERVER['PHP_SELF'], basename(__FILE__)) !== false) {
43         die();
44 } // END - if
45
46 // Include ctracker, recommended place!
47 //require_once('ctracker.php');
48
49 /**
50  * Function to secure input strings
51  *
52  * @param       $str    The unsecured string
53  * @param       $strip  Strip tags
54  * @return      $str    A (hopefully) secured string against XSS and other bad things
55  */
56 function secureString ($str, $strip = true, $encode = false) {
57         // Shall we strip HTML code?
58         if ($strip === true) $str = strip_tags($str);
59
60         // Trim string
61         $str = trim($str);
62
63         // Encode in entities if requested
64         if ($encode === true) {
65                 // Encode in entities (this breakes UTF-8!)
66                 $str = htmlentities($str, ENT_QUOTES);
67         } // END - if
68
69         // Return result
70         return $str;
71 }
72
73 /**
74  * Secures $_SERVER['PHP_SELF'] against attacks
75  *
76  * @return      void
77  */
78 function securePhpSelf () {
79         // Did it run before?
80         if (isset($GLOBALS['php_self_secured'])) {
81                 // Please do not call this twice!
82                 die('PHP_SELF is already secured. Please do not call ' . __FUNCTION__ . ' for your self.');
83         } // END - if
84
85         // Secure the string
86         $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
87
88         // Split it up into path and filename
89         $phpSelfDirectory = dirname($_SERVER['PHP_SELF']);
90         $phpSelfFile      = basename($_SERVER['PHP_SELF']);
91
92         // Check for a .php inside the $phpSelfDirectory...
93         while (strpos($phpSelfDirectory, '.php') !== false) {
94                 // Correct the dirname
95                 $phpSelfDirectory = substr($phpSelfDirectory, 0, (strpos($phpSelfDirectory, '.php') + 4));
96                 // Rewrite filename...
97                 $phpSelfFile = basename($phpSelfDirectory);
98                 // ... and dirname
99                 $phpSelfDirectory = dirname($phpSelfDirectory);
100         } // END - while
101
102         // Put both together again and let's pray it is secured now...
103         $_SERVER['PHP_SELF'] = $phpSelfDirectory . '/' . $phpSelfFile;
104
105         // Did run...
106         $GLOBALS['php_self_secured'] = true;
107
108         // Remove uneccessary variables
109         unset($phpSelfDirectory);
110         unset($phpSelfFile);
111 }
112
113 /**
114  * Detects caching in PHP
115  *
116  * @return      void
117  */
118 function detectPhpCaching () {
119         // Activate caching or transparent compressing when it is not already done
120         if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), 'Mozilla')))) {
121                 if ((extension_loaded('zlib')) && (function_exists('ob_start'))) {
122                         // Start caching
123                         $GLOBALS['php_caching'] = 'on';
124                         ob_start();
125                 } else {
126                         // Extension not loaded or required function is missing
127                         $GLOBALS['php_caching'] = '404';
128                 }
129         } else {
130                 // Old PHP version
131                 $GLOBALS['php_caching'] = 'old';
132         }
133 }
134
135 // Runtime/GPC quoting is off now...
136 ini_set('magic_quotes_runtime', false);
137 ini_set('magic_quotes_gpc', false); // This may not work on some systems
138
139 // No compatibility with Zend Engine 1, else an error like 'Implicit cloning'
140 // will be produced.
141 if (phpversion() >= '5.0') {
142         ini_set('zend.ze1_compatibility_mode', 'Off');
143 } // END - if
144
145 // Check if important arrays are found and define them if missing
146 if (!isset($_SERVER)) {
147         global $_SERVER;
148         $_SERVER = $GLOBALS['_SERVER'];
149 } // END - if
150
151 if (!isset($_GET)) {
152         global $_GET;
153         $_GET = $GLOBALS['_GET'];
154 } // END - if
155
156 if (!isset($_POST)) {
157         global $_POST;
158         $_POST = $GLOBALS['_POST'];
159 } // END - if
160
161 // Generate arrays which holds the relevante chars to replace
162 $GLOBALS['security_chars'] = array(
163         // The chars we are looking for...
164         'from' => array('/', '.', "'", '$', '(', ')', '{--', '--}', '{?', '?}', '%', ';', '[', ']', ':', '--'),
165         // ... and we will replace to.
166         'to'   => array(
167                 '{SLASH}',
168                 '{DOT}',
169                 '{QUOT}',
170                 '{DOLLAR}',
171                 '{OPEN_ANCHOR}',
172                 '{CLOSE_ANCHOR}',
173                 '{OPEN_TEMPLATE}',
174                 '{CLOSE_TEMPLATE}',
175                 '{OPEN_CONFIG}',
176                 '{CLOSE_CONFIG}',
177                 '{PER}',
178                 '{SEMI}',
179                 '{OPEN_INDEX}',
180                 '{CLOSE_INDEX}',
181                 '{DBL_DOT}',
182                 '{COMMENT}'
183         ),
184 );
185
186 // Characters allowed in URLs
187 //
188 // Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
189 //       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
190 $GLOBALS['url_chars'] = array(
191         // Search for these secured characters
192         'to'   => array('{SLASH}', '{DOT}', '{PER}', '{DBL_DOT}', '{COMMENT}'),
193         // Replace with these characters
194         'from' => array('/', '.', '%', ':', '--')
195 );
196
197 // Overworked security part:
198 if (is_array($_GET)) {
199         foreach ($_GET as $seckey => $secvalue) {
200                 if (is_array($secvalue)) {
201                         // Throw arrays away...
202                         unset($_GET[$seckey]);
203                 } else {
204                         // Only variables are allowed (non-array) but we secure them all!
205                         foreach ($GLOBALS['security_chars']['from'] as $key => $char) {
206                                 // Pass all through
207                                 $_GET[$seckey] = str_replace($char  , $GLOBALS['security_chars']['to'][$key], $_GET[$seckey]);
208                         } // END - foreach
209
210                         // Strip all other out
211                         $_GET[$seckey] = secureString($_GET[$seckey]);
212                 }
213         } // END - foreach
214 } // END - if
215
216 // Detect PHP caching
217 detectPhpCaching();
218
219 // At last secure the $_SERVER['PHP_SELF'] element
220 securePhpSelf();
221
222 // Security system loaded...
223 define('__SECURITY', 1);
224
225 // [EOF]
226 ?>