Deprecated set_magic_quotes_runtime in PHP 5.3.1 rewritren
[mailer.git] / inc / libs / security_functions.php
index fa1679ab02bff27f40217711a067204871905276..c57d1e4c6eb35a638e4fdc997c61ad449847e051 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 /************************************************************************
- * MXChange v0.2.1                                    Start: 09/20/2005 *
- * ===============                              Last change: 09/20/2005 *
+ * Mailer v0.2.1-FINAL                                Start: 09/20/2005 *
+ * ===================                          Last change: 09/20/2005 *
  *                                                                      *
  * -------------------------------------------------------------------- *
  * File              : security_functions.php                           *
@@ -17,7 +17,8 @@
  * Needs to be in all Files and every File needs "svn propset           *
  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
- * Copyright (c) 2003 - 2008 by Roland Haeder                           *
+ * Copyright (c) 2003 - 2009 by Roland Haeder                           *
+ * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
  * For more information visit: http://www.mxchange.org                  *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
  * MA  02110-1301  USA                                                  *
  ************************************************************************/
 
+// Run only once this security check/replacement
+if (defined('__SECURITY')) return;
+
 // Some security stuff...
-if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
-       $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
-       require($INC);
-}
+if (strpos($_SERVER['PHP_SELF'], basename(__FILE__)) !== false) {
+       die();
+} // END - if
 
 /**
  * Function to secure input strings
@@ -49,158 +52,173 @@ if (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
  * @param      $strip  Strip tags
  * @return     $str    A (hopefully) secured string against XSS and other bad things
  */
-function secureString ($str, $strip=true) {
+function secureString ($str, $strip = true, $encode = false) {
        // Shall we strip HTML code?
-       if ($strip) $str = strip_tags($str);
+       if ($strip === true) $str = strip_tags($str);
 
        // Trim string
        $str = trim($str);
 
-       // Encode in entities
-       $str = htmlentities($str, ENT_QUOTES);
+       // Encode in entities if requested
+       if ($encode === true) {
+               // Encode in entities (this breakes UTF-8!)
+               $str = htmlentities($str, ENT_QUOTES);
+       } // END - if
+
+       // Return result
        return $str;
 }
 
-// Run only once this security check/exchange
-if (defined('__SECURITY')) return;
+/**
+ * Secures $_SERVER['PHP_SELF'] against attacks
+ *
+ * @return     void
+ */
+function securePhpSelf () {
+       // Did it run before?
+       if (isset($GLOBALS['php_self_secured'])) {
+               // Please do not call this twice!
+               die('PHP_SELF is already secured. Please do not call ' . __FUNCTION__ . ' for your self.');
+       } // END - if
+
+       // Secure the string
+       $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
+
+       // Split it up into path and filename
+       $phpSelfDirectory = dirname($_SERVER['PHP_SELF']);
+       $phpSelfFile      = basename($_SERVER['PHP_SELF']);
+
+       // Check for a .php inside the $phpSelfDirectory...
+       while (strpos($phpSelfDirectory, '.php') !== false) {
+               // Correct the dirname
+               $phpSelfDirectory = substr($phpSelfDirectory, 0, (strpos($phpSelfDirectory, '.php') + 4));
+               // Rewrite filename...
+               $phpSelfFile = basename($phpSelfDirectory);
+               // ... and dirname
+               $phpSelfDirectory = dirname($phpSelfDirectory);
+       } // END - while
+
+       // Put both together again and let's pray it is secured now...
+       $_SERVER['PHP_SELF'] = $phpSelfDirectory . '/' . $phpSelfFile;
+
+       // Did run...
+       $GLOBALS['php_self_secured'] = true;
+
+       // Remove uneccessary variables
+       unset($phpSelfDirectory);
+       unset($phpSelfFile);
+}
+
+/**
+ * Detects caching in PHP
+ *
+ * @return     void
+ */
+function detectPhpCaching () {
+       // Activate caching or transparent compressing when it is not already done
+       if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), 'Mozilla')))) {
+               if ((extension_loaded('zlib')) && (function_exists('ob_start'))) {
+                       // Start caching
+                       $GLOBALS['php_caching'] = 'on';
+                       ob_start();
+               } else {
+                       // Extension not loaded or required function is missing
+                       $GLOBALS['php_caching'] = '404';
+               }
+       } else {
+               // Old PHP version
+               $GLOBALS['php_caching'] = 'old';
+       }
+}
 
 // Runtime/GPC quoting is off now...
