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