PageRenderTime 145ms CodeModel.GetById 80ms app.highlight 10ms RepoModel.GetById 50ms app.codeStats 0ms

/demo/yii/base/CSecurityManager.php

https://bitbucket.org/dzio/yii-bootstrap
PHP | 329 lines | 162 code | 23 blank | 144 comment | 15 complexity | 1456da85779320c6869ff8c4d5e1db42 MD5 | raw file
  1<?php
  2/**
  3 * This file contains classes implementing security manager feature.
  4 *
  5 * @author Qiang Xue <qiang.xue@gmail.com>
  6 * @link http://www.yiiframework.com/
  7 * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8 * @license http://www.yiiframework.com/license/
  9 */
 10
 11/**
 12 * CSecurityManager provides private keys, hashing and encryption functions.
 13 *
 14 * CSecurityManager is used by Yii components and applications for security-related purpose.
 15 * For example, it is used in cookie validation feature to prevent cookie data
 16 * from being tampered.
 17 *
 18 * CSecurityManager is mainly used to protect data from being tampered and viewed.
 19 * It can generate HMAC and encrypt the data. The private key used to generate HMAC
 20 * is set by {@link setValidationKey ValidationKey}. The key used to encrypt data is
 21 * specified by {@link setEncryptionKey EncryptionKey}. If the above keys are not
 22 * explicitly set, random keys will be generated and used.
 23 *
 24 * To protected data with HMAC, call {@link hashData()}; and to check if the data
 25 * is tampered, call {@link validateData()}, which will return the real data if
 26 * it is not tampered. The algorithm used to generated HMAC is specified by
 27 * {@link validation}.
 28 *
 29 * To encrypt and decrypt data, call {@link encrypt()} and {@link decrypt()}
 30 * respectively, which uses 3DES encryption algorithm.  Note, the PHP Mcrypt
 31 * extension must be installed and loaded.
 32 *
 33 * CSecurityManager is a core application component that can be accessed via
 34 * {@link CApplication::getSecurityManager()}.
 35 *
 36 * @property string $validationKey The private key used to generate HMAC.
 37 * If the key is not explicitly set, a random one is generated and returned.
 38 * @property string $encryptionKey The private key used to encrypt/decrypt data.
 39 * If the key is not explicitly set, a random one is generated and returned.
 40 * @property string $validation
 41 *
 42 * @author Qiang Xue <qiang.xue@gmail.com>
 43 * @version $Id: CSecurityManager.php 3555 2012-02-09 10:29:44Z mdomba $
 44 * @package system.base
 45 * @since 1.0
 46 */
 47class CSecurityManager extends CApplicationComponent
 48{
 49	const STATE_VALIDATION_KEY='Yii.CSecurityManager.validationkey';
 50	const STATE_ENCRYPTION_KEY='Yii.CSecurityManager.encryptionkey';
 51
 52	/**
 53	 * @var string the name of the hashing algorithm to be used by {@link computeHMAC}.
 54	 * See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
 55	 * hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
 56	 *
 57	 * Defaults to 'sha1', meaning using SHA1 hash algorithm.
 58	 * @since 1.1.3
 59	 */
 60	public $hashAlgorithm='sha1';
 61	/**
 62	 * @var mixed the name of the crypt algorithm to be used by {@link encrypt} and {@link decrypt}.
 63	 * This will be passed as the first parameter to {@link http://php.net/manual/en/function.mcrypt-module-open.php mcrypt_module_open}.
 64	 *
 65	 * This property can also be configured as an array. In this case, the array elements will be passed in order
 66	 * as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>.
 67	 *
 68	 * Defaults to 'des', meaning using DES crypt algorithm.
 69	 * @since 1.1.3
 70	 */
 71	public $cryptAlgorithm='des';
 72
 73	private $_validationKey;
 74	private $_encryptionKey;
 75	private $_mbstring;
 76
 77	public function init()
 78	{
 79		parent::init();
 80		$this->_mbstring=extension_loaded('mbstring');
 81	}
 82
 83	/**
 84	 * @return string a randomly generated private key
 85	 */
 86	protected function generateRandomKey()
 87	{
 88		return sprintf('%08x%08x%08x%08x',mt_rand(),mt_rand(),mt_rand(),mt_rand());
 89	}
 90
 91	/**
 92	 * @return string the private key used to generate HMAC.
 93	 * If the key is not explicitly set, a random one is generated and returned.
 94	 */
 95	public function getValidationKey()
 96	{
 97		if($this->_validationKey!==null)
 98			return $this->_validationKey;
 99		else
100		{
101			if(($key=Yii::app()->getGlobalState(self::STATE_VALIDATION_KEY))!==null)
102				$this->setValidationKey($key);
103			else
104			{
105				$key=$this->generateRandomKey();
106				$this->setValidationKey($key);
107				Yii::app()->setGlobalState(self::STATE_VALIDATION_KEY,$key);
108			}
109			return $this->_validationKey;
110		}
111	}
112
113	/**
114	 * @param string $value the key used to generate HMAC
115	 * @throws CException if the key is empty
116	 */
117	public function setValidationKey($value)
118	{
119		if(!empty($value))
120			$this->_validationKey=$value;
121		else
122			throw new CException(Yii::t('yii','CSecurityManager.validationKey cannot be empty.'));
123	}
124
125	/**
126	 * @return string the private key used to encrypt/decrypt data.
127	 * If the key is not explicitly set, a random one is generated and returned.
128	 */
129	public function getEncryptionKey()
130	{
131		if($this->_encryptionKey!==null)
132			return $this->_encryptionKey;
133		else
134		{
135			if(($key=Yii::app()->getGlobalState(self::STATE_ENCRYPTION_KEY))!==null)
136				$this->setEncryptionKey($key);
137			else
138			{
139				$key=$this->generateRandomKey();
140				$this->setEncryptionKey($key);
141				Yii::app()->setGlobalState(self::STATE_ENCRYPTION_KEY,$key);
142			}
143			return $this->_encryptionKey;
144		}
145	}
146
147	/**
148	 * @param string $value the key used to encrypt/decrypt data.
149	 * @throws CException if the key is empty
150	 */
151	public function setEncryptionKey($value)
152	{
153		if(!empty($value))
154			$this->_encryptionKey=$value;
155		else
156			throw new CException(Yii::t('yii','CSecurityManager.encryptionKey cannot be empty.'));
157	}
158
159	/**
160	 * This method has been deprecated since version 1.1.3.
161	 * Please use {@link hashAlgorithm} instead.
162	 * @return string
163	 */
164	public function getValidation()
165	{
166		return $this->hashAlgorithm;
167	}
168
169	/**
170	 * This method has been deprecated since version 1.1.3.
171	 * Please use {@link hashAlgorithm} instead.
172	 * @param string $value -
173	 */
174	public function setValidation($value)
175	{
176		$this->hashAlgorithm=$value;
177	}
178
179	/**
180	 * Encrypts data.
181	 * @param string $data data to be encrypted.
182	 * @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
183	 * @return string the encrypted data
184	 * @throws CException if PHP Mcrypt extension is not loaded
185	 */
186	public function encrypt($data,$key=null)
187	{
188		$module=$this->openCryptModule();
189		$key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
190		srand();
191		$iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
192		mcrypt_generic_init($module,$key,$iv);
193		$encrypted=$iv.mcrypt_generic($module,$data);
194		mcrypt_generic_deinit($module);
195		mcrypt_module_close($module);
196		return $encrypted;
197	}
198
199	/**
200	 * Decrypts data
201	 * @param string $data data to be decrypted.
202	 * @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
203	 * @return string the decrypted data
204	 * @throws CException if PHP Mcrypt extension is not loaded
205	 */
206	public function decrypt($data,$key=null)
207	{
208		$module=$this->openCryptModule();
209		$key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
210		$ivSize=mcrypt_enc_get_iv_size($module);
211		$iv=$this->substr($data,0,$ivSize);
212		mcrypt_generic_init($module,$key,$iv);
213		$decrypted=mdecrypt_generic($module,$this->substr($data,$ivSize,$this->strlen($data)));
214		mcrypt_generic_deinit($module);
215		mcrypt_module_close($module);
216		return rtrim($decrypted,"\0");
217	}
218
219	/**
220	 * Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
221	 * @return resource the mycrypt module handle.
222	 * @since 1.1.3
223	 */
224	protected function openCryptModule()
225	{
226		if(extension_loaded('mcrypt'))
227		{
228			if(is_array($this->cryptAlgorithm))
229				$module=@call_user_func_array('mcrypt_module_open',$this->cryptAlgorithm);
230			else
231				$module=@mcrypt_module_open($this->cryptAlgorithm,'', MCRYPT_MODE_CBC,'');
232
233			if($module===false)
234				throw new CException(Yii::t('yii','Failed to initialize the mcrypt module.'));
235
236			return $module;
237		}
238		else
239			throw new CException(Yii::t('yii','CSecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
240	}
241
242	/**
243	 * Prefixes data with an HMAC.
244	 * @param string $data data to be hashed.
245	 * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
246	 * @return string data prefixed with HMAC
247	 */
248	public function hashData($data,$key=null)
249	{
250		return $this->computeHMAC($data,$key).$data;
251	}
252
253	/**
254	 * Validates if data is tampered.
255	 * @param string $data data to be validated. The data must be previously
256	 * generated using {@link hashData()}.
257	 * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
258	 * @return string the real data with HMAC stripped off. False if the data
259	 * is tampered.
260	 */
261	public function validateData($data,$key=null)
262	{
263		$len=$this->strlen($this->computeHMAC('test'));
264		if($this->strlen($data)>=$len)
265		{
266			$hmac=$this->substr($data,0,$len);
267			$data2=$this->substr($data,$len,$this->strlen($data));
268			return $hmac===$this->computeHMAC($data2,$key)?$data2:false;
269		}
270		else
271			return false;
272	}
273
274	/**
275	 * Computes the HMAC for the data with {@link getValidationKey ValidationKey}.
276	 * @param string $data data to be generated HMAC
277	 * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
278	 * @return string the HMAC for the data
279	 */
280	protected function computeHMAC($data,$key=null)
281	{
282		if($key===null)
283			$key=$this->getValidationKey();
284
285		if(function_exists('hash_hmac'))
286			return hash_hmac($this->hashAlgorithm, $data, $key);
287
288		if(!strcasecmp($this->hashAlgorithm,'sha1'))
289		{
290			$pack='H40';
291			$func='sha1';
292		}
293		else
294		{
295			$pack='H32';
296			$func='md5';
297		}
298		if($this->strlen($key) > 64)
299			$key=pack($pack, $func($key));
300		if($this->strlen($key) < 64)
301			$key=str_pad($key, 64, chr(0));
302		$key=$this->substr($key,0,64);
303		return $func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack, $func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
304	}
305
306	/**
307	 * Returns the length of the given string.
308	 * If available uses the multibyte string function mb_strlen.
309	 * @param string $string the string being measured for length
310	 * @return int the length of the string
311	 */
312	private function strlen($string)
313	{
314		return $this->_mbstring ? mb_strlen($string,'8bit') : strlen($string);
315	}
316
317	/**
318	 * Returns the portion of string specified by the start and length parameters.
319	 * If available uses the multibyte string function mb_substr
320	 * @param string $string the input string. Must be one character or longer.
321	 * @param int $start the starting position
322	 * @param int $length the desired portion length
323	 * @return string the extracted part of string, or FALSE on failure or an empty string.
324	 */
325	private function substr($string,$start,$length)
326	{
327		return $this->_mbstring ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
328	}
329}