Project

General

Profile

1
<?php
2
/**
3
 *
4
 * @category        framework
5
 * @package         SecureForm
6
 * @author          Independend-Software-Team
7
 * @author          WebsiteBaker Project
8
 * @copyright       2004-2009, Ryan Djurovich
9
 * @copyright       2009-2011, Website Baker Org. e.V.
10
 * @link			http://www.websitebaker2.org/
11
 * @license         http://www.gnu.org/licenses/gpl.html
12
 * @platform        WebsiteBaker 2.8.x
13
 * @requirements    PHP 5.2.2 and higher
14
 * @version         $Id: SecureForm.php 1524 2011-11-13 20:14:01Z Luisehahne $
15
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/SecureForm.php $
16
 * @lastmodified    $Date: 2011-11-13 21:14:01 +0100 (Sun, 13 Nov 2011) $
17
 * @description
18
 */
19
/* -------------------------------------------------------- */
20
// Must include code to stop this file being accessed directly
21
if(!defined('WB_PATH')) {
22
	require_once(dirname(__FILE__).'/globalExceptionHandler.php');
23
	throw new IllegalFileException();
24
}
25
/* -------------------------------------------------------- */
26

    
27
class SecureForm {
28

    
29
	const FRONTEND = 0;
30
	const BACKEND  = 1;
31

    
32

    
33
	private $_FTAN        = '';
34
	private $_IDKEYs      = array('0'=>'0');
35
	private $_ftan_name   = '';
36
	private $_idkey_name  = '';
37
	private $_salt        = '';
38
	private $_fingerprint = '';
39

    
40
/* Construtor */
41
	protected function __construct($mode = self::FRONTEND)
42
	{
43
		$this->_FTAN  = '';
44
		$this->_salt = $this->_generate_salt();
45
		$this->_fingerprint = $this->_generate_fingerprint();
46
	// generate names for session variables
47
		$this->_ftan_name =
48
			substr($this->_fingerprint, -(16 + hexdec($this->_fingerprint[0])), 16);
49
	// make sure there is a alpha-letter at first position
50
		$this->_ftan_name = $this->_makeFirst2Letter($this->_ftan_name);
51
		$this->_idkey_name =
52
			substr($this->_fingerprint, hexdec($this->_fingerprint[strlen($this->_fingerprint)-1]), 16);
53
	// make sure there is a alpha-letter at first position
54
		$this->_idkey_name = $this->_makeFirst2Letter($this->_idkey_name);
55
	// takeover id_keys from session if available
56
		if(isset($_SESSION[$this->_idkey_name]) && is_array($_SESSION[$this->_idkey_name]))
57
		{
58
			$this->_IDKEYs = $_SESSION[$this->_idkey_name];
59
		}else{
60
			$this->_IDKEYs = array('0'=>'0');
61
			$_SESSION[$this->_idkey_name] = $this->_IDKEYs;
62
		}
63
	}
64

    
65
	private function _makeFirst2Letter($string)
66
	{
67
		$string[0] = dechex(10 + (hexdec($string[0]) % 5));
68
		return $string;
69
	}
70

    
71
	private function _generate_salt()
72
	{
73
		if(function_exists('microtime'))
74
		{
75
			list($usec, $sec) = explode(" ", microtime());
76
			$salt = (string)((float)$usec + (float)$sec);
77
		}else{
78
			$salt = (string)time();
79
		}
80
		$salt = (string)rand(10000, 99999) . $salt . (string)rand(10000, 99999);
81
		return md5($salt);
82
	}
83

    
84
	private function _generate_fingerprint()
85
	{
86
		// server depending values
87
		$fingerprint  = ( isset($_SERVER['SERVER_SIGNATURE']) ) ? $_SERVER['SERVER_SIGNATURE'] : '2';
88
		$fingerprint .= ( isset($_SERVER['SERVER_SOFTWARE']) ) ? $_SERVER['SERVER_SOFTWARE'] : '3';
89
		$fingerprint .= ( isset($_SERVER['SERVER_NAME']) ) ? $_SERVER['SERVER_NAME'] : '5';
90
		$fingerprint .= ( isset($_SERVER['SERVER_ADDR']) ) ? $_SERVER['SERVER_ADDR'] : '7';
91
		$fingerprint .= ( isset($_SERVER['SERVER_PORT']) ) ? $_SERVER['SERVER_PORT'] : '11';
92
		$fingerprint .= ( isset($_SERVER['SERVER_ADMIN']) ) ? $_SERVER['SERVER_ADMIN'] : '13';
93
		$fingerprint .= __FILE__;
94
		$fingerprint .= PHP_VERSION;
95
		// client depending values
96
		$fingerprint .= ( isset($_SERVER['HTTP_USER_AGENT']) ) ? $_SERVER['HTTP_USER_AGENT'] : '19';
97
		$usedOctets = ( defined('FINGERPRINT_WITH_IP_OCTETS') ) ? (intval(FINGERPRINT_WITH_IP_OCTETS) % 5) : 2;
98
		$clientIp = ( isset($_SERVER['REMOTE_ADDR'])  ? $_SERVER['REMOTE_ADDR'] : '' );
99
		if(($clientIp != '') && ($usedOctets > 0)){
100
			$ip = explode('.', $clientIp);
101
			while(sizeof($ip) > $usedOctets) { array_pop($ip); }
102
			$clientIp = implode('.', $ip);
103
		}else {
104
			$clientIp = '23';
105
		}
106
		$fingerprint = md5($fingerprint.$clientIp);
107
		$lastDigit = hexdec($fingerprint[strlen($fingerprint)-1]);
108
		if ((hexdec($fingerprint[0]) + $lastDigit) == 16) {
109
			$fingerprint[strlen($fingerprint)-1] = dechex(($lastDigit + 6) % 16);
110
		}
111
		return $fingerprint;
112
	}
113

    
114
	private function _calcFtan($tanPart)
115
	{
116
		$ftan = md5($tanPart . $this->_fingerprint);
117
		$name = substr($ftan, -(16 + hexdec($ftan[0])), 16);
118
		$name = $this->_makeFirst2Letter($name);
119
		$value = substr($ftan, hexdec($ftan[strlen($ftan)-1]), 16);
120
		return array( $name, $value);
121
	}
122
/**
123
 * creates Formular transactionnumbers for unique use
124
 *
125
 * @return void
126
 * requirements: an active session must be available
127
 */
128
	final protected function createFTAN()
129
	{
130
		if( $this->_FTAN == '')
131
		{ // if no FTAN exists, create new one from time and salt
132
			$this->_FTAN = md5($this->_fingerprint.$this->_salt);
133
			$_SESSION[$this->_ftan_name] = $this->_FTAN; // store FTAN into session
134
		}
135
	}
136
/*
137
 * returns the current FTAN
138
 * @access public
139
 * @param bool $mode: true or POST returns a complete prepared, hidden HTML-Input-Tag (default)
140
 *                    false or GET returns an GET argument 'key=value'
141
 * @return mixed:     array or string
142
 */
143
	final public function getFTAN( $mode = 'POST')
144
	{
145
		$ftan = $this->_calcFtan($this->_FTAN);
146
		if((is_string($mode) && strtolower($mode) == 'post') || ($mode === true))
147
		{ // by default return a complete, hidden <input>-tag
148
			return '<input type="hidden" name="'.$ftan[0].'" value="'.$ftan[1].'" title="" alt="" />';
149
		}else{ // return an string with GET params (FTAN0=FTAN1)
150
			return $ftan[0].'='.$ftan[1];
151
		}
152
	}
153

    
154
/*
155
 * checks received form-transactionnumbers against session-stored one
156
 * @access public
157
 * @param string $mode: requestmethode POST(default) or GET
158
 * @return bool:    true if numbers matches against stored ones
159
 *
160
 * requirements: an active session must be available
161
 * this check will prevent from multiple sending a form. history.back() also will never work
162
 */
163
	final public function checkFTAN( $mode = 'POST')
164
	{
165
		$retval = false;
166
		if(isset($_SESSION[$this->_ftan_name]))
167
		{
168
			if( $_SESSION[$this->_ftan_name] && (strlen($_SESSION[$this->_ftan_name]) == strlen(md5('dummy'))))
169
			{
170
				$ftan = $this->_calcFtan($_SESSION[$this->_ftan_name]);
171
				unset($_SESSION[$this->_ftan_name]);
172
				$mode = (strtoupper($mode) != 'POST' ? '_GET' : '_POST');
173
				if( isset($GLOBALS[$mode][$ftan[0]]))
174
				{
175
					$retval = ($GLOBALS[$mode][$ftan[0]] == $ftan[1]);
176
					unset($GLOBALS[$mode][$ftan[0]]);
177
				}
178
			}
179
		}
180
		return $retval;
181
	}
182

    
183
/*
184
 * save values in session and returns a ID-key
185
 * @access public
186
 * @param mixed $value: the value for witch a key shall be generated and memorized
187
 * @return string:      a MD5-Key to use instead of the real value
188
 *
189
 * @requirements: an active session must be available
190
 * @description: IDKEY can handle string/numeric/array - vars. Each key is a
191
 */
192
	final public function getIDKEY($value)
193
	{
194
		if( is_array($value) == true )
195
		{ // serialize value, if it's an array
196
			$value = serialize($value);
197
		}
198
		// crypt value with salt into md5-hash
199
		// and return a 16-digit block from random start position
200
		$key = substr( md5($this->_salt.(string)$value), rand(0,15), 16);
201
		do{ // loop while key/value isn't added
202
			if( !array_key_exists($key, $this->_IDKEYs) )
203
			{ // the key is unique, so store it in list
204
				$this->_IDKEYs[$key] = $value;
205
				break;
206
			}else {
207
				// if key already exist, increment the last five digits until the key is unique
208
				$key = substr($key, 0, -5).dechex(('0x'.substr($key, -5)) + 1);
209
			}
210
		}while(0);
211
		// store key/value-pairs into session
212
		$_SESSION[$this->_idkey_name] = $this->_IDKEYs;
213
		return $key;
214
	}
215

    
216
/*
217
 * search for key in session and returns the original value
218
 * @access public
219
 * @param string $fieldname: name of the POST/GET-Field containing the key or hex-key itself
220
 * @param mixed $default: returnvalue if key not exist (default 0)
221
 * @param string $request: requestmethode can be POST or GET or '' (default POST)
222
 * @return mixed: the original value (string, numeric, array) or DEFAULT if request fails
223
 *
224
 * @requirements: an active session must be available
225
 * @description: each IDKEY can be checked only once. Unused Keys stay in list until the
226
 *               session is destroyed.
227
 */
228
 	final public function checkIDKEY( $fieldname, $default = 0, $request = 'POST' )
229
	{
230
		$return_value = $default; // set returnvalue to default
231
		switch( strtoupper($request) )
232
		{
233
			case 'POST':
234
				$key = isset($_POST[$fieldname]) ? $_POST[$fieldname] : $fieldname;
235
				break;
236
			case 'GET':
237
				$key = isset($_GET[$fieldname]) ? $_GET[$fieldname] : $fieldname;
238
				break;
239
			default:
240
				$key = $fieldname;
241
		}
242

    
243
		if( preg_match('/[0-9a-f]{16}$/', $key) )
244
		{ // key must be a 16-digit hexvalue
245
			if( array_key_exists($key, $this->_IDKEYs))
246
			{ // check if key is stored in IDKEYs-list
247
				$return_value = $this->_IDKEYs[$key]; // get stored value
248
				unset($this->_IDKEYs[$key]);   // remove from list to prevent multiuse
249
				$_SESSION[$this->_idkey_name] = $this->_IDKEYs; // save modified list into session again
250
				if( preg_match('/.*(?<!\{).*(\d:\{.*;\}).*(?!\}).*/', $return_value) )
251
				{ // if value is a serialized array, then deserialize it
252
					$return_value = unserialize($return_value);
253
				}
254
			}
255
		}
256
		return $return_value;
257
	}
258

    
259
/* @access public
260
 * @return void
261
 *
262
 * @requirements: an active session must be available
263
 * @description: remove all entries from IDKEY-Array
264
 *
265
 */
266
 	final public function clearIDKEY()
267
	{
268
		 $this->_IDKEYs = array('0'=>'0');
269
	}
270
}
(4-4/20)