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 1475 2011-07-12 23:07:10Z Luisehahne $
14
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/SecureForm.mtab.php $
15
 * @lastmodified    $Date: 2011-07-13 01:07:10 +0200 (Wed, 13 Jul 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
class SecureForm {
50

    
51
	const FRONTEND = 0;
52
	const BACKEND  = 1;      
53

    
54
        ## additional private data
55
	private $_secret      	 = '5609bnefg93jmgi99igjefg';
56
	private $_secrettime  	 = 86400;   #Approx. one day 
57
        private $_tokenname   	 = 'formtoken';
58
	private $_timeout	 = 7200;         
59
	private $_useipblocks	 = 2;
60
	private $_usefingerprint = true;
61
        ### additional private data
62

    
63
        private $_FTAN           = '';
64
	private $_IDKEYs         = array('0'=>'0');
65
	private $_idkey_name     = '';
66
	private $_salt           = '';
67
	private $_fingerprint    = '';
68
	private $_serverdata  	 = '';
69

    
70
	/* Construtor */
71
	protected function __construct($mode = self::FRONTEND){
72

    
73
        	## additional constants and stuff for global configuration
74

    
75
		# Secret can contain anything its the base for the secret part of the hash
76
                if (defined ('WB_SECFORM_SECRET')){ 	
77
			$this->_secret=WB_SECFORM_SECRET;
78
		}
79

    
80
		# shall we use fingerprinting
81
                if (defined ('WB_SECFORM_USEFP') AND WB_SECFORM_USEFP===false){
82
			$this->_usefingerprint	= false;
83
		}
84

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

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

    
116
	private function _generate_secret(){
117

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

    
126
		$secret .= $this->_secret.$this->_serverdata.session_id();
127
		if ($this->_usefingerprint){$secret.= $this->_browser_fingerprint;}
128
		
129
	return $secret;
130
	}
131

    
132

    
133

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

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

    
167
	private function _generate_serverdata(){
168

    
169
	 	$serverdata  = ( isset($_SERVER['SERVER_SIGNATURE']) ) ? $_SERVER['SERVER_SIGNATURE'] : '2';
170
		$serverdata .= ( isset($_SERVER['SERVER_SOFTWARE']) ) ? $_SERVER['SERVER_SOFTWARE'] : '3';
171
		$serverdata .= ( isset($_SERVER['SERVER_NAME']) ) ? $_SERVER['SERVER_NAME'] : '5';
172
		$serverdata .= ( isset($_SERVER['SERVER_ADDR']) ) ? $_SERVER['SERVER_ADDR'] : '7';
173
		$serverdata .= ( isset($_SERVER['SERVER_PORT']) ) ? $_SERVER['SERVER_PORT'] : '11';
174
		$serverdata .= ( isset($_SERVER['SERVER_ADMIN']) ) ? $_SERVER['SERVER_ADMIN'] : '13';
175
		$serverdata .= PHP_VERSION;
176
	return  $serverdata;
177
	}
178

    
179
        // fake funktion , just exits to avoid error message 
180
        final protected function createFTAN(){}
181

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

    
195
		$timeout= time()+$this->_timeout;
196

    
197
		#mt_srand(hexdec(crc32(microtime()));
198
                $token= dechex(mt_rand());
199

    
200
                $hash= sha1($secret.'-'.$token.'-'.$timeout);
201
		$signed= $token.'-'.$timeout.'-'.$hash;
202

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

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

    
224
		$isok= false;
225
		$secret= $this->_secret;
226

    
227
		if (isset($GLOBALS[$mode][$this->_tokenname])) 	{$latoken=$GLOBALS[$mode][$this->_tokenname];}
228
                else 						{return $isok;}
229

    
230
		$parts= explode('-', $latoken);
231
		if (count($parts)==3) {
232
			list($token,$timeout, $hash)= $parts;
233
			if ($hash==sha1($secret.'-'.$token.'-'.$timeout) AND $timeout > time())
234
			{$isok= true;}
235
		}
236

    
237
		return $isok;
238
	}
239

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

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

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

    
327

    
328
	## additional Functions needed cause the original ones lack some functionality
329
	## all are Copyright Norbert Heimsath, heimsath.org
330
	## released under GPLv3  http://www.gnu.org/licenses/gpl.html
331

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

    
341
 	private function _is04($input){
342
	# integer value between 0-4
343
		if (preg_match('/^[0-4]$/', $input)) {return false;}
344
	
345
	return "The given input is not an alphanumeric string.";
346
	} 
347

    
348

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