Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        framework
5
 * @package         SecureForm.mtab
6
 * @author          WebsiteBaker Community Project
7
 * @copyright       2004-2009, Ryan Djurovich
8
 * @copyright       2009-2011, Website Baker Org. e.V.
9
 * @link			http://www.websitebaker2.org/
10
 * @license         http://www.gnu.org/licenses/gpl.html
11
 * @platform        WebsiteBaker 2.8.2
12
 * @requirements    PHP 5.2.2 and higher
13
 * @version         $Id: SecureForm.mtab.php 1496 2011-08-11 16:15:31Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/SecureForm.mtab.php $
15
 * @lastmodified    $Date: 2011-08-11 18:15:31 +0200 (Thu, 11 Aug 2011) $
16
 * @description
17
 */
18
##  Heavy patched version, idea for patches based on :
19
##  http://stackoverflow.com/questions/2695153/php-csrf-how-to-make-it-works-in-all-tabs/2695291#2695291
20
##  Whith this patch the token System now allows for multiple browser tabs but 
21
##  denies the use of multiple browsers.
22
##  You can configure this class by adding several constants to your config.php
23
##  All Patches are Copyright Norbert Heimsath released under GPLv3 
24
##  http://www.gnu.org/licenses/gpl.html
25
##  Take a look at  __construkt  for configuration options(constants).
26
##  Patch version 0.3.5
27

    
28
/**
29
 * If you want some special configuration put this somewhere in your config.php for
30
 * example or just uncomment the lines here
31
 *
32
 * This parameter now can be set with the admintool SecureForm Switcher coded by Luisehahne,
33
 * pls ask for it in the forum
34
 *
35
 * Secret can contain anything its the base for the secret part for the hash
36
 * define ('WB_SECFORM_SECRET','whatever you like');
37
 * after how many seconds a new secret is generated
38
 * define ('WB_SECFORM_SECRETTIME',86400);      #aprox one day
39
 * shall we use fingerprinting true/false
40
 * define ('WB_SECFORM_USEFP', true);
41
 * Timeout till the form token times out. Integer value between 0-86400 seconds (one day)
42
 * define ('WB_SECFORM_TIMEOUT', 3600);
43
 * Name for the token form element only alphanumerical string allowed that starts whith a charakter
44
 * define ('WB_SECFORM_TOKENNAME','my3form3');
45
 * how many blocks of the IP should be used in fingerprint 0=no ipcheck, possible values 0-4
46
 * define ('FINGERPRINT_WITH_IP_OCTETS',2);
47
 */
