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