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 1561 2012-01-05 11:56:34Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/SecureForm.mtab.php $
15
 * @lastmodified    $Date: 2012-01-05 12:56:34 +0100 (Thu, 05 Jan 2012) $
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
		$usedOctets = ( defined('FINGERPRINT_WITH_IP_OCTETS') ) ? (intval(FINGERPRINT_WITH_IP_OCTETS) % 5) : 2;
177
		$serverdata  = '';
178
	 	$serverdata .= ( isset($_SERVER['SERVER_SIGNATURE']) ) ? $_SERVER['SERVER_SIGNATURE'] : '2';
179
		$serverdata .= ( isset($_SERVER['SERVER_SOFTWARE']) ) ? $_SERVER['SERVER_SOFTWARE'] : '3';
180
		$serverdata .= ( isset($_SERVER['SERVER_NAME']) ) ? $_SERVER['SERVER_NAME'] : '5';
181
		$serverIp = ( isset($_SERVER['SERVER_ADDR']) ) ? $_SERVER['SERVER_ADDR'] : '';
182
		if(($serverIp != '') && ($usedOctets > 0)){
183
			$ip = explode('.', $serverIp);
184
			while(sizeof($ip) > $usedOctets) { array_pop($ip); }
185
			$serverdata .= implode('.', $ip);
186
		}else {
187
			$serverdata .= '7';
188
		}
189
		$serverdata .= ( isset($_SERVER['SERVER_PORT']) ) ? $_SERVER['SERVER_PORT'] : '11';
190
		$serverdata .= ( isset($_SERVER['SERVER_ADMIN']) ) ? $_SERVER['SERVER_ADMIN'] : '13';
191
		$serverdata .= PHP_VERSION;
192
	return  $serverdata;
193
	}
194

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

    
198
	/*
199
	* creates selfsigning Formular transactionnumbers for unique use
200
	* @access public
201
	* @param bool $asTAG: true returns a complete prepared, hidden HTML-Input-Tag (default)
202
	*                     false returns an GET argument 'key=value'
203
	* @return mixed:      string
204
	*
205
	* requirements: an active session must not be available but it makes no sense whithout :-)
206
	*/
207
	final public function getFTAN( $as_tag = true)
208
	{
209
		$secret= $this->_secret;
210

    
211
		$timeout= time()+$this->_timeout;
212

    
213
		#mt_srand(hexdec(crc32(microtime()));
214
                $token= dechex(mt_rand());
215

    
216
                $hash= sha1($secret.'-'.$token.'-'.$timeout);
217
		$signed= $token.'-'.$timeout.'-'.$hash;
218

    
219
		if($as_tag == true)
220
		{ // by default return a complete, hidden <input>-tag
221
			return '<input type="hidden" name="'.$this->_tokenname.'" value="'.htmlspecialchars($signed).'" title="" alt="" />';
222
		}else{ // return an array with raw tokenname=value
223
			return $this->_tokenname.'='.$signed;
224
		}
225
	}
226

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

    
240
		$isok= false;
241
		$secret= $this->_secret;
242

    
243
		if (isset($GLOBALS[$mode][$this->_tokenname])) 	{$latoken=$GLOBALS[$mode][$this->_tokenname];}
244
                else 						{return $isok;}
245

    
246
		$parts= explode('-', $latoken);
247
		if (count($parts)==3) {
248
			list($token,$timeout, $hash)= $parts;
249
			if ($hash==sha1($secret.'-'.$token.'-'.$timeout) AND $timeout > time())
250
			{$isok= true;}
251
		}
252

    
253
		return $isok;
254
	}
255

    
256
	/*
257
	* save values in session and returns a ID-key
258
	* @access public
259
	* @param mixed $value: the value for witch a key shall be generated and memorized
260
	* @return string:      a MD5-Key to use instead of the real value
261
	*
262
	* @requirements: an active session must be available
263
	* @description: IDKEY can handle string/numeric/array - vars. Each key is a
264
	*/
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);
270
		}
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;
286
		return $key;
287
	}
288

    
289
	/*
290
	* search for key in session and returns the original value
291
	* @access public
292
	* @param string $fieldname: name of the POST/GET-Field containing the key or hex-key itself
293
	* @param mixed $default: returnvalue if key not exist (default 0)
294
	* @param string $request: requestmethode can be POST or GET or '' (default POST)
295
	* @return mixed: the original value (string, numeric, array) or DEFAULT if request fails
296
	*
297
	* @requirements: an active session must be available
298
	* @description: each IDKEY can be checked only once. Unused Keys stay in list until the
299
	*               session is destroyed.
300
	*/
