Project

General

Profile

« Previous | Next » 

Revision 1699

Added by Dietmar almost 12 years ago

! Fixed IDKEY in Secureform.mtab to solve issues whith Security warnings
! on pages that used a lot of IDKEYS. (fixed by NorHei)

View differences:

SecureForm.mtab.php
17 17
 */
18 18
##  Heavy patched version, idea for patches based on :
19 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 
20
##  Whith this patch the token System now allows for multiple browser tabs but
21 21
##  denies the use of multiple browsers.
22 22
##  You can configure this class by adding several constants to your config.php
23
##  All Patches are Copyright Norbert Heimsath released under GPLv3 
23
##  All Patches are Copyright Norbert Heimsath released under GPLv3
24 24
##  http://www.gnu.org/licenses/gpl.html
25 25
##  Take a look at  __construkt  for configuration options(constants).
26 26
##  Patch version 0.3.5
27 27

  
28 28
/**
29
 *
29 30
 * If you want some special configuration put this somewhere in your config.php for
30 31
 * example or just uncomment the lines here
31 32
 *
......
44 45
 * define ('WB_SECFORM_TOKENNAME','my3form3');
45 46
 * how many blocks of the IP should be used in fingerprint 0=no ipcheck, possible values 0-4
46 47
 * define ('FINGERPRINT_WITH_IP_OCTETS',2);
48
 *
49
 * Fixed IDKEY in Secureform 2012/08/27 by NorHey
50
 *
51
 * I still had problems whith Security warnings on pages that used alot of
52
 * IDKEYS. For example if i tried to move a field in the basic form module
53
 * i had one  Warning on in about 15 atempts.
54
 *
55
 * Another Problem: unused old IDKEYS where never deleted so session got
56
 * spammed by idkeys.
57
 *
58
 * So i made a more unique ID, recursive checking for overlapping ids,
59
 * added a tiemout for IDKEYS (same as for FTAN) and added a page parameter
60
 * to instantly delete all keys from a pagecall if one is used.
61
 *
62
 * Last thing i added is an additional parameter that allows the use of
63
 * IDKEYS whith ajax scripts. If this setting is used, the key is not
64
 * removed and can be used multiple times. (this is a small security risk
65
 * but nothing compared to the 1 in 16 chance to guess the key that we had before.)
66
 *
47 67
 */
