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 1499 2011-08-12 11:21:25Z DarkViper $
15
 * @filesource		$HeadURL: svn://isteam.dynxs.de/wb-archiv/branches/2.8.x/wb/framework/SecureForm.php $
16
 * @lastmodified    $Date: 2011-08-12 13:21:25 +0200 (Fri, 12 Aug 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 .= PHP_VERSION;
94
	// client depending values
95
		$fingerprint .= ( isset($_SERVER['HTTP_USER_AGENT']) ) ? $_SERVER['HTTP_USER_AGENT'] : '17';
96
		$usedOctets = ( defined('FINGERPRINT_WITH_IP_OCTETS') ) ? (intval(FINGERPRINT_WITH_IP_OCTETS) % 5) : 2;
97
		$clientIp = ( isset($_SERVER['REMOTE_ADDR'])  ? $_SERVER['REMOTE_ADDR'] : '' );
98
		if(($clientIp != '') && ($usedOctets > 0)){
99
			$ip = explode('.', $clientIp);
100
			while(sizeof($ip) > $usedOctets) { array_pop($ip); }
101
			$clientIp = implode('.', $ip);
102
		}else {
103
			$clientIp = 19;
104
		}
105
		$fingerprint .= $clientIp;
106
		return md5($fingerprint);
107
	}
108

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

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

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

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

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

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