301
 	final public function checkIDKEY( $fieldname, $default = 0, $request = 'POST' )
302
	{
303
		$return_value = $default; // set returnvalue to default
304
		switch( strtoupper($request) )
305
		{
306
			case 'POST':
307
				$key = isset($_POST[$fieldname]) ? $_POST[$fieldname] : $fieldname;
308
				break;
309
			case 'GET':
310
				$key = isset($_GET[$fieldname]) ? $_GET[$fieldname] : $fieldname;
311
				break;
312
			default:
313
				$key = $fieldname;
314
		}
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
322
				if( preg_match('/.*(?<!\{).*(\d:\{.*;\}).*(?!\}).*/', $return_value) )
323
				{ // if value is a serialized array, then deserialize it
324
					$return_value = unserialize($return_value);
325
				}
326
			}
327
		}
328
		return $return_value;
329
	}
330

    
331
	/* @access public
332
	* @return void
333
	*
334
	* @requirements: an active session must be available
335
	* @description: remove all entries from IDKEY-Array
336
	*
337
	*/
338
 	final public function clearIDKEY()
339
	{
340
		 $this->_IDKEYs = array('0'=>'0');
341
	}
342

    
343

    
344
	## additional Functions needed cause the original ones lack some functionality
345
	## all are Copyright Norbert Heimsath, heimsath.org
346
	## released under GPLv3  http://www.gnu.org/licenses/gpl.html
347

    
348
	/* Made because ctype_ gives strange results using mb Strings*/ 
349
 	private function _validate_alalnum($input){
350
	# alphanumerical string that starts whith a letter charakter 
351
		if (preg_match('/^[a-zA-Z][0-9a-zA-Z]+$/u', $input))
352
			{return false;}
353
	
354
	return "The given input is not an alphanumeric string.";
355
	} 
356

    
357
 	private function _is04($input){
358
	# integer value between 0-4
359
		if (preg_match('/^[0-4]$/', $input)) {return false;}
360
	
361
	return "The given input is not an alphanumeric string.";
362
	} 
363

    
364

    
365
	private function _getip($ipblocks=4){
366
	/*
367
	Just a function to get User ip even if hes behind a proxy
368
	*/
369
		$ip    	=   ""; //Ip address result
370
		$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, 
373
		# it sends us the "HTTP_X_FORWARDED_FOR" Header. Sometimes there is more than one Proxy.
374
		# !!!!!! THIS PART WAS NEVER TESTED BECAUSE I ONLY GOT A DIRECT INTERNET CONNECTION !!!!!!
375
		# long2ip(ip2long($lastip)) makes sure we got nothing else than an ip into our script ;-)
376
		# !!!!! WARNING the 'HTTP_X_FORWARDED_FOR' Part is NOT TESTED !!!!!
377
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
378
		{
379
			$iplist= explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
380
			$lastip = array_pop($iplist);
381
			$ip.= long2ip(ip2long($lastip));
382
		}
383
		
384
		/* If theres no other supported info we just use REMOTE_ADDR
385
		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. 
388
		*/
389
		else 
390
		{
391
			$ip = long2ip(ip2long($_SERVER['REMOTE_ADDR']));
392
	
393
			# ipblocks used here defines how many blocks of the ip adress are checked xxx.xxx.xxx.xxx
394
			$blocks = explode('.', $ip);
395
			for ($i=0; $i<$ipblocks; $i++){
396
				$cutip.= $blocks[$i] . '.';
397
				}
398
			$ip=substr($cutip, 0, -1);
399
		}
400
		
401
	return $ip;
402
	}
403
	
404
	private function _browser_fingerprint($encode=true,$fpsalt="My Fingerprint: "){
405
	/*
406
	Creates a basic Browser Fingerprint for securing the session and forms.
407
	*/
408
	
409
		$fingerprint=$fpsalt;
410
		if (isset($_SERVER['HTTP_USER_AGENT'])){ $fingerprint .= $_SERVER['HTTP_USER_AGENT'];}
411
		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_LANGUAGE'];}
412
		if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_ENCODING'];}
413
		if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])){ $fingerprint .= $_SERVER['HTTP_ACCEPT_CHARSET'];}
414
		
415
		$fingerprint.= $this->_getip($this->_useipblocks);
416
		
417
		if ($encode){$fingerprint=md5($fingerprint);}
418
	
419
	return $fingerprint;
420
	}
421
	##
422
	## additional Functions END
423
	##
424
}
(5-5/23)