48
/* -------------------------------------------------------- */
49
// Must include code to stop this file being accessed directly
50
require_once('globalExceptionHandler.php');
51
if(!defined('WB_PATH')) { throw new IllegalFileException(); }
52
/* -------------------------------------------------------- */
53

    
54
class SecureForm {
55

    
56
	const FRONTEND = 0;
57
	const BACKEND  = 1;      
58

    
59
        ## additional private data
60
	private $_secret      	 = '5609bnefg93jmgi99igjefg';
61
	private $_secrettime  	 = 86400;   #Approx. one day 
62
        private $_tokenname   	 = 'formtoken';
63
	private $_timeout	 = 7200;         
64
	private $_useipblocks	 = 2;
65
	private $_usefingerprint = true;
66
        ### additional private data
67

    
68
        private $_FTAN           = '';
69
	private $_IDKEYs         = array('0'=>'0');
70
	private $_idkey_name     = '';
71
	private $_salt           = '';
72
	private $_fingerprint    = '';
73
	private $_serverdata  	 = '';
74

    
75
	/* Construtor */
76
	protected function __construct($mode = self::FRONTEND){
77

    
78
        	## additional constants and stuff for global configuration
79

    
80
		# Secret can contain anything its the base for the secret part of the hash
81
                if (defined ('WB_SECFORM_SECRET')){ 	
82
			$this->_secret=WB_SECFORM_SECRET;
83
		}
84

    
85
		# shall we use fingerprinting
86
                if (defined ('WB_SECFORM_USEFP') AND WB_SECFORM_USEFP===false){
87
			$this->_usefingerprint	= false;
88
		}
89

    
90
                # Timeout till the form token times out. Integer value between 0-86400 seconds (one day)
91
                if (defined ('WB_SECFORM_TIMEOUT') AND is_numeric(WB_SECFORM_TIMEOUT) AND intval(WB_SECFORM_TIMEOUT) >=0 AND intval(WB_SECFORM_TIMEOUT) <=86400 ){
92
			$this->_timeout=intval(WB_SECFORM_TIMEOUT);
93
		}
94
		# Name for the token form element only alphanumerical string allowed that starts whith a charakter
95
                if (defined ('WB_SECFORM_TOKENNAME') AND !$this->_validate_alalnum(WB_SECFORM_TOKENNAME)){
96
			$this->_tokenname=WB_SECFORM_TOKENNAME;
97
		}
98
		# how many bloks of the IP should be used 0=no ipcheck 
99
                if (defined ('FINGERPRINT_WITH_IP_OCTETS') AND !$this->_is04(FINGERPRINT_WITH_IP_OCTETS)){
100
			$this->_useipblocks=FINGERPRINT_WITH_IP_OCTETS;
101
                }
102
		## additional stuff end 
103
		$this->_browser_fingerprint   = $this->_browser_fingerprint(true);
104
		$this->_fingerprint   = $this->_generate_fingerprint();
105
		$this->_serverdata    = $this->_generate_serverdata();
106
		$this->_secret        = $this->_generate_secret();
107
                $this->_salt          = $this->_generate_salt();
108

    
109
		$this->_idkey_name    = substr($this->_fingerprint, hexdec($this->_fingerprint[strlen($this->_fingerprint)-1]), 16);
110
		// make sure there is a alpha-letter at first position
111
		$this->_idkey_name[0] = dechex(10 + (hexdec($this->_idkey_name[0]) % 5));
112
		// takeover id_keys from session if available
113
		if(isset($_SESSION[$this->_idkey_name]) && is_array($_SESSION[$this->_idkey_name])){
114
			$this->_IDKEYs = $_SESSION[$this->_idkey_name];
115
		}else{
116
			$this->_IDKEYs = array('0'=>'0');
117
			$_SESSION[$this->_idkey_name] = $this->_IDKEYs;
118
		}
119
	}
120

    
121
	private function _generate_secret(){
122

    
123
                $secret= $this->_secret;
124
		$secrettime= $this->_secrettime;
125
		#create a different secret every day
126
		$TimeSeed= floor(time()/$secrettime)*$secrettime;  #round(floor) time() to whole days
127
		$DomainSeed =  $_SERVER['SERVER_NAME'];  # generate a numerical from server name.
128
		$Seed = $TimeSeed+$DomainSeed;
129
                $secret .=md5($Seed);  #
130

    
131
		$secret .= $this->_secret.$this->_serverdata.session_id();
132
		if ($this->_usefingerprint){$secret.= $this->_browser_fingerprint;}
133
		
134
	return $secret;
135
	}
136

    
137

    
138

    
139
	private function _generate_salt()
140
		{
141
			if(function_exists('microtime'))
142
			{
143
				list($usec, $sec) = explode(" ", microtime());
144
				$salt = (string)((float)$usec + (float)$sec);
145
			}else{
146
				$salt = (string)time();
147
			}
148
			$salt = (string)rand(10000, 99999) . $salt . (string)rand(10000, 99999);
149
			return md5($salt);
150
		}
151

    
152
	private function _generate_fingerprint()
153
	{
154
	// server depending values
155
 		$fingerprint  = $this->_generate_serverdata();
156
		
157
	// client depending values
158
		$fingerprint .= ( isset($_SERVER['HTTP_USER_AGENT']) ) ? $_SERVER['HTTP_USER_AGENT'] : '17';
159
		$usedOctets = ( defined('FINGERPRINT_WITH_IP_OCTETS') ) ? intval(defined('FINGERPRINT_WITH_IP_OCTETS')) : 0;
160
		$clientIp = ( isset($_SERVER['REMOTE_ADDR'])  ? $_SERVER['REMOTE_ADDR'] : '' );
161
		if(($clientIp != '') && ($usedOctets > 0)){
162
			$ip = explode('.', $clientIp);
163
			while(sizeof($ip) > $usedOctets) { array_pop($ip); }
164
			$clientIp = implode('.', $ip);
165
		}else {
166
			$clientIp = 19;
167
		}
168
		$fingerprint .= $clientIp;
169
		return md5($fingerprint);
170
	}
171

    
172
	private function _generate_serverdata(){
173

    
174
	 	$serverdata  = ( isset($_SERVER['SERVER_SIGNATURE']) ) ? $_SERVER['SERVER_SIGNATURE'] : '2';
175
		$serverdata .= ( isset($_SERVER['SERVER_SOFTWARE']) ) ? $_SERVER['SERVER_SOFTWARE'] : '3';
176
		$serverdata .= ( isset($_SERVER['SERVER_NAME']) ) ? $_SERVER['SERVER_NAME'] : '5';
177
		$serverdata .= ( isset($_SERVER['SERVER_ADDR']) ) ? $_SERVER['SERVER_ADDR'] : '7';
178
		$serverdata .= ( isset($_SERVER['SERVER_PORT']) ) ? $_SERVER['SERVER_PORT'] : '11';
179
		$serverdata .= ( isset($_SERVER['SERVER_ADMIN']) ) ? $_SERVER['SERVER_ADMIN'] : '13';
180
		$serverdata .= PHP_VERSION;
181
	return  $serverdata;
182
	}
183

    
184
        // fake funktion , just exits to avoid error message 
185
        final protected function createFTAN(){}
186

    
187
	/*
188
	* creates selfsigning Formular transactionnumbers for unique use
189
	* @access public
190
	* @param bool $asTAG: true returns a complete prepared, hidden HTML-Input-Tag (default)
191
	*                     false returns an GET argument 'key=value'
192
	* @return mixed:      string
193
	*
194
	* requirements: an active session must not be available but it makes no sense whithout :-)
195
	*/
196
	final public function getFTAN( $as_tag = true)
197
	{
198
		$secret= $this->_secret;
199

    
200
		$timeout= time()+$this->_timeout;
201

    
202
		#mt_srand(hexdec(crc32(microtime()));
203
                $token= dechex(mt_rand());
204

    
205
                $hash= sha1($secret.'-'.$token.'-'.$timeout);
206
		$signed= $token.'-'.$timeout.'-'.$hash;
207

    
208
		if($as_tag == true)
209
		{ // by default return a complete, hidden <input>-tag
210
			return '<input type="hidden" name="'.$this->_tokenname.'" value="'.htmlspecialchars($signed).'" title="" alt="" />';
211
		}else{ // return an array with raw tokenname=value
212
			return $this->_tokenname.'='.$signed;
213
		}
214
	}
215

    
216
	/*
217
	* checks received form-transactionnumbers against itself
218
	* @access public
219
	* @param string $mode: requestmethode POST(default) or GET
220
	* @return bool:    true if numbers matches against stored ones
221
	*
222
	* requirements: no active session must be available but it makes no sense whithout.
223
	* this check will prevent from multiple sending a form. history.back() also will never work
224
	*/
225
	final public function checkFTAN( $mode = 'POST')
226
	{
227
		$mode = (strtoupper($mode) != 'POST' ? '_GET' : '_POST');
228

    
229
		$isok= false;
230
		$secret= $this->_secret;
231

    
232
		if (isset($GLOBALS[$mode][$this->_tokenname])) 	{$latoken=$GLOBALS[$mode][$this->_tokenname];}
233
                else 						{return $isok;}
234

    
235
		$parts= explode('-', $latoken);
236
		if (count($parts)==3) {
237
			list($token,$timeout, $hash)= $parts;
238
			if ($hash==sha1($secret.'-'.$token.'-'.$timeout) AND $timeout > time())
239
			{$isok= true;}
240
		}
241

    
242
		return $isok;
243
	}
244

    
245
	/*
246
	* save values in session and returns a ID-key
247
	* @access public
248
	* @param mixed $value: the value for witch a key shall be generated and memorized
249
	* @return string:      a MD5-Key to use instead of the real value
250
	*
251
	* @requirements: an active session must be available
252
	* @description: IDKEY can handle string/numeric/array - vars. Each key is a
253
	*/
254
	final public function getIDKEY($value)
255
	{
256
		if( is_array($value) == true )
257
		{ // serialize value, if it's an array
258
			$value = serialize($value);
259
		}
260
		// crypt value with salt into md5-hash
261
		// and return a 16-digit block from random start position
262
		$key = substr( md5($this->_salt.(string)$value), rand(0,15), 16);
263
		do{ // loop while key/value isn't added
264
			if( !array_key_exists($key, $this->_IDKEYs) )
265
			{ // the key is unique, so store it in list
266
				$this->_IDKEYs[$key] = $value;
267
				break;
268
			}else {
269
				// if key already exist, increment the last five digits until the key is unique
270
				$key = substr($key, 0, -5).dechex(('0x'.substr($key, -5)) + 1);
271
			}
272
		}while(0);
273
		// store key/value-pairs into session
274
		$_SESSION[$this->_idkey_name] = $this->_IDKEYs;
275
		return $key;
276
	}
277

    
278
	/*
279
	* search for key in session and returns the original value
280
	* @access public
281
	* @param string $fieldname: name of the POST/GET-Field containing the key or hex-key itself
282
	* @param mixed $default: returnvalue if key not exist (default 0)
283
	* @param string $request: requestmethode can be POST or GET or '' (default POST)
284
	* @return mixed: the original value (string, numeric, array) or DEFAULT if request fails
285
	*
286
	* @requirements: an active session must be available
287
	* @description: each IDKEY can be checked only once. Unused Keys stay in list until the
288
	*               session is destroyed.
289
	*/
290
 	final public function checkIDKEY( $fieldname, $default = 0, $request = 'POST' )
291
	{
292
		$return_value = $default; // set returnvalue to default
293
		switch( strtoupper($request) )
294
		{
295
			case 'POST':
296
				$key = isset($_POST[$fieldname]) ? $_POST[$fieldname] : $fieldname;
297
				break;
298
			case 'GET':
299
				$key = isset($_GET[$fieldname]) ? $_GET[$fieldname] : $fieldname;
300
				break;
301
			default:
302
				$key = $fieldname;
303
		}
304
		if( preg_match('/[0-9a-f]{16}$/', $key) )
305
		{ // key must be a 16-digit hexvalue
306
			if( array_key_exists($key, $this->_IDKEYs))
307
			{ // check if key is stored in IDKEYs-list
308
				$return_value = $this->_IDKEYs[$key]; // get stored value
309
				unset($this->_IDKEYs[$key]);   // remove from list to prevent multiuse
310
				$_SESSION[$this->_idkey_name] = $this->_IDKEYs; // save modified list into session again
311
				if( preg_match('/.*(?<!\{).*(\d:\{.*;\}).*(?!\}).*/', $return_value) )
312
				{ // if value is a serialized array, then deserialize it
313
					$return_value = unserialize($return_value);
314
				}
315
			}
316
		}
317
		return $return_value;
318
	}
319

    
320
	/* @access public
321
	* @return void
322
	*
323
	* @requirements: an active session must be available
324
	* @description: remove all entries from IDKEY-Array
325
	*
326
	*/
327
 	final public function clearIDKEY()
328
	{
329
		 $this->_IDKEYs = array('0'=>'0');
330
	}
331

    
332

    
333
	## additional Functions needed cause the original ones lack some functionality
334
	## all are Copyright Norbert Heimsath, heimsath.org
335
	## released under GPLv3  http://www.gnu.org/licenses/gpl.html
336

    
337
	/* Made because ctype_ gives strange results using mb Strings*/ 
338
 	private function _validate_alalnum($input){
339
	# alphanumerical string that starts whith a letter charakter 
340
		if (preg_match('/^[a-zA-Z][0-9a-zA-Z]+$/u', $input))
341
			{return false;}
342
	
343
	return "The given input is not an alphanumeric string.";
344
	} 
345

    
346
 	private function _is04($input){
347
	# integer value between 0-4
348
		if (preg_match('/^[0-4]$/', $input)) {return false;}
349
	
350
	return "The given input is not an alphanumeric string.";
351
	} 
352

    
353

    
354
	private function _getip($ipblocks=4){
355
	/*
356
	Just a function to get User ip even if hes behind a proxy
357
	*/
358
		$ip    	=   ""; //Ip address result
359
		$cutip	=   ""; //Ip address cut to limit
360
	
361
		# mabe user is behind a Proxy but we need his real ip address if we got a nice Proxyserver, 
362
		# it sends us the "HTTP_X_FORWARDED_FOR" Header. Sometimes there is more than one Proxy.
363
		# !!!!!! THIS PART WAS NEVER TESTED BECAUSE I ONLY GOT A DIRECT INTERNET CONNECTION !!!!!!
364
		# long2ip(ip2long($lastip)) makes sure we got nothing else than an ip into our script ;-)
365
		# !!!!! WARNING the 'HTTP_X_FORWARDED_FOR' Part is NOT TESTED !!!!!
366
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
367
		{
368
			$iplist= explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
369
			$lastip = array_pop($iplist);
370
			$ip.= long2ip(ip2long($lastip));
371
		}
372
		
373
		/* If theres no other supported info we just use REMOTE_ADDR
374
		If we have a fiendly proxy supporting  HTTP_X_FORWARDED_FOR its ok to use the full address.
375
		But if there is no HTTP_X_FORWARDED_FOR we can  not be sure if its a proxy or whatever, so we use the 
376
		blocklimit for IP address. 
377
		*/
378
		else 
379
		{
380
			$ip = long2ip(ip2long($_SERVER['REMOTE_ADDR']));
381
	
382
			# ipblocks used here defines how many blocks of the ip adress are checked xxx.xxx.xxx.xxx
383
			$blocks = explode('.', $ip);
384
			for ($i=0; $i<$ipblocks; $i++){
385
				$cutip.= $blocks[$i] . '.';
386
				}
387
			$ip=substr($cutip, 0, -1);
388
		}
389
		
390
	return $ip;
391
	}
392
	
393
	private function _browser_fingerprint($encode=true,$fpsalt="My Fingerprint: "){
394
	/*
395
	Creates a basic Browser Fingerprint for securing the session and forms.
396
	*/
397
	
398
		$fingerprint=$fpsalt;
399
		if (isset($_SERVER['HTTP_USER_AGENT'])){ $fingerprint .= $_SERVER['HTTP_USER_AGENT'];}
400
		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];}
401
		if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_ENCODING'];}
402
		if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_CHARSET'];}
403
		
404
		$fingerprint.= $this->_getip($this->_useipblocks);
405
		
406
		if ($encode){$fingerprint=md5($fingerprint);}
407
	
408
	return $fingerprint;
409
	}
410
	##
411
	## additional Functions END
412
	##
413
}
(2-2/19)