More EL code, security for $_POST elements rewritten (simplified):
[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 - 2011 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')) {
40         return;
41 } // END - if
42
43 // Some security stuff...
44 if (strpos($_SERVER['PHP_SELF'], basename(__FILE__)) !== false) {
45         die();
46 } // END - if
47
48 // Include ctracker, recommended place!
49 //require_once('ctracker.php');
50
51 /**
52  * Function to secure input strings
53  *
54  * @param       $str    The unsecured string
55  * @param       $strip  Strip tags
56  * @return      $str    A (hopefully) secured string against XSS and other bad things
57  */
58 function secureString ($str, $strip = true, $encode = false) {
59         // Shall we strip HTML code?
60         if ($strip === true) $str = strip_tags($str);
61
62         // Trim string
63         $str = trim($str);
64
65         // Encode in entities if requested
66         if ($encode === true) {
67                 // Encode in entities (this breakes UTF-8!)
68                 $str = htmlentities($str, ENT_QUOTES);
69         } // END - if
70
71         // Return result
72         return $str;
73 }
74
75 /**
76  * Secures $_SERVER['PHP_SELF'] against attacks
77  *
78  * @return      void
79  */
80 function securePhpSelf () {
81         // Did it run before?
82         if (isset($GLOBALS['php_self_secured'])) {
83                 // Please do not call this twice!
84                 die('PHP_SELF is already secured. Please do not call ' . __FUNCTION__ . ' for your self.');
85         } // END - if
86
87         // Secure the string
88         $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
89
90         // Split it up into path and filename
91         $phpSelfDirectory = dirname($_SERVER['PHP_SELF']);
92         $phpSelfFile      = basename($_SERVER['PHP_SELF']);
93
94         // Check for a .php inside the $phpSelfDirectory...
95         while (strpos($phpSelfDirectory, '.php') !== false) {
96                 // Correct the dirname
97                 $phpSelfDirectory = substr($phpSelfDirectory, 0, (strpos($phpSelfDirectory, '.php') + 4));
98                 // Rewrite filename...
99                 $phpSelfFile = basename($phpSelfDirectory);
100                 // ... and dirname
101                 $phpSelfDirectory = dirname($phpSelfDirectory);
102         } // END - while
103
104         // Put both together again and let's pray it is secured now...
105         $_SERVER['PHP_SELF'] = $phpSelfDirectory . '/' . $phpSelfFile;
106
107         // Did run...
108         $GLOBALS['php_self_secured'] = true;
109
110         // Remove uneccessary variables
111         unset($phpSelfDirectory);
112         unset($phpSelfFile);
113 }
114
115 /**
116  * Detects caching in PHP
117  *
118  * @return      void
119  */
120 function detectPhpCaching () {
121         // Activate caching or transparent compressing when it is not already done
122         if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), 'Mozilla')))) {
123                 if ((extension_loaded('zlib')) && (function_exists('ob_start'))) {
124                         // Start caching
125                         $GLOBALS['php_caching'] = 'on';
126                         ob_start();
127                 } else {
128                         // Extension not loaded or required function is missing
129                         $GLOBALS['php_caching'] = '404';
130                 }
131         } else {
132                 // Old PHP version
133                 $GLOBALS['php_caching'] = 'old';
134         }
135 }
136
137 // Runtime/GPC quoting is off now...
138 ini_set('magic_quotes_runtime', false);
139 ini_set('magic_quotes_gpc', false); // This may not work on some systems
140
141 // No compatibility with Zend Engine 1, else an error like 'Implicit cloning'
142 // will be produced.
143 if (phpversion() >= '5.0') {
144         ini_set('zend.ze1_compatibility_mode', 'Off');
145 } // END - if
146
147 // Check if important arrays are found and define them if missing
148 if (!isset($_SERVER)) {
149         global $_SERVER;
150         $_SERVER = $GLOBALS['_SERVER'];
151 } // END - if
152
153 if (!isset($_GET)) {
154         global $_GET;
155         $_GET = $GLOBALS['_GET'];
156 } // END - if
157
158 if (!isset($_POST)) {
159         global $_POST;
160         $_POST = $GLOBALS['_POST'];
161 } // END - if
162
163 // Generate arrays which holds the relevante chars to replace
164 $GLOBALS['security_chars'] = array(
165         // The chars we are looking for...
166         'from' => array('/', '.', "'", '$', '(', ')', '{--', '--}', '{?', '?}', '%', ';', '[', ']', ':', '--'),
167         // ... and we will replace to.
168         'to'   => array(
169                 '{SLASH}',
170                 '{DOT}',
171                 '{QUOT}',
172                 '{DOLLAR}',
173                 '{OPEN_ANCHOR}',
174                 '{CLOSE_ANCHOR}',
175                 '{OPEN_TEMPLATE}',
176                 '{CLOSE_TEMPLATE}',
177                 '{OPEN_CONFIG}',
178                 '{CLOSE_CONFIG}',
179                 '{PER}',
180                 '{SEMI}',
181                 '{OPEN_INDEX}',
182                 '{CLOSE_INDEX}',
183                 '{DBL_DOT}',
184                 '{COMMENT}'
185         ),
186 );
187
188 // Characters allowed in URLs
189 //
190 // Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
191 //       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
192 $GLOBALS['url_chars'] = array(
193         // Search for these secured characters
194         'to'   => array('{SLASH}', '{DOT}', '{PER}', '{DBL_DOT}', '{COMMENT}'),
195         // Replace with these characters
196         'from' => array('/', '.', '%', ':', '--')
197 );
198
199 // Overworked security part:
200 if (is_array($_GET)) {
201         foreach ($_GET as $seckey => $secvalue) {
202                 if (is_array($secvalue)) {
203                         // Throw arrays away...
204                         unset($_GET[$seckey]);
205                 } else {
206                         // Only variables are allowed (non-array) but we secure them all!
207                         $_GET[$seckey] = str_replace($GLOBALS['security_chars']['from'], $GLOBALS['security_chars']['to'], $_GET[$seckey]);
208
209                         // Strip all other out
210                         $_GET[$seckey] = secureString($_GET[$seckey]);
211                 }
212         } // END - foreach
213 } // END - if
214
215 // Secure also $_POST data (only simple, no replace)
216 if (is_array($_POST)) {
217         // Secure only simple data
218         foreach ($_POST as $seckey => $secvalue) {
219                 // Is it an array?
220                 if (!is_array($secvalue)) {
221                         // Strip all other out
222                         $_POST[$seckey] = secureString($_POST[$seckey]);
223                 } // END - if
224         } // END - foreach
225 } // END - if
226
227 // Detect PHP caching
228 detectPhpCaching();
229
230 // At last secure the $_SERVER['PHP_SELF'] element
231 securePhpSelf();
232
233 // Security system loaded...
234 define('__SECURITY', 1);
235
236 // [EOF]
237 ?>