-@set_magic_quotes_runtime(false);
-@ini_set('magic_quotes_gpc', false); // This may not work on some systems
+ini_set('magic_quotes_runtime', false);
+ini_set('magic_quotes_gpc', false); // This may not work on some systems
 
 // Check if important arrays are found and define them if missing
 if (!isset($_SERVER)) {
        global $_SERVER;
        $_SERVER = $GLOBALS['_SERVER'];
-}
+} // END - if
 
 if (!isset($_GET)) {
        global $_GET;
        $_GET = $GLOBALS['_GET'];
-}
+} // END - if
 
 if (!isset($_POST)) {
        global $_POST;
        $_POST = $GLOBALS['_POST'];
-}
+} // END - if
 
 // Include IP-Filter here
-//require("/usr/share/php/ipfilter.php");
+//include("/usr/share/php/ipfilter.php");
 
 // Generate arrays which holds the relevante chars to replace
 $GLOBALS['security_chars'] = array(
-// The chars we are looking for...
-       'from' => array("{", "}", '/', '.', "'", "$", '(', ')', '{--', '--}', "%", ';', "[", "]", ':', "--"),
-// ... and we will replace to.
+       // The chars we are looking for...
+       'from' => array('{', '}', '/', '.', "'", '$', '(', ')', '{--', '--}', '{?', '?}', '%', ';', '[', ']', ':', '--'),
+       // ... and we will replace to.
        'to'   => array(
-               "{OPEN_ANCHOR2}",
-               "{CLOSE_ANCHOR2}",
-               "{SLASH}",
-               "{DOT}",
-               "{QUOT}",
-               "{DOLLAR}",
-               "{OPEN_ANCHOR}",
-               "{CLOSE_ANCHOR}",
-               "{OPEN_TEMPLATE}",
-               "{CLOSE_TEMPLATE}",
-               "{PER}",
-               "{SEMI}",
-               "{OPEN_INDEX}",
-               "{CLOSE_INDEX}",
-               "{DBL_DOT}",
-               "{COMMENT}"
-               ),
-               );
-
-               // Characters allowed in URLs
-               //
-               // Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
-               //       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
-               $GLOBALS['url_chars'] = array(
-               // Search for these secured characters
-       'to'   => array("{SLASH}", "{DOT}", "{PER}", "{DBL_DOT}", "{COMMENT}"),
-               // Replace with these characters
-       'from' => array('/', '.', "%", ':', "--")
-               );
-
-               // Overworked security part:
-               if (is_array($_GET)) {
-                       foreach ($_GET as $seckey => $secvalue) {
-                               if (is_array($secvalue)) {
-                                       // Throw arrays away...
-                                       unset($_GET[$seckey]);
-                               } else {
-                                       // Only variables are allowed (non-array) but we secure them all!
-                                       foreach ($GLOBALS['security_chars']['from'] as $key => $char) {
-                                               // Pass all through
-                                               $_GET[$seckey] = str_replace($char  , $GLOBALS['security_chars']['to'][$key], $_GET[$seckey]);
-                                       }
-
-                                       // Strip all other out
-                                       $_GET[$seckey] = strip_tags($_GET[$seckey]);
-                               }
-                       }
-               }
-
-               if (basename($_SERVER['PHP_SELF']) != 'install.php') {
-                       // And POST data
-                       foreach ($_POST as $seckey => $secvalue) {
-                               if (!is_array($secvalue)) {
-                                       // Only variables are allowed (non-array) to be secured...
-                                       foreach ($GLOBALS['security_chars']['from'] as $key => $char) {
-                                               // Pass all through
-                                               $_POST[$seckey] = str_replace($char  , $GLOBALS['security_chars']['to'][$key], $_POST[$seckey]);
-                                       }
-
-                                       // Strip all other out
-                                       $_POST[$seckey] = strip_tags($_POST[$seckey]);
-                               }
-                       }
-               }
-
-               // Activate caching or transparent compressing when it is not already done
-               if (!defined('_OB_CACHING')) {
-                       if (phpversion() >= '4.0.4pl1' && (strstr(getenv('HTTP_USER_AGENT'),'compatible') || (strstr(getenv('HTTP_USER_AGENT'), "Mozilla")))) {
-                               if ((extension_loaded('zlib')) && (function_exists('ob_start'))) {
-                                       // Start caching
-                                       define('_OB_CACHING', 'on');
-                                       ob_start();
-                               } else {
-                                       // Extension not loaded or required function is missing
-                                       define('_OB_CACHING', '404');
-                               }
-                       } else {
-                               // Old PHP version
-                               define('_OB_CACHING', 'old');
-                       }
-               }
-
-               // At last secure the $_SERVER['PHP_SELF'] element
-               $_SERVER['PHP_SELF'] = secureString($_SERVER['PHP_SELF']);
-
-               // Split it up into path and filename
-               $SELF_DIR  = dirname($_SERVER['PHP_SELF']);
-               $SELF_FILE = basename($_SERVER['PHP_SELF']);
-
-               // Check for a .php inside the $SELF_DIR...
-               while (ereg('.php', $SELF_DIR)) {
-                       // Correct the dirname
-                       $SELF_DIR = substr($SELF_DIR, 0, (strpos($SELF_DIR, '.php') + 4));
-                       // Rewrite filename...
-                       $SELF_FILE = basename($SELF_DIR);
-                       // ... and dirname
-                       $SELF_DIR = dirname($SELF_DIR);
+               '{OPEN_ANCHOR2}',
+               '{CLOSE_ANCHOR2}',
+               '{SLASH}',
+               '{DOT}',
+               '{QUOT}',
+               '{DOLLAR}',
+               '{OPEN_ANCHOR}',
+               '{CLOSE_ANCHOR}',
+               '{OPEN_TEMPLATE}',
+               '{CLOSE_TEMPLATE}',
+               '{OPEN_CONFIG}',
+               '{CLOSE_CONFIG}',
+               '{PER}',
+               '{SEMI}',
+               '{OPEN_INDEX}',
+               '{CLOSE_INDEX}',
+               '{DBL_DOT}',
+               '{COMMENT}'
+       ),
+);
+
+// Characters allowed in URLs
+//
+// Note: Do not replace 'to' with 'from' and vise-versa! When you do this all booked URLs will be
+//       rejected because of the {SLASH}, {DOT} and all below listed items inside the URL.
+$GLOBALS['url_chars'] = array(
+       // Search for these secured characters
+       'to'   => array('{SLASH}', '{DOT}', '{PER}', '{DBL_DOT}', '{COMMENT}'),
+       // Replace with these characters
+       'from' => array('/', '.', '%', ':', '--')
+);
+
+// Overworked security part:
+if (is_array($_GET)) {
+       foreach ($_GET as $seckey => $secvalue) {
+               if (is_array($secvalue)) {
+                       // Throw arrays away...
+                       unset($_GET[$seckey]);
+               } else {
+                       // Only variables are allowed (non-array) but we secure them all!
+                       foreach ($GLOBALS['security_chars']['from'] as $key => $char) {
+                               // Pass all through
+                               $_GET[$seckey] = str_replace($char  , $GLOBALS['security_chars']['to'][$key], $_GET[$seckey]);
+                       } // END - foreach
+
+                       // Strip all other out
+                       $_GET[$seckey] = secureString($_GET[$seckey]);
                }
+       } // END - foreach
+} // END - if
 
-               // Put both together again and let's pray it is secured now...
-               $_SERVER['PHP_SELF'] = $SELF_DIR.'/'.$SELF_FILE;
+// Detect PHP caching
+detectPhpCaching();
 
-               // Remove uneccessary variables
-               unset($SELF_DIR);
-               unset($SELF_FILE);
+// At last secure the $_SERVER['PHP_SELF'] element
+securePhpSelf();
 
-               // Security system loaded...
-               define('__SECURITY', '1');
+// Security system loaded...
+define('__SECURITY', 1);
 
-               //
-               ?>
+// [EOF]
+?>