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 1499 2011-08-12 11:21:25Z DarkViper $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/SecureForm.mtab.php $
15
 * @lastmodified    $Date: 2011-08-12 13:21:25 +0200 (Fri, 12 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
if(!defined('WB_PATH')) {
51
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
52
	throw new IllegalFileException();
53
}
54
/* -------------------------------------------------------- */
55

    
56
class SecureForm {
57

    
58
	const FRONTEND = 0;
59
	const BACKEND  = 1;      
60

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

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

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

    
80
        	## additional constants and stuff for global configuration
81

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

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

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

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

    
123
	private function _generate_secret(){
124

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

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

    
139

    
140

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

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

    
174
	private function _generate_serverdata(){
175

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

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

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

    
202
		$timeout= time()+$this->_timeout;
203

    
204
		#mt_srand(hexdec(crc32(microtime()));
205
                $token= dechex(mt_rand());
206

    
207
                $hash= sha1($secret.'-'.$token.'-'.$timeout);
208
		$signed= $token.'-'.$timeout.'-'.$hash;
209

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

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

    
231
		$isok= false;
232
		$secret= $this->_secret;
233

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

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

    
244
		return $isok;
245
	}
246

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

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

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

    
334

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

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

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

    
355

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