Reverted of changes in 1704, see ticket #160
[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/exchange
41 if (defined('__SECURITY')) return;
42
43 // Some security stuff...
44 if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
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 // Runtime/GPC quoting is off now...
73 set_magic_quotes_runtime(false);
74 ini_set('magic_quotes_gpc', false); // This may not work on some systems
75
76 // Check if important arrays are found and define them if missing
77 if (!isset($_SERVER)) {
78         global $_SERVER;
79         $_SERVER = $GLOBALS['_SERVER'];
80 } // END - if
81
82 if (!isset($_GET)) {
83         global $_GET;
84         $_GET = $GLOBALS['_GET'];
85 } // END - if
86
87 if (!isset($_POST)) {
88         global $_POST;
89         $_POST = $GLOBALS['_POST'];
90 } // END - if
91
92 // Include IP-Filter here
93 //include("/usr/share/php/ipfilter.php");
94
95 // Generate arrays which holds the relevante chars to replace
96 $GLOBALS['security_chars'] = array(
97         // The chars we are looking for...
98         'from' => array('{', '}', '/', '.', "'", '$', '(', ')', '{--', '--}', '{?', '?}', '%', ';', '[', ']', ':', '--'),
99         // ... and we will replace to.
100         'to'   => array(
101                 '{OPEN_ANCHOR2}',
102                 '{CLOSE_ANCHOR2}',
103                 '{SLASH}',
104                 '{DOT}',
105                 '{QUOT}',
106                 '{DOLLAR}',
107                 '{OPEN_ANCHOR}',
108                 '{CLOSE_ANCHOR}',
109                 '{OPEN_TEMPLATE}',
110                 '{CLOSE_TEMPLATE}',
111                 '{OPEN_CONFIG}',
112                 '{CLOSE_CONFIG}',
113                 '{PER}',
114                 '{SEMI}',
115                 '{OPEN_INDEX}',
116                 '{CLOSE_INDEX}',
117                 '{DBL_DOT}',
118                 '{COMMENT}'
119         ),
120 );
121
122 // Characters allowed in URLs
123 //
124 // Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
125 //       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
126 $GLOBALS['url_chars'] = array(
127         // Search for these secured characters
128         'to'   => array('{SLASH}', '{DOT}', '{PER}', '{DBL_DOT}', '{COMMENT}'),
129         // Replace with these characters
130         'from' => array('/', '.', '%', ':', '--')
131 );
132
133 // Overworked security part:
134 if (is_array($_GET)) {
135         foreach ($_GET as $seckey => $secvalue) {
136                 if (is_array($secvalue)) {
137                         // Throw arrays away...
138                         unset($_GET[$seckey]);
139                 } else {
140                         // Only variables are allowed (non-array) but we secure them all!
141                         foreach ($GLOBALS['security_chars']['from'] as $key => $char) {
142                                 // Pass all through
143                                 $_GET[$seckey] = str_replace($char  , $GLOBALS['security_chars']['to'][$key], $_GET[$seckey]);
144                         } // END - foreach
145
146                         // Strip all other out
147                         $_GET[$seckey] = secureString($_GET[$seckey]);
148                 }
149         } // END - foreach
150 } // END - if
151
152 // Activate caching or transparent compressing when it is not already done
153 if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), 'Mozilla')))) {
154         if ((extension_loaded('zlib')) && (function_exists('ob_start'))) {
155                 // Start caching
156                 $GLOBALS['php_caching'] = 'on';
157                 ob_start();
158         } else {
159                 // Extension not loaded or required function is missing
160                 $GLOBALS['php_caching'] = '404';
161         }
162 } else {
163         // Old PHP version
164         $GLOBALS['php_caching'] = 'old';
165 }
166
167 // At last secure the $_SERVER['PHP_SELF'] element
168 $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
169
170 // Split it up into path and filename
171 $phpSelfDirectory = dirname($_SERVER['PHP_SELF']);
172 $phpSelfFile      = basename($_SERVER['PHP_SELF']);
173
174 // Check for a .php inside the $phpSelfDirectory...
175 while (ereg('.php', $phpSelfDirectory)) {
176         // Correct the dirname
177         $phpSelfDirectory = substr($phpSelfDirectory, 0, (strpos($phpSelfDirectory, '.php') + 4));
178         // Rewrite filename...
179         $phpSelfFile = basename($phpSelfDirectory);
180         // ... and dirname
181         $phpSelfDirectory = dirname($phpSelfDirectory);
182 } // END - while
183
184 // Put both together again and let's pray it is secured now...
185 $_SERVER['PHP_SELF'] = $phpSelfDirectory . '/' . $phpSelfFile;
186
187 // Remove uneccessary variables
188 unset($phpSelfDirectory);
189 unset($phpSelfFile);
190
191 // Security system loaded...
192 define('__SECURITY', 1);
193
194 // [EOF]
195 ?>