68

  
48 69
/* -------------------------------------------------------- */
49 70
// Must include code to stop this file being accessed directly
50 71
if(!defined('WB_PATH')) {
......
56 77
class SecureForm {
57 78

  
58 79
	const FRONTEND = 0;
59
	const BACKEND  = 1;      
80
	const BACKEND  = 1;
60 81

  
61 82
        ## additional private data
62 83
	private $_secret      	 = '5609bnefg93jmgi99igjefg';
63
	private $_secrettime  	 = 86400;   #Approx. one day 
84
	private $_secrettime  	 = 86400;   #Approx. one day
64 85
        private $_tokenname   	 = 'formtoken';
65
	private $_timeout	 = 7200;         
86
	private $_timeout	 = 7200;
66 87
	private $_useipblocks	 = 2;
67 88
	private $_usefingerprint = true;
89
	private $_page_uid = "";
90
	private $_page_id = "";
68 91
        ### additional private data
69 92

  
70 93
        private $_FTAN           = '';
......
77 100
	/* Construtor */
78 101
	protected function __construct($mode = self::FRONTEND){
79 102

  
80
        	## additional constants and stuff for global configuration
103
        	// additional constants and stuff for global configuration
81 104

  
82
		# Secret can contain anything its the base for the secret part of the hash
83
                if (defined ('WB_SECFORM_SECRET')){ 	
105
		// Secret can contain anything its the base for the secret part of the hash
106
                if (defined ('WB_SECFORM_SECRET')){
84 107
			$this->_secret=WB_SECFORM_SECRET;
85 108
		}
86 109

  
87
		# shall we use fingerprinting
110
		// shall we use fingerprinting
88 111
                if (defined ('WB_SECFORM_USEFP') AND WB_SECFORM_USEFP===false){
89 112
			$this->_usefingerprint	= false;
90 113
		}
91 114

  
92
                # Timeout till the form token times out. Integer value between 0-86400 seconds (one day)
115
                // Timeout till the form token times out. Integer value between 0-86400 seconds (one day)
93 116
                if (defined ('WB_SECFORM_TIMEOUT') AND is_numeric(WB_SECFORM_TIMEOUT) AND intval(WB_SECFORM_TIMEOUT) >=0 AND intval(WB_SECFORM_TIMEOUT) <=86400 ){
94 117
			$this->_timeout=intval(WB_SECFORM_TIMEOUT);
95 118
		}
96
		# Name for the token form element only alphanumerical string allowed that starts whith a charakter
119
		// Name for the token form element only alphanumerical string allowed that starts whith a charakter
97 120
                if (defined ('WB_SECFORM_TOKENNAME') AND !$this->_validate_alalnum(WB_SECFORM_TOKENNAME)){
98 121
			$this->_tokenname=WB_SECFORM_TOKENNAME;
99 122
		}
100
		# how many bloks of the IP should be used 0=no ipcheck 
123
		// how many bloks of the IP should be used 0=no ipcheck
101 124
                if (defined ('FINGERPRINT_WITH_IP_OCTETS') AND !$this->_is04(FINGERPRINT_WITH_IP_OCTETS)){
102 125
			$this->_useipblocks=FINGERPRINT_WITH_IP_OCTETS;
103 126
                }
104
		## additional stuff end 
127

  
128
		// create a unique pageid for per page management of idkeys , especially
129
		// to identify and delete unused ones from same page call.
130
		$this->_page_uid = uniqid (rand(), true);
131

  
132
		// additional stuff end
105 133
		$this->_browser_fingerprint   = $this->_browser_fingerprint(true);
106 134
		$this->_fingerprint   = $this->_generate_fingerprint();
107 135
		$this->_serverdata    = $this->_generate_serverdata();
......
132 160

  
133 161
		$secret .= $this->_secret.$this->_serverdata.session_id();
134 162
		if ($this->_usefingerprint){$secret.= $this->_browser_fingerprint;}
135
		
163

  
136 164
	return $secret;
137 165
	}
138 166

  
......
155 183
	{
156 184
	// server depending values
157 185
 		$fingerprint  = $this->_generate_serverdata();
158
		
186

  
159 187
	// client depending values
160 188
		$fingerprint .= ( isset($_SERVER['HTTP_USER_AGENT']) ) ? $_SERVER['HTTP_USER_AGENT'] : '17';
161 189
		$usedOctets = ( defined('FINGERPRINT_WITH_IP_OCTETS') ) ? intval(defined('FINGERPRINT_WITH_IP_OCTETS')) : 0;
......
192 220
	return  $serverdata;
193 221
	}
194 222

  
195
        // fake funktion , just exits to avoid error message 
223
        // fake funktion , just exits to avoid error message
196 224
        final protected function createFTAN(){}
197 225

  
198 226
	/*
......
261 289
	*
262 290
	* @requirements: an active session must be available
263 291
	* @description: IDKEY can handle string/numeric/array - vars. Each key is a
292
	*  shortened md5 String
264 293
	*/
265
	final public function getIDKEY($value)
266
	{
267
		if( is_array($value) == true )
268
		{ // serialize value, if it's an array
269
			$value = serialize($value);
294
	final public function getIDKEY($value) {
295

  
296

  
297
		// serialize value, if it's an array
298
		if( is_array($value) == true ) $value = serialize($value);
299

  
300
		// cryptsome random stuff with salt into md5-hash
301
		$key = md5($this->_salt.rand().uniqid('', true));
302

  
303
		//shorten hash a bit
304
		$key = str_replace(array("=","$","+"),array("-","_",""),base64_encode(pack('H*',$key)));
305

  
306
		// the key is unique, so store it in list
307
		if( !array_key_exists($key,  $_SESSION[$this->_idkey_name])) {
308
			$_SESSION[$this->_idkey_name][$key]['value'] = $value;
309
			$_SESSION[$this->_idkey_name][$key]['time'] = time();
310
			$_SESSION[$this->_idkey_name][$key]['page'] = $this->_page_uid;
270 311
		}
271
		// crypt value with salt into md5-hash
272
		// and return a 16-digit block from random start position
273
		$key = substr( md5($this->_salt.(string)$value), rand(0,15), 16);
274
		do{ // loop while key/value isn't added
275
			if( !array_key_exists($key, $this->_IDKEYs) )
276
			{ // the key is unique, so store it in list
277
				$this->_IDKEYs[$key] = $value;
278
				break;
279
			}else {
280
				// if key already exist, increment the last five digits until the key is unique
281
				$key = substr($key, 0, -5).dechex(('0x'.substr($key, -5)) + 1);
282
			}
283
		}while(0);
284
		// store key/value-pairs into session
285
		$_SESSION[$this->_idkey_name] = $this->_IDKEYs;
312
		// if key already exist, try again, dont store as it already been stored
313
		else $key = $this->getIDKEY($value);
314

  
286 315
		return $key;
287 316
	}
288 317

  
......
298 327
	* @description: each IDKEY can be checked only once. Unused Keys stay in list until the
299 328
	*               session is destroyed.
300 329
	*/
301
 	final public function checkIDKEY( $fieldname, $default = 0, $request = 'POST' )
330
 	final public function checkIDKEY( $fieldname, $default = 0, $request = 'POST', $ajax=false)
302 331
	{
332
		//Remove timed out idkeys
333
		$_SESSION[$this->_idkey_name]= array_filter( $_SESSION[$this->_idkey_name],array($this, "_timedout"));
334

  
335

  
303 336
		$return_value = $default; // set returnvalue to default
304 337
		switch( strtoupper($request) )
305 338
		{
......
312 345
			default:
313 346
				$key = $fieldname;
314 347
		}
315
		if( preg_match('/[0-9a-f]{16}$/', $key) )
316
		{ // key must be a 16-digit hexvalue
317
			if( array_key_exists($key, $this->_IDKEYs))
318
			{ // check if key is stored in IDKEYs-list
319
				$return_value = $this->_IDKEYs[$key]; // get stored value
320
				unset($this->_IDKEYs[$key]);   // remove from list to prevent multiuse
321
				$_SESSION[$this->_idkey_name] = $this->_IDKEYs; // save modified list into session again
348
		if( preg_match('/[0-9a-zA-Z\-\_]{1,32}$/', $key) ) { // key must match the generated ones
349
			if( array_key_exists($key, $_SESSION[$this->_idkey_name])) { // check if key is stored in IDKEYs-list
350
				$return_value = $_SESSION[$this->_idkey_name][$key]['value']; // get stored value
351
				$this->_page_id = $_SESSION[$this->_idkey_name][$key]['page'];
352

  
353
				if ($ajax === false) {
354
					//Remove all keys from this page to prevent multiuse and session mem usage
355
					$_SESSION[$this->_idkey_name]= array_filter( $_SESSION[$this->_idkey_name],array($this, "_fpages"));
356
					//unset($_SESSION[$this->_idkey_name][$key]);   // remove from list to prevent multiuse
357
				}
322 358
				if( preg_match('/.*(?<!\{).*(\d:\{.*;\}).*(?!\}).*/', $return_value) )
323 359
				{ // if value is a serialized array, then deserialize it
324 360
					$return_value = unserialize($return_value);
325 361
				}
326 362
			}
327 363
		}
364

  
328 365
		return $return_value;
329 366
	}
330 367

  
368
 	private function _timedout( $var ) {
369
		if ($var['time'] < time()-$this->_timeout) return false;
370
		return true;
371
	}
372
 	private function _fpages( $var ) {
373
		if ($var['page'] == $this->_page_id) return false;
374
		return true;
375
	}
376

  
331 377
	/* @access public
332 378
	* @return void
333 379
	*
......
345 391
	## all are Copyright Norbert Heimsath, heimsath.org
346 392
	## released under GPLv3  http://www.gnu.org/licenses/gpl.html
347 393

  
348
	/* Made because ctype_ gives strange results using mb Strings*/ 
394
	/* Made because ctype_ gives strange results using mb Strings*/
349 395
 	private function _validate_alalnum($input){
350
	# alphanumerical string that starts whith a letter charakter 
396
	# alphanumerical string that starts whith a letter charakter
351 397
		if (preg_match('/^[a-zA-Z][0-9a-zA-Z]+$/u', $input))
352 398
			{return false;}
353
	
399

  
354 400
	return "The given input is not an alphanumeric string.";
355
	} 
401
	}
356 402

  
357 403
 	private function _is04($input){
358 404
	# integer value between 0-4
359 405
		if (preg_match('/^[0-4]$/', $input)) {return false;}
360
	
406

  
361 407
	return "The given input is not an alphanumeric string.";
362
	} 
408
	}
363 409

  
364 410

  
365 411
	private function _getip($ipblocks=4){
......
368 414
	*/
369 415
		$ip    	=   ""; //Ip address result
370 416
		$cutip	=   ""; //Ip address cut to limit
371
	
372
		# mabe user is behind a Proxy but we need his real ip address if we got a nice Proxyserver, 
417

  
418
		# mabe user is behind a Proxy but we need his real ip address if we got a nice Proxyserver,
373 419
		# it sends us the "HTTP_X_FORWARDED_FOR" Header. Sometimes there is more than one Proxy.
374 420
		# !!!!!! THIS PART WAS NEVER TESTED BECAUSE I ONLY GOT A DIRECT INTERNET CONNECTION !!!!!!
375 421
		# long2ip(ip2long($lastip)) makes sure we got nothing else than an ip into our script ;-)
......
380 426
			$lastip = array_pop($iplist);
381 427
			$ip.= long2ip(ip2long($lastip));
382 428
		}
383
		
429

  
384 430
		/* If theres no other supported info we just use REMOTE_ADDR
385 431
		If we have a fiendly proxy supporting  HTTP_X_FORWARDED_FOR its ok to use the full address.
386
		But if there is no HTTP_X_FORWARDED_FOR we can  not be sure if its a proxy or whatever, so we use the 
387
		blocklimit for IP address. 
432
		But if there is no HTTP_X_FORWARDED_FOR we can  not be sure if its a proxy or whatever, so we use the
433
		blocklimit for IP address.
388 434
		*/
389
		else 
435
		else
390 436
		{
391 437
			$ip = long2ip(ip2long($_SERVER['REMOTE_ADDR']));
392
	
438

  
393 439
			# ipblocks used here defines how many blocks of the ip adress are checked xxx.xxx.xxx.xxx
394 440
			$blocks = explode('.', $ip);
395 441
			for ($i=0; $i<$ipblocks; $i++){
......
397 443
				}
398 444
			$ip=substr($cutip, 0, -1);
399 445
		}
400
		
446

  
401 447
	return $ip;
402 448
	}
403
	
449

  
404 450
	private function _browser_fingerprint($encode=true,$fpsalt="My Fingerprint: "){
405 451
	/*
406 452
	Creates a basic Browser Fingerprint for securing the session and forms.
407 453
	*/
408
	
454

  
409 455
		$fingerprint=$fpsalt;
410 456
		if (isset($_SERVER['HTTP_USER_AGENT'])){ $fingerprint .= $_SERVER['HTTP_USER_AGENT'];}
411 457
		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];}
412 458
		if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_ENCODING'];}
413 459
		if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_CHARSET'];}
414
		
460

  
415 461
		$fingerprint.= $this->_getip($this->_useipblocks);
416
		
462

  
417 463
		if ($encode){$fingerprint=md5($fingerprint);}
418
	
464

  
419 465
	return $fingerprint;
420 466
	}
421 467
	##
422 468
	## additional Functions END
423 469
	##
424
}
470
}

Also available in: Unified diff