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