diff --git a/composer.json b/composer.json index 418493125..437548121 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ "require": { "doctrine/dbal": "2.5.4", "mcnetic/zipstreamer": "^1.0", - "phpseclib/phpseclib": "2.0.0", + "phpseclib/phpseclib": "2.0.3", "rackspace/php-opencloud": "v1.9.2", "jeremeamia/superclosure": "2.1.0", "bantu/ini-get-wrapper": "v1.0.1", diff --git a/composer.lock b/composer.lock index 5fe5c5b59..f109db279 100644 --- a/composer.lock +++ b/composer.lock @@ -4,8 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "hash": "8db5cba22824fde712d2c8056e164fe0", - "content-hash": "589b54b3b21a15a12fd90dffa8b9e86c", + "hash": "7e581aa687d41077f841922ce16303ee", + "content-hash": "67dab6cbfe9cc949621bf6f6a2d1fe54", "packages": [ { "name": "bantu/ini-get-wrapper", @@ -1722,16 +1722,16 @@ }, { "name": "phpseclib/phpseclib", - "version": "2.0.0", + "version": "2.0.3", "source": { "type": "git", "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "a74aa9efbe61430fcb60157c8e025a48ec8ff604" + "reference": "41f85e9c2582b3f6d1b7d20395fb40c687ad5370" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/a74aa9efbe61430fcb60157c8e025a48ec8ff604", - "reference": "a74aa9efbe61430fcb60157c8e025a48ec8ff604", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/41f85e9c2582b3f6d1b7d20395fb40c687ad5370", + "reference": "41f85e9c2582b3f6d1b7d20395fb40c687ad5370", "shasum": "" }, "require": { @@ -1747,19 +1747,18 @@ "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", - "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations.", - "pear-pear/PHP_Compat": "Install PHP_Compat to get phpseclib working on PHP < 5.0.0." + "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." }, "type": "library", "autoload": { + "files": [ + "phpseclib/bootstrap.php" + ], "psr-4": { "phpseclib\\": "phpseclib/" } }, "notification-url": "https://packagist.org/downloads/", - "include-path": [ - "phpseclib/" - ], "license": [ "MIT" ], @@ -1783,6 +1782,11 @@ "name": "Hans-Jürgen Petrich", "email": "petrich@tronic-media.com", "role": "Developer" + }, + { + "name": "Graham Campbell", + "email": "graham@alt-three.com", + "role": "Developer" } ], "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", @@ -1806,7 +1810,7 @@ "x.509", "x509" ], - "time": "2015-08-04 04:48:03" + "time": "2016-08-18 18:49:14" }, { "name": "pimple/pimple", diff --git a/composer/autoload_files.php b/composer/autoload_files.php index b23dd5b3c..ad880378e 100644 --- a/composer/autoload_files.php +++ b/composer/autoload_files.php @@ -17,4 +17,5 @@ '2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php', 'e40631d46120a9c38ea139981f8dab26' => $vendorDir . '/ircmaxell/password-compat/lib/password.php', '023d27dca8066ef29e6739335ea73bad' => $vendorDir . '/symfony/polyfill-php70/bootstrap.php', + 'decc78cc4436b1292c6c0d151b19445c' => $vendorDir . '/phpseclib/phpseclib/phpseclib/bootstrap.php', ); diff --git a/composer/autoload_static.php b/composer/autoload_static.php index 39fbee9c9..10ae984bd 100644 --- a/composer/autoload_static.php +++ b/composer/autoload_static.php @@ -18,6 +18,7 @@ class ComposerStaticInit2f23f73bc0cc116b4b1eee1521aa8652 '2c102faa651ef8ea5874edb585946bce' => __DIR__ . '/..' . '/swiftmailer/swiftmailer/lib/swift_required.php', 'e40631d46120a9c38ea139981f8dab26' => __DIR__ . '/..' . '/ircmaxell/password-compat/lib/password.php', '023d27dca8066ef29e6739335ea73bad' => __DIR__ . '/..' . '/symfony/polyfill-php70/bootstrap.php', + 'decc78cc4436b1292c6c0d151b19445c' => __DIR__ . '/..' . '/phpseclib/phpseclib/phpseclib/bootstrap.php', ); public static $prefixLengthsPsr4 = array ( diff --git a/composer/include_paths.php b/composer/include_paths.php index 86a177519..9d5276c92 100644 --- a/composer/include_paths.php +++ b/composer/include_paths.php @@ -10,5 +10,4 @@ $vendorDir . '/pear/pear_exception', $vendorDir . '/pear/pear-core-minimal/src', $vendorDir . '/pear/archive_tar', - $vendorDir . '/phpseclib/phpseclib/phpseclib', ); diff --git a/composer/installed.json b/composer/installed.json index 2d973e844..9cdeb4c6b 100644 --- a/composer/installed.json +++ b/composer/installed.json @@ -931,96 +931,6 @@ ], "description": "A lightweight implementation of CommonJS Promises/A for PHP" }, - { - "name": "phpseclib/phpseclib", - "version": "2.0.0", - "version_normalized": "2.0.0.0", - "source": { - "type": "git", - "url": "https://github.com/phpseclib/phpseclib.git", - "reference": "a74aa9efbe61430fcb60157c8e025a48ec8ff604" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/a74aa9efbe61430fcb60157c8e025a48ec8ff604", - "reference": "a74aa9efbe61430fcb60157c8e025a48ec8ff604", - "shasum": "" - }, - "require": { - "php": ">=5.3.3" - }, - "require-dev": { - "phing/phing": "~2.7", - "phpunit/phpunit": "~4.0", - "sami/sami": "~2.0", - "squizlabs/php_codesniffer": "~2.0" - }, - "suggest": { - "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", - "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", - "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", - "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations.", - "pear-pear/PHP_Compat": "Install PHP_Compat to get phpseclib working on PHP < 5.0.0." - }, - "time": "2015-08-04 04:48:03", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-4": { - "phpseclib\\": "phpseclib/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "include-path": [ - "phpseclib/" - ], - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Jim Wigginton", - "email": "terrafrost@php.net", - "role": "Lead Developer" - }, - { - "name": "Patrick Monnerat", - "email": "pm@datasphere.ch", - "role": "Developer" - }, - { - "name": "Andreas Fischer", - "email": "bantu@phpbb.com", - "role": "Developer" - }, - { - "name": "Hans-Jürgen Petrich", - "email": "petrich@tronic-media.com", - "role": "Developer" - } - ], - "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", - "homepage": "http://phpseclib.sourceforge.net", - "keywords": [ - "BigInteger", - "aes", - "asn.1", - "asn1", - "blowfish", - "crypto", - "cryptography", - "encryption", - "rsa", - "security", - "sftp", - "signature", - "signing", - "ssh", - "twofish", - "x.509", - "x509" - ] - }, { "name": "doctrine/lexer", "version": "v1.0.1", @@ -2892,5 +2802,99 @@ "uri", "url" ] + }, + { + "name": "phpseclib/phpseclib", + "version": "2.0.3", + "version_normalized": "2.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/phpseclib/phpseclib.git", + "reference": "41f85e9c2582b3f6d1b7d20395fb40c687ad5370" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/41f85e9c2582b3f6d1b7d20395fb40c687ad5370", + "reference": "41f85e9c2582b3f6d1b7d20395fb40c687ad5370", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phing/phing": "~2.7", + "phpunit/phpunit": "~4.0", + "sami/sami": "~2.0", + "squizlabs/php_codesniffer": "~2.0" + }, + "suggest": { + "ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.", + "ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.", + "ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.", + "ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations." + }, + "time": "2016-08-18 18:49:14", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "phpseclib/bootstrap.php" + ], + "psr-4": { + "phpseclib\\": "phpseclib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jim Wigginton", + "email": "terrafrost@php.net", + "role": "Lead Developer" + }, + { + "name": "Patrick Monnerat", + "email": "pm@datasphere.ch", + "role": "Developer" + }, + { + "name": "Andreas Fischer", + "email": "bantu@phpbb.com", + "role": "Developer" + }, + { + "name": "Hans-Jürgen Petrich", + "email": "petrich@tronic-media.com", + "role": "Developer" + }, + { + "name": "Graham Campbell", + "email": "graham@alt-three.com", + "role": "Developer" + } + ], + "description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.", + "homepage": "http://phpseclib.sourceforge.net", + "keywords": [ + "BigInteger", + "aes", + "asn.1", + "asn1", + "blowfish", + "crypto", + "cryptography", + "encryption", + "rsa", + "security", + "sftp", + "signature", + "signing", + "ssh", + "twofish", + "x.509", + "x509" + ] } ] diff --git a/phpseclib/phpseclib/AUTHORS b/phpseclib/phpseclib/AUTHORS index e175f9f22..a08b3099c 100644 --- a/phpseclib/phpseclib/AUTHORS +++ b/phpseclib/phpseclib/AUTHORS @@ -3,3 +3,4 @@ phpseclib Lead Developer: TerraFrost (Jim Wigginton) phpseclib Developers: monnerat (Patrick Monnerat) bantu (Andreas Fischer) petrich (Hans-Jürgen Petrich) + GrahamCampbell (Graham Campbell) diff --git a/phpseclib/phpseclib/LICENSE b/phpseclib/phpseclib/LICENSE index 75f6b2045..a8ec8ebd4 100644 --- a/phpseclib/phpseclib/LICENSE +++ b/phpseclib/phpseclib/LICENSE @@ -1,4 +1,4 @@ -Copyright 2007-2013 TerraFrost and other contributors +Copyright 2007-2016 TerraFrost and other contributors http://phpseclib.sourceforge.net/ Permission is hereby granted, free of charge, to any person obtaining diff --git a/phpseclib/phpseclib/phpseclib/Crypt/AES.php b/phpseclib/phpseclib/phpseclib/Crypt/AES.php index 2696e0abb..7d8cb8b03 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/AES.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/AES.php @@ -11,13 +11,13 @@ * just a wrapper to Rijndael.php you may consider using Rijndael.php instead of * to save one include_once(). * - * If {@link \phpseclib\Crypt\AES::setKeyLength() setKeyLength()} isn't called, it'll be calculated from - * {@link \phpseclib\Crypt\AES::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits - * it'll be null-padded to 192-bits and 192 bits will be the key length until {@link \phpseclib\Crypt\AES::setKey() setKey()} + * If {@link self::setKeyLength() setKeyLength()} isn't called, it'll be calculated from + * {@link self::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits + * it'll be null-padded to 192-bits and 192 bits will be the key length until {@link self::setKey() setKey()} * is called, again, at which point, it'll be recalculated. * * Since \phpseclib\Crypt\AES extends \phpseclib\Crypt\Rijndael, some functions are available to be called that, in the context of AES, don't - * make a whole lot of sense. {@link \phpseclib\Crypt\AES::setBlockLength() setBlockLength()}, for instance. Calling that function, + * make a whole lot of sense. {@link self::setBlockLength() setBlockLength()}, for instance. Calling that function, * however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one). * * Here's a short example of how to use this library: @@ -49,8 +49,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Rijndael; - /** * Pure-PHP implementation of AES. * @@ -67,7 +65,7 @@ class AES extends Rijndael * * @see \phpseclib\Crypt\Rijndael::setBlockLength() * @access public - * @param Integer $length + * @param int $length */ function setBlockLength($length) { @@ -82,7 +80,7 @@ function setBlockLength($length) * * @see \phpseclib\Crypt\Rijndael:setKeyLength() * @access public - * @param Integer $length + * @param int $length */ function setKeyLength($length) { @@ -104,7 +102,7 @@ function setKeyLength($length) * @see \phpseclib\Crypt\Rijndael:setKey() * @see setKeyLength() * @access public - * @param String $key + * @param string $key */ function setKey($key) { @@ -114,13 +112,13 @@ function setKey($key) $length = strlen($key); switch (true) { case $length <= 16: - $this->key_size = 16; + $this->key_length = 16; break; case $length <= 24: - $this->key_size = 24; + $this->key_length = 24; break; default: - $this->key_size = 32; + $this->key_length = 32; } $this->_setEngine(); } diff --git a/phpseclib/phpseclib/phpseclib/Crypt/Base.php b/phpseclib/phpseclib/phpseclib/Crypt/Base.php index 715ab2a5d..e616e0cb7 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/Base.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/Base.php @@ -36,8 +36,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Hash; - /** * Base Class for all \phpseclib\Crypt\* cipher classes * @@ -94,7 +92,7 @@ abstract class Base * Whirlpool available flag * * @see \phpseclib\Crypt\Base::_hashInlineCryptFunction() - * @var Boolean + * @var bool * @access private */ static $WHIRLPOOL_AVAILABLE; @@ -120,8 +118,8 @@ abstract class Base /** * The Encryption Mode * - * @see \phpseclib\Crypt\Base::__construct() - * @var Integer + * @see self::__construct() + * @var int * @access private */ var $mode; @@ -129,7 +127,7 @@ abstract class Base /** * The Block Length of the block cipher * - * @var Integer + * @var int * @access private */ var $block_size = 16; @@ -137,8 +135,8 @@ abstract class Base /** * The Key * - * @see \phpseclib\Crypt\Base::setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; @@ -146,8 +144,8 @@ abstract class Base /** * The Initialization Vector * - * @see \phpseclib\Crypt\Base::setIV() - * @var String + * @see self::setIV() + * @var string * @access private */ var $iv; @@ -155,9 +153,9 @@ abstract class Base /** * A "sliding" Initialization Vector * - * @see \phpseclib\Crypt\Base::enableContinuousBuffer() - * @see \phpseclib\Crypt\Base::_clearBuffers() - * @var String + * @see self::enableContinuousBuffer() + * @see self::_clearBuffers() + * @var string * @access private */ var $encryptIV; @@ -165,9 +163,9 @@ abstract class Base /** * A "sliding" Initialization Vector * - * @see \phpseclib\Crypt\Base::enableContinuousBuffer() - * @see \phpseclib\Crypt\Base::_clearBuffers() - * @var String + * @see self::enableContinuousBuffer() + * @see self::_clearBuffers() + * @var string * @access private */ var $decryptIV; @@ -175,8 +173,8 @@ abstract class Base /** * Continuous Buffer status * - * @see \phpseclib\Crypt\Base::enableContinuousBuffer() - * @var Boolean + * @see self::enableContinuousBuffer() + * @var bool * @access private */ var $continuousBuffer = false; @@ -184,9 +182,9 @@ abstract class Base /** * Encryption buffer for CTR, OFB and CFB modes * - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::_clearBuffers() - * @var Array + * @see self::encrypt() + * @see self::_clearBuffers() + * @var array * @access private */ var $enbuffer; @@ -194,9 +192,9 @@ abstract class Base /** * Decryption buffer for CTR, OFB and CFB modes * - * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\Base::_clearBuffers() - * @var Array + * @see self::decrypt() + * @see self::_clearBuffers() + * @var array * @access private */ var $debuffer; @@ -207,8 +205,8 @@ abstract class Base * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. * - * @see \phpseclib\Crypt\Base::encrypt() - * @var Resource + * @see self::encrypt() + * @var resource * @access private */ var $enmcrypt; @@ -219,8 +217,8 @@ abstract class Base * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. * - * @see \phpseclib\Crypt\Base::decrypt() - * @var Resource + * @see self::decrypt() + * @var resource * @access private */ var $demcrypt; @@ -230,7 +228,7 @@ abstract class Base * * @see \phpseclib\Crypt\Twofish::setKey() * @see \phpseclib\Crypt\Twofish::setIV() - * @var Boolean + * @var bool * @access private */ var $enchanged = true; @@ -240,7 +238,7 @@ abstract class Base * * @see \phpseclib\Crypt\Twofish::setKey() * @see \phpseclib\Crypt\Twofish::setIV() - * @var Boolean + * @var bool * @access private */ var $dechanged = true; @@ -256,10 +254,10 @@ abstract class Base * use a separate ECB-mode mcrypt resource. * * @link http://phpseclib.sourceforge.net/cfb-demo.phps - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\Base::_setupMcrypt() - * @var Resource + * @see self::encrypt() + * @see self::decrypt() + * @see self::_setupMcrypt() + * @var resource * @access private */ var $ecb; @@ -280,8 +278,8 @@ abstract class Base * which, typically, depends on the complexity * on its internaly Key-expanding algorithm. * - * @see \phpseclib\Crypt\Base::encrypt() - * @var Integer + * @see self::encrypt() + * @var int * @access private */ var $cfb_init_len = 600; @@ -289,10 +287,10 @@ abstract class Base /** * Does internal cipher state need to be (re)initialized? * - * @see setKey() - * @see setIV() - * @see disableContinuousBuffer() - * @var Boolean + * @see self::setKey() + * @see self::setIV() + * @see self::disableContinuousBuffer() + * @var bool * @access private */ var $changed = true; @@ -300,8 +298,8 @@ abstract class Base /** * Padding status * - * @see \phpseclib\Crypt\Base::enablePadding() - * @var Boolean + * @see self::enablePadding() + * @var bool * @access private */ var $padding = true; @@ -309,8 +307,8 @@ abstract class Base /** * Is the mode one that is paddable? * - * @see \phpseclib\Crypt\Base::__construct() - * @var Boolean + * @see self::__construct() + * @var bool * @access private */ var $paddable = false; @@ -324,10 +322,10 @@ abstract class Base * - self::ENGINE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required) * - self::ENGINE_INTERNAL (slower, pure php-engine, no php-extension required) * - * @see \phpseclib\Crypt\Base::_setEngine() - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::decrypt() - * @var Integer + * @see self::_setEngine() + * @see self::encrypt() + * @see self::decrypt() + * @var int * @access private */ var $engine; @@ -335,9 +333,9 @@ abstract class Base /** * Holds the preferred crypt engine * - * @see \phpseclib\Crypt\Base::_setEngine() - * @see \phpseclib\Crypt\Base::setPreferredEngine() - * @var Integer + * @see self::_setEngine() + * @see self::setPreferredEngine() + * @var int * @access private */ var $preferredEngine; @@ -349,8 +347,8 @@ abstract class Base * * @link http://www.php.net/mcrypt_module_open * @link http://www.php.net/mcrypt_list_algorithms - * @see \phpseclib\Crypt\Base::_setupMcrypt() - * @var String + * @see self::_setupMcrypt() + * @var string * @access private */ var $cipher_name_mcrypt; @@ -358,10 +356,10 @@ abstract class Base /** * The openssl specific name of the cipher * - * Only used if $engine == CRYPT_ENGINE_OPENSSL + * Only used if $engine == self::ENGINE_OPENSSL * * @link http://www.php.net/openssl-get-cipher-methods - * @var String + * @var string * @access private */ var $cipher_name_openssl; @@ -373,25 +371,16 @@ abstract class Base * it can still be emulated with ECB mode. * * @link http://www.php.net/openssl-get-cipher-methods - * @var String + * @var string * @access private */ var $cipher_name_openssl_ecb; - /** - * The default password key_size used by setPassword() - * - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer - * @access private - */ - var $password_key_size = 32; - /** * The default salt used by setPassword() * - * @see \phpseclib\Crypt\Base::setPassword() - * @var String + * @see self::setPassword() + * @var string * @access private */ var $password_default_salt = 'phpseclib/salt'; @@ -402,10 +391,10 @@ abstract class Base * Used by encrypt() / decrypt() * only if $engine == self::ENGINE_INTERNAL * - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\Base::_setupInlineCrypt() - * @see \phpseclib\Crypt\Base::$use_inline_crypt + * @see self::encrypt() + * @see self::decrypt() + * @see self::_setupInlineCrypt() + * @see self::$use_inline_crypt * @var Callback * @access private */ @@ -414,9 +403,9 @@ abstract class Base /** * Holds whether performance-optimized $inline_crypt() can/should be used. * - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\Base::inline_crypt + * @see self::encrypt() + * @see self::decrypt() + * @see self::inline_crypt * @var mixed * @access private */ @@ -425,8 +414,8 @@ abstract class Base /** * If OpenSSL can be used in ECB but not in CTR we can emulate CTR * - * @see \phpseclib\Crypt\Base::_openssl_ctr_process() - * @var Boolean + * @see self::_openssl_ctr_process() + * @var bool * @access private */ var $openssl_emulate_ctr = false; @@ -434,12 +423,30 @@ abstract class Base /** * Determines what options are passed to openssl_encrypt/decrypt * - * @see \phpseclib\Crypt\Base::isValidEngine() + * @see self::isValidEngine() * @var mixed * @access private */ var $openssl_options; + /** + * Has the key length explicitly been set or should it be derived from the key, itself? + * + * @see self::setKeyLength() + * @var bool + * @access private + */ + var $explicit_key_length = false; + + /** + * Don't truncate / null pad key + * + * @see self::_clearBuffers() + * @var bool + * @access private + */ + var $skip_key_adjustment = false; + /** * Default Constructor. * @@ -457,11 +464,9 @@ abstract class Base * * - self::MODE_OFB * - * (or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...) - * * If not explicitly set, self::MODE_CBC will be used. * - * @param optional Integer $mode + * @param int $mode * @access public */ function __construct($mode = self::MODE_CBC) @@ -499,7 +504,7 @@ function __construct($mode = self::MODE_CBC) * to be all zero's. * * @access public - * @param String $iv + * @param string $iv * @internal Can be overwritten by a sub class, but does not have to be */ function setIV($iv) @@ -512,6 +517,43 @@ function setIV($iv) $this->changed = true; } + /** + * Sets the key length. + * + * Keys with explicitly set lengths need to be treated accordingly + * + * @access public + * @param int $length + */ + function setKeyLength($length) + { + $this->explicit_key_length = true; + $this->changed = true; + $this->_setEngine(); + } + + /** + * Returns the current key length in bits + * + * @access public + * @return int + */ + function getKeyLength() + { + return $this->key_length << 3; + } + + /** + * Returns the current block length in bits + * + * @access public + * @return int + */ + function getBlockLength() + { + return $this->block_size << 3; + } + /** * Sets the key. * @@ -523,11 +565,16 @@ function setIV($iv) * If the key is not explicitly set, it'll be assumed to be all null bytes. * * @access public - * @param String $key + * @param string $key * @internal Could, but not must, extend by the child Crypt_* class */ function setKey($key) { + if (!$this->explicit_key_length) { + $this->setKeyLength(strlen($key) << 3); + $this->explicit_key_length = false; + } + $this->key = $key; $this->changed = true; $this->_setEngine(); @@ -543,9 +590,9 @@ function setKey($key) * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php * * @see Crypt/Hash.php - * @param String $password - * @param optional String $method - * @return Boolean + * @param string $password + * @param string $method + * @return bool * @access public * @internal Could, but not must, extend by the child Crypt_* class */ @@ -571,7 +618,7 @@ function setPassword($password, $method = 'pbkdf2') if (isset($func_args[5])) { $dkLen = $func_args[5]; } else { - $dkLen = $method == 'pbkdf1' ? 2 * $this->password_key_size : $this->password_key_size; + $dkLen = $method == 'pbkdf1' ? 2 * $this->key_length : $this->key_length; } switch (true) { @@ -634,10 +681,10 @@ function setPassword($password, $method = 'pbkdf2') * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that * length. * - * @see \phpseclib\Crypt\Base::decrypt() + * @see self::decrypt() * @access public - * @param String $plaintext - * @return String $ciphertext + * @param string $plaintext + * @return string $ciphertext * @internal Could, but not must, extend by the child Crypt_* class */ function encrypt($plaintext) @@ -659,10 +706,13 @@ function encrypt($plaintext) return !defined('OPENSSL_RAW_DATA') ? substr($result, 0, -$this->block_size) : $result; case self::MODE_CBC: $result = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $this->encryptIV); + if (!defined('OPENSSL_RAW_DATA')) { + $result = substr($result, 0, -$this->block_size); + } if ($this->continuousBuffer) { $this->encryptIV = substr($result, -$this->block_size); } - return !defined('OPENSSL_RAW_DATA') ? substr($result, 0, -$this->block_size) : $result; + return $result; case self::MODE_CTR: return $this->_openssl_ctr_process($plaintext, $this->encryptIV, $this->enbuffer); case self::MODE_CFB: @@ -914,7 +964,7 @@ function encrypt($plaintext) if ($this->continuousBuffer) { $this->encryptIV = $xor; if ($start = strlen($plaintext) % $block_size) { - $buffer['xor'] = substr($key, $start) . $buffer['xor']; + $buffer['xor'] = substr($key, $start) . $buffer['xor']; } } break; @@ -932,10 +982,10 @@ function encrypt($plaintext) * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until * it is. * - * @see \phpseclib\Crypt\Base::encrypt() + * @see self::encrypt() * @access public - * @param String $ciphertext - * @return String $plaintext + * @param string $ciphertext + * @return string $plaintext * @internal Could, but not must, extend by the child Crypt_* class */ function decrypt($ciphertext) @@ -957,7 +1007,7 @@ function decrypt($ciphertext) break; case self::MODE_ECB: if (!defined('OPENSSL_RAW_DATA')) { - $ciphetext.= openssl_encrypt('', $this->cipher_name_openssl_ecb, $this->key, true); + $ciphertext.= openssl_encrypt('', $this->cipher_name_openssl_ecb, $this->key, true); } $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options); break; @@ -965,10 +1015,13 @@ function decrypt($ciphertext) if (!defined('OPENSSL_RAW_DATA')) { $padding = str_repeat(chr($this->block_size), $this->block_size) ^ substr($ciphertext, -$this->block_size); $ciphertext.= substr(openssl_encrypt($padding, $this->cipher_name_openssl_ecb, $this->key, true), 0, $this->block_size); + $offset = 2 * $this->block_size; + } else { + $offset = $this->block_size; } $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $this->decryptIV); if ($this->continuousBuffer) { - $this->decryptIV = substr($ciphertext, -$this->block_size); + $this->decryptIV = substr($ciphertext, -$offset, $this->block_size); } break; case self::MODE_CTR: @@ -1204,7 +1257,7 @@ function decrypt($ciphertext) if ($this->continuousBuffer) { $this->decryptIV = $xor; if ($start = strlen($ciphertext) % $block_size) { - $buffer['xor'] = substr($key, $start) . $buffer['xor']; + $buffer['xor'] = substr($key, $start) . $buffer['xor']; } } break; @@ -1219,16 +1272,16 @@ function decrypt($ciphertext) * OpenSSL CTR Processor * * PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream - * for CTR is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt() - * and Crypt_Base::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this - * function will emulate CTR with ECB when necesary. - * - * @see Crypt_Base::encrypt() - * @see Crypt_Base::decrypt() - * @param String $plaintext - * @param String $encryptIV - * @param Array $buffer - * @return String + * for CTR is the same for both encrypting and decrypting this function is re-used by both Base::encrypt() + * and Base::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this + * function will emulate CTR with ECB when necessary. + * + * @see self::encrypt() + * @see self::decrypt() + * @param string $plaintext + * @param string $encryptIV + * @param array $buffer + * @return string * @access private */ function _openssl_ctr_process($plaintext, &$encryptIV, &$buffer) @@ -1314,15 +1367,15 @@ function _openssl_ctr_process($plaintext, &$encryptIV, &$buffer) * OpenSSL OFB Processor * * PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream - * for OFB is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt() - * and Crypt_Base::decrypt(). - * - * @see Crypt_Base::encrypt() - * @see Crypt_Base::decrypt() - * @param String $plaintext - * @param String $encryptIV - * @param Array $buffer - * @return String + * for OFB is the same for both encrypting and decrypting this function is re-used by both Base::encrypt() + * and Base::decrypt(). + * + * @see self::encrypt() + * @see self::decrypt() + * @param string $plaintext + * @param string $encryptIV + * @param array $buffer + * @return string * @access private */ function _openssl_ofb_process($plaintext, &$encryptIV, &$buffer) @@ -1368,7 +1421,7 @@ function _openssl_ofb_process($plaintext, &$encryptIV, &$buffer) * * May need to be overwritten by classes extending this one in some cases * - * @return Integer + * @return int * @access private */ function _openssl_translate_mode() @@ -1399,7 +1452,7 @@ function _openssl_translate_mode() * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is * transmitted separately) * - * @see \phpseclib\Crypt\Base::disablePadding() + * @see self::disablePadding() * @access public */ function enablePadding() @@ -1410,7 +1463,7 @@ function enablePadding() /** * Do not pad packets. * - * @see \phpseclib\Crypt\Base::enablePadding() + * @see self::enablePadding() * @access public */ function disablePadding() @@ -1452,7 +1505,7 @@ function disablePadding() * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), * however, they are also less intuitive and more likely to cause you problems. * - * @see \phpseclib\Crypt\Base::disableContinuousBuffer() + * @see self::disableContinuousBuffer() * @access public * @internal Could, but not must, extend by the child Crypt_* class */ @@ -1472,7 +1525,7 @@ function enableContinuousBuffer() * * The default behavior. * - * @see \phpseclib\Crypt\Base::enableContinuousBuffer() + * @see self::enableContinuousBuffer() * @access public * @internal Could, but not must, extend by the child Crypt_* class */ @@ -1494,10 +1547,10 @@ function disableContinuousBuffer() /** * Test for engine validity * - * @see \phpseclib\Crypt\Base::Crypt_Base() - * @param Integer $engine + * @see self::__construct() + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { @@ -1561,8 +1614,8 @@ function isValidEngine($engine) * * If the preferred crypt engine is not available the fastest available one will be used * - * @see \phpseclib\Crypt\Base::Crypt_Base() - * @param Integer $engine + * @see self::__construct() + * @param int $engine * @access public */ function setPreferredEngine($engine) @@ -1583,7 +1636,7 @@ function setPreferredEngine($engine) /** * Returns the engine currently being utilized * - * @see \phpseclib\Crypt\Base::_setEngine() + * @see self::_setEngine() * @access public */ function getEngine() @@ -1594,7 +1647,7 @@ function getEngine() /** * Sets the engine as appropriate * - * @see \phpseclib\Crypt\Base::Crypt_Base() + * @see self::__construct() * @access private */ function _setEngine() @@ -1639,8 +1692,8 @@ function _setEngine() * Note: Must be extended by the child \phpseclib\Crypt\* class * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ abstract function _encryptBlock($in); @@ -1650,8 +1703,8 @@ abstract function _encryptBlock($in); * Note: Must be extended by the child \phpseclib\Crypt\* class * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ abstract function _decryptBlock($in); @@ -1662,7 +1715,7 @@ abstract function _decryptBlock($in); * * Note: Must extend by the child \phpseclib\Crypt\* class * - * @see \phpseclib\Crypt\Base::_setup() + * @see self::_setup() * @access private */ abstract function _setupKey(); @@ -1684,9 +1737,9 @@ abstract function _setupKey(); * * - First run of encrypt() / decrypt() with no init-settings * - * @see setKey() - * @see setIV() - * @see disableContinuousBuffer() + * @see self::setKey() + * @see self::setIV() + * @see self::disableContinuousBuffer() * @access private * @internal _setup() is always called before en/decryption. * @internal Could, but not must, extend by the child Crypt_* class @@ -1718,9 +1771,9 @@ function _setup() * * - First run of encrypt() / decrypt() * - * @see setKey() - * @see setIV() - * @see disableContinuousBuffer() + * @see self::setKey() + * @see self::setIV() + * @see self::disableContinuousBuffer() * @access private * @internal Could, but not must, extend by the child Crypt_* class */ @@ -1748,7 +1801,6 @@ function _setupMcrypt() if ($this->mode == self::MODE_CFB) { $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, ''); } - } // else should mcrypt_generic_deinit be called? if ($this->mode == self::MODE_CFB) { @@ -1766,10 +1818,10 @@ function _setupMcrypt() * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless * and padding will, hence forth, be enabled. * - * @see \phpseclib\Crypt\Base::_unpad() - * @param String $text + * @see self::_unpad() + * @param string $text * @access private - * @return String + * @return string */ function _pad($text) { @@ -1795,10 +1847,10 @@ function _pad($text) * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong * and false will be returned. * - * @see \phpseclib\Crypt\Base::_pad() - * @param String $text + * @see self::_pad() + * @param string $text * @access private - * @return String + * @return string */ function _unpad($text) { @@ -1832,6 +1884,10 @@ function _clearBuffers() // mcrypt's handling of invalid's $iv: // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size); $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0"); + + if (!$this->skip_key_adjustment) { + $this->key = str_pad(substr($this->key, 0, $this->key_length), $this->key_length, "\0"); + } } /** @@ -1839,10 +1895,10 @@ function _clearBuffers() * * Inspired by array_shift * - * @param String $string - * @param optional Integer $index + * @param string $string + * @param int $index * @access private - * @return String + * @return string */ function _string_shift(&$string, $index = 1) { @@ -1856,10 +1912,10 @@ function _string_shift(&$string, $index = 1) * * Inspired by array_pop * - * @param String $string - * @param optional Integer $index + * @param string $string + * @param int $index * @access private - * @return String + * @return string */ function _string_pop(&$string, $index = 1) { @@ -1871,9 +1927,9 @@ function _string_pop(&$string, $index = 1) /** * Increment the current string * - * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\Base::encrypt() - * @param String $var + * @see self::decrypt() + * @see self::encrypt() + * @param string $var * @access private */ function _increment_str(&$var) @@ -1958,10 +2014,10 @@ function _increment_str(&$var) * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only * * - * @see \phpseclib\Crypt\Base::_setup() - * @see \phpseclib\Crypt\Base::_createInlineCryptFunction() - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::decrypt() + * @see self::_setup() + * @see self::_createInlineCryptFunction() + * @see self::encrypt() + * @see self::decrypt() * @access private * @internal If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt() */ @@ -2080,12 +2136,12 @@ function _setupInlineCrypt() * ); * * - * @see \phpseclib\Crypt\Base::_setupInlineCrypt() - * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\Base::decrypt() - * @param Array $cipher_code + * @see self::_setupInlineCrypt() + * @see self::encrypt() + * @see self::decrypt() + * @param array $cipher_code * @access private - * @return String (the name of the created callback function) + * @return string (the name of the created callback function) */ function _createInlineCryptFunction($cipher_code) { @@ -2447,12 +2503,12 @@ function _createInlineCryptFunction($cipher_code) * is stored, classwide (!), here for reusing. * * The string-based index of $function is a classwide - * uniqe value representing, at least, the $mode of + * unique value representing, at least, the $mode of * operation (or more... depends of the optimizing level) * for which $mode the lambda function was created. * * @access private - * @return Array &$functions + * @return array &$functions */ function &_getLambdaFunctions() { @@ -2463,10 +2519,10 @@ function &_getLambdaFunctions() /** * Generates a digest from $bytes * - * @see _setupInlineCrypt() + * @see self::_setupInlineCrypt() * @access private * @param $bytes - * @return String + * @return string */ function _hashInlineCryptFunction($bytes) { diff --git a/phpseclib/phpseclib/phpseclib/Crypt/Blowfish.php b/phpseclib/phpseclib/phpseclib/Crypt/Blowfish.php index 9844bafaf..3949e8123 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/Blowfish.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/Blowfish.php @@ -37,8 +37,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; - /** * Pure-PHP implementation of Blowfish. * @@ -53,26 +51,16 @@ class Blowfish extends Base * Block Length of the cipher * * @see \phpseclib\Crypt\Base::block_size - * @var Integer + * @var int * @access private */ var $block_size = 8; - /** - * The default password key_size used by setPassword() - * - * @see \phpseclib\Crypt\Base::password_key_size - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer - * @access private - */ - var $password_key_size = 56; - /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt - * @var String + * @var string * @access private */ var $cipher_name_mcrypt = 'blowfish'; @@ -81,7 +69,7 @@ class Blowfish extends Base * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len - * @var Integer + * @var int * @access private */ var $cfb_init_len = 500; @@ -94,7 +82,7 @@ class Blowfish extends Base * @access private * @var array */ - var $sbox0 = array ( + var $sbox0 = array( 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, @@ -277,53 +265,59 @@ class Blowfish extends Base /** * Holds the last used key * - * @var Array + * @var array * @access private */ var $kl; /** - * Sets the key. + * The Key Length (in bytes) * - * Keys can be of any length. Blowfish, itself, requires the use of a key between 32 and max. 448-bits long. - * If the key is less than 32-bits we NOT fill the key to 32bit but let the key as it is to be compatible - * with mcrypt because mcrypt act this way with blowfish key's < 32 bits. - * - * If the key is more than 448-bits, we trim the excess bits. + * @see \phpseclib\Crypt\Base::setKeyLength() + * @var int + * @access private + * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk + * because the encryption / decryption / key schedule creation requires this number and not $key_length. We could + * derive this from $key_length or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu + * of that, we'll just precompute it once. + */ + var $key_length = 16; + + /** + * Sets the key length. * - * If the key is not explicitly set, or empty, it'll be assumed a 128 bits key to be all null bytes. + * Key lengths can be between 32 and 448 bits. * * @access public - * @see \phpseclib\Crypt\Base::setKey() - * @param String $key + * @param int $length */ - function setKey($key) + function setKeyLength($length) { - $keylength = strlen($key); - - if (!$keylength) { - $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; - } elseif ($keylength > 56) { - $key = substr($key, 0, 56); + if ($length < 32) { + $this->key_length = 7; + } elseif ($length > 448) { + $this->key_length = 56; + } else { + $this->key_length = $length >> 3; } - parent::setKey($key); + parent::setKeyLength($length); } /** * Test for engine validity * - * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine() * * @see \phpseclib\Crypt\Base::isValidEngine() - * @param Integer $engine + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { if ($engine == self::ENGINE_OPENSSL) { - if (strlen($this->key) != 16) { + if ($this->key_length != 16) { return false; } $this->cipher_name_openssl_ecb = 'bf-ecb'; @@ -393,8 +387,8 @@ function _setupKey() * Encrypts a block * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _encryptBlock($in) { @@ -429,8 +423,8 @@ function _encryptBlock($in) * Decrypts a block * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _decryptBlock($in) { @@ -471,9 +465,9 @@ function _setupInlineCrypt() $lambda_functions =& self::_getLambdaFunctions(); // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. - // (Currently, for Crypt_Blowfish, one generated $lambda_function cost on php5.5@32bit ~100kb unfreeable mem and ~180kb on php5.5@64bit) + // (Currently, for Blowfish, one generated $lambda_function cost on php5.5@32bit ~100kb unfreeable mem and ~180kb on php5.5@64bit) // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one. - $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); // Generation of a unique hash for our generated code $code_hash = "Crypt_Blowfish, {$this->mode}"; diff --git a/phpseclib/phpseclib/phpseclib/Crypt/DES.php b/phpseclib/phpseclib/phpseclib/Crypt/DES.php index d748f1a56..512204691 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/DES.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/DES.php @@ -42,8 +42,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; - /** * Pure-PHP implementation of DES. * @@ -64,7 +62,7 @@ class DES extends Base const ENCRYPT = 0; /** * Contains $keys[self::DECRYPT] - */ + */ const DECRYPT = 1; /**#@-*/ @@ -72,36 +70,25 @@ class DES extends Base * Block Length of the cipher * * @see \phpseclib\Crypt\Base::block_size - * @var Integer + * @var int * @access private */ var $block_size = 8; /** - * The Key - * - * @see \phpseclib\Crypt\Base::key - * @see setKey() - * @var String - * @access private - */ - var $key = "\0\0\0\0\0\0\0\0"; - - /** - * The default password key_size used by setPassword() + * Key Length (in bytes) * - * @see \phpseclib\Crypt\Base::password_key_size - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer + * @see \phpseclib\Crypt\Base::setKeyLength() + * @var int * @access private */ - var $password_key_size = 8; + var $key_length = 8; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt - * @var String + * @var string * @access private */ var $cipher_name_mcrypt = 'des'; @@ -110,7 +97,7 @@ class DES extends Base * The OpenSSL names of the cipher / modes * * @see \phpseclib\Crypt\Base::openssl_mode_names - * @var Array + * @var array * @access private */ var $openssl_mode_names = array( @@ -125,7 +112,7 @@ class DES extends Base * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len - * @var Integer + * @var int * @access private */ var $cfb_init_len = 500; @@ -135,9 +122,9 @@ class DES extends Base * * Used only if $engine == self::ENGINE_INTERNAL * - * @see \phpseclib\Crypt\DES::_setupKey() - * @see \phpseclib\Crypt\DES::_processBlock() - * @var Integer + * @see self::_setupKey() + * @see self::_processBlock() + * @var int * @access private */ var $des_rounds = 1; @@ -145,17 +132,17 @@ class DES extends Base /** * max possible size of $key * - * @see \phpseclib\Crypt\DES::setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ - var $key_size_max = 8; + var $key_length_max = 8; /** * The Key Schedule * - * @see \phpseclib\Crypt\DES::_setupKey() - * @var Array + * @see self::_setupKey() + * @var array * @access private */ var $keys; @@ -167,9 +154,9 @@ class DES extends Base * with each byte containing all bits in the same state as the * corresponding bit in the index value. * - * @see \phpseclib\Crypt\DES::_processBlock() - * @see \phpseclib\Crypt\DES::_setupKey() - * @var Array + * @see self::_processBlock() + * @see self::_setupKey() + * @var array * @access private */ var $shuffle = array( @@ -308,7 +295,7 @@ class DES extends Base * * Indexing this table with each source byte performs the initial bit permutation. * - * @var Array + * @var array * @access private */ var $ipmap = array( @@ -350,7 +337,7 @@ class DES extends Base * Inverse IP mapping helper table. * Indexing this table with a byte value reverses the bit order. * - * @var Array + * @var array * @access private */ var $invipmap = array( @@ -394,7 +381,7 @@ class DES extends Base * Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the * P table: concatenation can then be replaced by exclusive ORs. * - * @var Array + * @var array * @access private */ var $sbox1 = array( @@ -419,7 +406,7 @@ class DES extends Base /** * Pre-permuted S-box2 * - * @var Array + * @var array * @access private */ var $sbox2 = array( @@ -444,7 +431,7 @@ class DES extends Base /** * Pre-permuted S-box3 * - * @var Array + * @var array * @access private */ var $sbox3 = array( @@ -469,7 +456,7 @@ class DES extends Base /** * Pre-permuted S-box4 * - * @var Array + * @var array * @access private */ var $sbox4 = array( @@ -494,7 +481,7 @@ class DES extends Base /** * Pre-permuted S-box5 * - * @var Array + * @var array * @access private */ var $sbox5 = array( @@ -519,7 +506,7 @@ class DES extends Base /** * Pre-permuted S-box6 * - * @var Array + * @var array * @access private */ var $sbox6 = array( @@ -544,7 +531,7 @@ class DES extends Base /** * Pre-permuted S-box7 * - * @var Array + * @var array * @access private */ var $sbox7 = array( @@ -569,7 +556,7 @@ class DES extends Base /** * Pre-permuted S-box8 * - * @var Array + * @var array * @access private */ var $sbox8 = array( @@ -594,16 +581,16 @@ class DES extends Base /** * Test for engine validity * - * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine() * * @see \phpseclib\Crypt\Base::isValidEngine() - * @param Integer $engine + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { - if ($this->key_size_max == 8) { + if ($this->key_length_max == 8) { if ($engine == self::ENGINE_OPENSSL) { $this->cipher_name_openssl_ecb = 'des-ecb'; $this->cipher_name_openssl = 'des-' . $this->_openssl_translate_mode(); @@ -626,14 +613,14 @@ function isValidEngine($engine) * * @see \phpseclib\Crypt\Base::setKey() * @access public - * @param String $key + * @param string $key */ function setKey($key) { // We check/cut here only up to max length of the key. // Key padding to the proper length will be done in _setupKey() - if (strlen($key) > $this->key_size_max) { - $key = substr($key, 0, $this->key_size_max); + if (strlen($key) > $this->key_length_max) { + $key = substr($key, 0, $this->key_length_max); } // Sets the key @@ -645,10 +632,10 @@ function setKey($key) * * @see \phpseclib\Crypt\Base::_encryptBlock() * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\DES::encrypt() + * @see self::encrypt() * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _encryptBlock($in) { @@ -660,10 +647,10 @@ function _encryptBlock($in) * * @see \phpseclib\Crypt\Base::_decryptBlock() * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\DES::decrypt() + * @see self::decrypt() * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _decryptBlock($in) { @@ -677,12 +664,12 @@ function _decryptBlock($in) * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general * idea of what this function does. * - * @see \phpseclib\Crypt\DES::_encryptBlock() - * @see \phpseclib\Crypt\DES::_decryptBlock() + * @see self::_encryptBlock() + * @see self::_decryptBlock() * @access private - * @param String $block - * @param Integer $mode - * @return String + * @param string $block + * @param int $mode + * @return string */ function _processBlock($block, $mode) { @@ -1310,12 +1297,12 @@ function _setupInlineCrypt() $des_rounds = $this->des_rounds; // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. - // (Currently, for Crypt_DES, one generated $lambda_function cost on php5.5@32bit ~135kb unfreeable mem and ~230kb on php5.5@64bit) - // (Currently, for Crypt_TripleDES, one generated $lambda_function cost on php5.5@32bit ~240kb unfreeable mem and ~340kb on php5.5@64bit) + // (Currently, for DES, one generated $lambda_function cost on php5.5@32bit ~135kb unfreeable mem and ~230kb on php5.5@64bit) + // (Currently, for TripleDES, one generated $lambda_function cost on php5.5@32bit ~240kb unfreeable mem and ~340kb on php5.5@64bit) // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); - // Generation of a uniqe hash for our generated code + // Generation of a unique hash for our generated code $code_hash = "Crypt_DES, $des_rounds, {$this->mode}"; if ($gen_hi_opt_code) { // For hi-optimized code, we create for each combination of diff --git a/phpseclib/phpseclib/phpseclib/Crypt/Hash.php b/phpseclib/phpseclib/phpseclib/Crypt/Hash.php index 14b8a32ac..07665a165 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/Hash.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/Hash.php @@ -7,7 +7,7 @@ * * md2, md5, md5-96, sha1, sha1-96, sha256, sha256-96, sha384, and sha512, sha512-96 * - * If {@link \phpseclib\Crypt\Hash::setKey() setKey()} is called, {@link \phpseclib\Crypt\Hash::hash() hash()} will return the HMAC as opposed to + * If {@link self::setKey() setKey()} is called, {@link self::hash() hash()} will return the HMAC as opposed to * the hash. If no valid algorithm is provided, sha1 will be used. * * PHP version 5 @@ -59,19 +59,19 @@ class Hash const MODE_INTERNAL = 1; /** * Toggles the mhash() implementation, which has been deprecated on PHP 5.3.0+. - */ + */ const MODE_MHASH = 2; /** * Toggles the hash() implementation, which works on PHP 5.1.2+. - */ + */ const MODE_HASH = 3; /**#@-*/ /** * Hash Parameter * - * @see \phpseclib\Crypt\Hash::setHash() - * @var Integer + * @see self::setHash() + * @var int * @access private */ var $hashParam; @@ -79,8 +79,8 @@ class Hash /** * Byte-length of compression blocks / key (Internal HMAC) * - * @see \phpseclib\Crypt\Hash::setAlgorithm() - * @var Integer + * @see self::setAlgorithm() + * @var int * @access private */ var $b; @@ -88,8 +88,8 @@ class Hash /** * Byte-length of hash output (Internal HMAC) * - * @see \phpseclib\Crypt\Hash::setHash() - * @var Integer + * @see self::setHash() + * @var int * @access private */ var $l = false; @@ -97,8 +97,8 @@ class Hash /** * Hash Algorithm * - * @see \phpseclib\Crypt\Hash::setHash() - * @var String + * @see self::setHash() + * @var string * @access private */ var $hash; @@ -106,8 +106,8 @@ class Hash /** * Key * - * @see \phpseclib\Crypt\Hash::setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ var $key = false; @@ -115,8 +115,8 @@ class Hash /** * Outer XOR (Internal HMAC) * - * @see \phpseclib\Crypt\Hash::setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ var $opad; @@ -124,8 +124,8 @@ class Hash /** * Inner XOR (Internal HMAC) * - * @see \phpseclib\Crypt\Hash::setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ var $ipad; @@ -133,7 +133,7 @@ class Hash /** * Default Constructor. * - * @param optional String $hash + * @param string $hash * @return \phpseclib\Crypt\Hash * @access public */ @@ -161,7 +161,7 @@ function __construct($hash = 'sha1') * Keys can be of any length. * * @access public - * @param optional String $key + * @param string $key */ function setKey($key = false) { @@ -174,7 +174,7 @@ function setKey($key = false) * As set by the constructor or by the setHash() method. * * @access public - * @return String + * @return string */ function getHash() { @@ -185,7 +185,7 @@ function getHash() * Sets the hash function. * * @access public - * @param String $hash + * @param string $hash */ function setHash($hash) { @@ -292,8 +292,8 @@ function setHash($hash) * Compute the HMAC. * * @access public - * @param String $text - * @return String + * @param string $text + * @return string */ function hash($text) { @@ -342,7 +342,7 @@ function hash($text) * Returns the hash length (in bytes) * * @access public - * @return Integer + * @return int */ function getLength() { @@ -353,7 +353,7 @@ function getLength() * Wrapper for MD5 * * @access private - * @param String $m + * @param string $m */ function _md5($m) { @@ -364,7 +364,7 @@ function _md5($m) * Wrapper for SHA1 * * @access private - * @param String $m + * @param string $m */ function _sha1($m) { @@ -377,7 +377,7 @@ function _sha1($m) * See {@link http://tools.ietf.org/html/rfc1319 RFC1319}. * * @access private - * @param String $m + * @param string $m */ function _md2($m) { @@ -453,7 +453,7 @@ function _md2($m) * See {@link http://en.wikipedia.org/wiki/SHA_hash_functions#SHA-256_.28a_SHA-2_variant.29_pseudocode SHA-256 (a SHA-2 variant) pseudocode - Wikipedia}. * * @access private - * @param String $m + * @param string $m */ function _sha256($m) { @@ -506,7 +506,6 @@ function _sha256($m) $this->_rightShift( $w[$i - 2], 10); // @codingStandardsIgnoreEnd $w[$i] = $this->_add($w[$i - 16], $s0, $w[$i - 7], $s1); - } // Initialize hash value for this chunk @@ -560,7 +559,7 @@ function _sha256($m) * Pure-PHP implementation of SHA384 and SHA512 * * @access private - * @param String $m + * @param string $m */ function _sha512($m) { @@ -739,10 +738,10 @@ function _sha512($m) * Right Rotate * * @access private - * @param Integer $int - * @param Integer $amt - * @see _sha256() - * @return Integer + * @param int $int + * @param int $amt + * @see self::_sha256() + * @return int */ function _rightRotate($int, $amt) { @@ -755,10 +754,10 @@ function _rightRotate($int, $amt) * Right Shift * * @access private - * @param Integer $int - * @param Integer $amt - * @see _sha256() - * @return Integer + * @param int $int + * @param int $amt + * @see self::_sha256() + * @return int */ function _rightShift($int, $amt) { @@ -770,9 +769,9 @@ function _rightShift($int, $amt) * Not * * @access private - * @param Integer $int - * @see _sha256() - * @return Integer + * @param int $int + * @see self::_sha256() + * @return int */ function _not($int) { @@ -785,9 +784,9 @@ function _not($int) * _sha256() adds multiple unsigned 32-bit integers. Since PHP doesn't support unsigned integers and since the * possibility of overflow exists, care has to be taken. BigInteger could be used but this should be faster. * - * @param Integer $... - * @return Integer - * @see _sha256() + * @param int $... + * @return int + * @see self::_sha256() * @access private */ function _add() @@ -811,9 +810,9 @@ function _add() * * Inspired by array_shift * - * @param String $string - * @param optional Integer $index - * @return String + * @param string $string + * @param int $index + * @return string * @access private */ function _string_shift(&$string, $index = 1) diff --git a/phpseclib/phpseclib/phpseclib/Crypt/RC2.php b/phpseclib/phpseclib/phpseclib/Crypt/RC2.php index 583517598..e9cfa3f83 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/RC2.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/RC2.php @@ -35,8 +35,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; - /** * Pure-PHP implementation of RC2. * @@ -49,7 +47,7 @@ class RC2 extends Base * Block Length of the cipher * * @see \phpseclib\Crypt\Base::block_size - * @var Integer + * @var int * @access private */ var $block_size = 8; @@ -58,8 +56,8 @@ class RC2 extends Base * The Key * * @see \phpseclib\Crypt\Base::key - * @see setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ var $key; @@ -68,29 +66,37 @@ class RC2 extends Base * The Original (unpadded) Key * * @see \phpseclib\Crypt\Base::key - * @see setKey() - * @see encrypt() - * @see decrypt() - * @var String + * @see self::setKey() + * @see self::encrypt() + * @see self::decrypt() + * @var string * @access private */ var $orig_key; /** - * The default password key_size used by setPassword() + * Don't truncate / null pad key * - * @see \phpseclib\Crypt\Base::password_key_size - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer + * @see \phpseclib\Crypt\Base::_clearBuffers() + * @var bool * @access private */ - var $password_key_size = 16; // = 128 bits + var $skip_key_adjustment = true; + + /** + * Key Length (in bytes) + * + * @see \phpseclib\Crypt\RC2::setKeyLength() + * @var int + * @access private + */ + var $key_length = 16; // = 128 bits /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt - * @var String + * @var string * @access private */ var $cipher_name_mcrypt = 'rc2'; @@ -99,7 +105,7 @@ class RC2 extends Base * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len - * @var Integer + * @var int * @access private */ var $cfb_init_len = 500; @@ -107,9 +113,9 @@ class RC2 extends Base /** * The key length in bits. * - * @see \phpseclib\Crypt\RC2::setKeyLength() - * @see \phpseclib\Crypt\RC2::setKey() - * @var Integer + * @see self::setKeyLength() + * @see self::setKey() + * @var int * @access private * @internal Should be in range [1..1024]. * @internal Changing this value after setting the key has no effect. @@ -119,9 +125,9 @@ class RC2 extends Base /** * The key length in bits. * - * @see \phpseclib\Crypt\RC2::isValidEnine() - * @see \phpseclib\Crypt\RC2::setKey() - * @var Integer + * @see self::isValidEnine() + * @see self::setKey() + * @var int * @access private * @internal Should be in range [1..1024]. */ @@ -130,8 +136,8 @@ class RC2 extends Base /** * The Key Schedule * - * @see \phpseclib\Crypt\RC2::_setupKey() - * @var Array + * @see self::_setupKey() + * @var array * @access private */ var $keys; @@ -140,8 +146,8 @@ class RC2 extends Base * Key expansion randomization table. * Twice the same 256-value sequence to save a modulus in key expansion. * - * @see \phpseclib\Crypt\RC2::setKey() - * @var Array + * @see self::setKey() + * @var array * @access private */ var $pitable = array( @@ -214,8 +220,8 @@ class RC2 extends Base /** * Inverse key expansion randomization table. * - * @see \phpseclib\Crypt\RC2::setKey() - * @var Array + * @see self::setKey() + * @var array * @access private */ var $invpitable = array( @@ -256,18 +262,18 @@ class RC2 extends Base /** * Test for engine validity * - * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine() * - * @see \phpseclib\Crypt\Base::Crypt_Base() - * @param Integer $engine + * @see \phpseclib\Crypt\Base::__construct() + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { switch ($engine) { case self::ENGINE_OPENSSL: - if ($this->current_key_length != 128 || strlen($this->orig_key) != 16) { + if ($this->current_key_length != 128 || strlen($this->orig_key) < 16) { return false; } $this->cipher_name_openssl_ecb = 'rc2-ecb'; @@ -278,26 +284,44 @@ function isValidEngine($engine) } /** - * Sets the key length + * Sets the key length. * - * Valid key lengths are 1 to 1024. + * Valid key lengths are 8 to 1024. * Calling this function after setting the key has no effect until the next * \phpseclib\Crypt\RC2::setKey() call. * * @access public - * @param Integer $length in bits + * @param int $length in bits */ function setKeyLength($length) { - if ($length >= 1 && $length <= 1024) { + if ($length < 8) { + $this->default_key_length = 8; + } elseif ($length > 1024) { + $this->default_key_length = 128; + } else { $this->default_key_length = $length; } + $this->current_key_length = $this->default_key_length; + + parent::setKeyLength($length); + } + + /** + * Returns the current key length + * + * @access public + * @return int + */ + function getKeyLength() + { + return $this->current_key_length; } /** * Sets the key. * - * Keys can be of any length. RC2, itself, uses 1 to 1024 bit keys (eg. + * Keys can be of any length. RC2, itself, uses 8 to 1024 bit keys (eg. * strlen($key) <= 128), however, we only use the first 128 bytes if $key * has more then 128 bytes in it, and set $key to a single null byte if * it is empty. @@ -307,8 +331,8 @@ function setKeyLength($length) * * @see \phpseclib\Crypt\Base::setKey() * @access public - * @param String $key - * @param Integer $t1 optional Effective key length in bits. + * @param string $key + * @param int $t1 optional Effective key length in bits. */ function setKey($key, $t1 = 0) { @@ -349,18 +373,19 @@ function setKey($key, $t1 = 0) // Prepare the key for mcrypt. $l[0] = $this->invpitable[$l[0]]; array_unshift($l, 'C*'); + parent::setKey(call_user_func_array('pack', $l)); } /** * Encrypts a message. * - * Mostly a wrapper for Crypt_Base::encrypt, with some additional OpenSSL handling code + * Mostly a wrapper for \phpseclib\Crypt\Base::encrypt, with some additional OpenSSL handling code * - * @see decrypt() + * @see self::decrypt() * @access public - * @param String $plaintext - * @return String $ciphertext + * @param string $plaintext + * @return string $ciphertext */ function encrypt($plaintext) { @@ -378,12 +403,12 @@ function encrypt($plaintext) /** * Decrypts a message. * - * Mostly a wrapper for Crypt_Base::decrypt, with some additional OpenSSL handling code + * Mostly a wrapper for \phpseclib\Crypt\Base::decrypt, with some additional OpenSSL handling code * - * @see encrypt() + * @see self::encrypt() * @access public - * @param String $ciphertext - * @return String $plaintext + * @param string $ciphertext + * @return string $plaintext */ function decrypt($ciphertext) { @@ -395,7 +420,7 @@ function decrypt($ciphertext) return $result; } - return parent::encrypt($ciphertext); + return parent::decrypt($ciphertext); } /** @@ -404,8 +429,8 @@ function decrypt($ciphertext) * @see \phpseclib\Crypt\Base::_encryptBlock() * @see \phpseclib\Crypt\Base::encrypt() * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _encryptBlock($in) { @@ -449,8 +474,8 @@ function _encryptBlock($in) * @see \phpseclib\Crypt\Base::_decryptBlock() * @see \phpseclib\Crypt\Base::decrypt() * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _decryptBlock($in) { @@ -538,9 +563,9 @@ function _setupInlineCrypt() // for the mixing rounds, for better inline crypt performance [~20% faster]. // But for memory reason we have to limit those ultra-optimized $lambda_functions to an amount of 10. // (Currently, for Crypt_RC2, one generated $lambda_function cost on php5.5@32bit ~60kb unfreeable mem and ~100kb on php5.5@64bit) - $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); - // Generation of a uniqe hash for our generated code + // Generation of a unique hash for our generated code $code_hash = "Crypt_RC2, {$this->mode}"; if ($gen_hi_opt_code) { $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); diff --git a/phpseclib/phpseclib/phpseclib/Crypt/RC4.php b/phpseclib/phpseclib/phpseclib/Crypt/RC4.php index 2c7f74c21..1e768d7d9 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/RC4.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/RC4.php @@ -44,8 +44,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; - /** * Pure-PHP implementation of RC4. * @@ -70,26 +68,25 @@ class RC4 extends Base * so we the block_size to 0 * * @see \phpseclib\Crypt\Base::block_size - * @var Integer + * @var int * @access private */ var $block_size = 0; /** - * The default password key_size used by setPassword() + * Key Length (in bytes) * - * @see \phpseclib\Crypt\Base::password_key_size - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer + * @see \phpseclib\Crypt\RC4::setKeyLength() + * @var int * @access private */ - var $password_key_size = 128; // = 1024 bits + var $key_length = 128; // = 1024 bits /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt - * @var String + * @var string * @access private */ var $cipher_name_mcrypt = 'arcfour'; @@ -106,8 +103,8 @@ class RC4 extends Base /** * The Key * - * @see \phpseclib\Crypt\RC4::setKey() - * @var String + * @see self::setKey() + * @var string * @access private */ var $key = "\0"; @@ -115,8 +112,8 @@ class RC4 extends Base /** * The Key Stream for decryption and encryption * - * @see \phpseclib\Crypt\RC4::setKey() - * @var Array + * @see self::setKey() + * @var array * @access private */ var $stream; @@ -138,12 +135,12 @@ function __construct() /** * Test for engine validity * - * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine() * - * @see Crypt_Base::Crypt_Base() - * @param Integer $engine + * @see \phpseclib\Crypt\Base::__construct() + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { @@ -182,8 +179,8 @@ function isValidEngine($engine) * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009} * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack} * - * @param String $iv - * @see \phpseclib\Crypt\RC4::setKey() + * @param string $iv + * @see self::setKey() * @access public */ function setIV($iv) @@ -191,28 +188,34 @@ function setIV($iv) } /** - * Sets the key. + * Sets the key length * - * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will - * be used. If no key is explicitly set, it'll be assumed to be a single null byte. + * Keys can be between 1 and 256 bytes long. * * @access public - * @see \phpseclib\Crypt\Base::setKey() - * @param String $key + * @param int $length */ - function setKey($key) + function setKeyLength($length) { - parent::setKey(substr($key, 0, 256)); + if ($length < 8) { + $this->key_length = 1; + } elseif ($length > 2048) { + $this->key_length = 256; + } else { + $this->key_length = $length >> 3; + } + + parent::setKeyLength($length); } /** * Encrypts a message. * * @see \phpseclib\Crypt\Base::decrypt() - * @see \phpseclib\Crypt\RC4::_crypt() + * @see self::_crypt() * @access public - * @param String $plaintext - * @return String $ciphertext + * @param string $plaintext + * @return string $ciphertext */ function encrypt($plaintext) { @@ -229,10 +232,10 @@ function encrypt($plaintext) * At least if the continuous buffer is disabled. * * @see \phpseclib\Crypt\Base::encrypt() - * @see \phpseclib\Crypt\RC4::_crypt() + * @see self::_crypt() * @access public - * @param String $ciphertext - * @return String $plaintext + * @param string $ciphertext + * @return string $plaintext */ function decrypt($ciphertext) { @@ -246,7 +249,7 @@ function decrypt($ciphertext) * Encrypts a block * * @access private - * @param String $in + * @param string $in */ function _encryptBlock($in) { @@ -257,7 +260,7 @@ function _encryptBlock($in) * Decrypts a block * * @access private - * @param String $in + * @param string $in */ function _decryptBlock($in) { @@ -294,12 +297,12 @@ function _setupKey() /** * Encrypts or decrypts a message. * - * @see \phpseclib\Crypt\RC4::encrypt() - * @see \phpseclib\Crypt\RC4::decrypt() + * @see self::encrypt() + * @see self::decrypt() * @access private - * @param String $text - * @param Integer $mode - * @return String $text + * @param string $text + * @param int $mode + * @return string $text */ function _crypt($text, $mode) { diff --git a/phpseclib/phpseclib/phpseclib/Crypt/RSA.php b/phpseclib/phpseclib/phpseclib/Crypt/RSA.php index 238f30cdc..ef508a433 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/RSA.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/RSA.php @@ -51,13 +51,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\AES; -use phpseclib\Crypt\Base; -use phpseclib\Crypt\DES; -use phpseclib\Crypt\Hash; -use phpseclib\Crypt\Random; -use phpseclib\Crypt\RSA; -use phpseclib\Crypt\TripleDES; use phpseclib\Math\BigInteger; /** @@ -71,8 +64,8 @@ class RSA { /**#@+ * @access public - * @see \phpseclib\Crypt\RSA::encrypt() - * @see \phpseclib\Crypt\RSA::decrypt() + * @see self::encrypt() + * @see self::decrypt() */ /** * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding} @@ -80,8 +73,8 @@ class RSA * * Uses sha1 by default. * - * @see \phpseclib\Crypt\RSA::setHash() - * @see \phpseclib\Crypt\RSA::setMGFHash() + * @see self::setHash() + * @see self::setMGFHash() */ const ENCRYPTION_OAEP = 1; /** @@ -89,7 +82,7 @@ class RSA * * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards * compatibility with protocols (like SSH-1) written before OAEP's introduction. - */ + */ const ENCRYPTION_PKCS1 = 2; /** * Do not use any padding @@ -102,25 +95,25 @@ class RSA /**#@+ * @access public - * @see \phpseclib\Crypt\RSA::sign() - * @see \phpseclib\Crypt\RSA::verify() - * @see \phpseclib\Crypt\RSA::setHash() + * @see self::sign() + * @see self::verify() + * @see self::setHash() */ /** * Use the Probabilistic Signature Scheme for signing * * Uses sha1 by default. * - * @see \phpseclib\Crypt\RSA::setSaltLength() - * @see \phpseclib\Crypt\RSA::setMGFHash() - */ + * @see self::setSaltLength() + * @see self::setMGFHash() + */ const SIGNATURE_PSS = 1; /** * Use the PKCS#1 scheme by default. * * Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards * compatibility with protocols (like SSH-2) written before PSS's introduction. - */ + */ const SIGNATURE_PKCS1 = 2; /**#@-*/ @@ -130,23 +123,23 @@ class RSA */ /** * ASN1 Integer - */ + */ const ASN1_INTEGER = 2; /** * ASN1 Bit String - */ + */ const ASN1_BITSTRING = 3; /** * ASN1 Octet String - */ + */ const ASN1_OCTETSTRING = 4; /** * ASN1 Object Identifier - */ + */ const ASN1_OBJECT = 6; /** * ASN1 Sequence (with the constucted bit set) - */ + */ const ASN1_SEQUENCE = 48; /**#@-*/ @@ -156,13 +149,13 @@ class RSA */ /** * To use the pure-PHP implementation - */ + */ const MODE_INTERNAL = 1; /** * To use the OpenSSL library * * (if enabled; otherwise, the internal implementation will be used) - */ + */ const MODE_OPENSSL = 2; /**#@-*/ @@ -175,20 +168,20 @@ class RSA * PKCS#1 formatted private key * * Used by OpenSSH - */ + */ const PRIVATE_FORMAT_PKCS1 = 0; /** * PuTTY formatted private key - */ + */ const PRIVATE_FORMAT_PUTTY = 1; /** * XML formatted private key - */ + */ const PRIVATE_FORMAT_XML = 2; /** * PKCS#8 formatted private key - */ - const PRIVATE_FORMAT_PKCS8 = 3; + */ + const PRIVATE_FORMAT_PKCS8 = 8; /**#@-*/ /**#@+ @@ -208,7 +201,7 @@ class RSA * The modulus can be indexed with any of the following: * * 1, n, modulo, modulus - */ + */ const PUBLIC_FORMAT_RAW = 3; /** * PKCS#1 formatted public key (raw) @@ -220,18 +213,18 @@ class RSA * -----BEGIN RSA PUBLIC KEY----- * * Analogous to ssh-keygen's pem format (as specified by -m) - */ + */ const PUBLIC_FORMAT_PKCS1 = 4; const PUBLIC_FORMAT_PKCS1_RAW = 4; /** * XML formatted public key - */ + */ const PUBLIC_FORMAT_XML = 5; /** * OpenSSH formatted public key * * Place in $HOME/.ssh/authorized_keys - */ + */ const PUBLIC_FORMAT_OPENSSH = 6; /** * PKCS#1 formatted public key (encapsulated) @@ -245,14 +238,14 @@ class RSA * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8 * is specific to private keys it's basically creating a DER-encoded wrapper * for keys. This just extends that same concept to public keys (much like ssh-keygen) - */ + */ const PUBLIC_FORMAT_PKCS8 = 7; /**#@-*/ /** * Precomputed Zero * - * @var Array + * @var \phpseclib\Math\BigInteger * @access private */ var $zero; @@ -260,7 +253,7 @@ class RSA /** * Precomputed One * - * @var Array + * @var \phpseclib\Math\BigInteger * @access private */ var $one; @@ -268,7 +261,7 @@ class RSA /** * Private Key Format * - * @var Integer + * @var int * @access private */ var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1; @@ -276,7 +269,7 @@ class RSA /** * Public Key Format * - * @var Integer + * @var int * @access public */ var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8; @@ -308,7 +301,7 @@ class RSA /** * Primes for Chinese Remainder Theorem (ie. p and q) * - * @var Array + * @var array * @access private */ var $primes; @@ -316,7 +309,7 @@ class RSA /** * Exponents for Chinese Remainder Theorem (ie. dP and dQ) * - * @var Array + * @var array * @access private */ var $exponents; @@ -324,7 +317,7 @@ class RSA /** * Coefficients for Chinese Remainder Theorem (ie. qInv) * - * @var Array + * @var array * @access private */ var $coefficients; @@ -332,7 +325,7 @@ class RSA /** * Hash name * - * @var String + * @var string * @access private */ var $hashName; @@ -348,7 +341,7 @@ class RSA /** * Length of hash function output * - * @var Integer + * @var int * @access private */ var $hLen; @@ -356,7 +349,7 @@ class RSA /** * Length of salt * - * @var Integer + * @var int * @access private */ var $sLen; @@ -372,7 +365,7 @@ class RSA /** * Length of MGF hash function output * - * @var Integer + * @var int * @access private */ var $mgfHLen; @@ -380,7 +373,7 @@ class RSA /** * Encryption mode * - * @var Integer + * @var int * @access private */ var $encryptionMode = self::ENCRYPTION_OAEP; @@ -388,7 +381,7 @@ class RSA /** * Signature mode * - * @var Integer + * @var int * @access private */ var $signatureMode = self::SIGNATURE_PSS; @@ -396,7 +389,7 @@ class RSA /** * Public Exponent * - * @var Mixed + * @var mixed * @access private */ var $publicExponent = false; @@ -404,7 +397,7 @@ class RSA /** * Password * - * @var String + * @var string * @access private */ var $password = false; @@ -415,8 +408,8 @@ class RSA * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions - * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't. * - * @see \phpseclib\Crypt\RSA::_start_element_handler() - * @var Array + * @see self::_start_element_handler() + * @var array * @access private */ var $components = array(); @@ -426,9 +419,9 @@ class RSA * * For use with parsing XML formatted keys. * - * @see \phpseclib\Crypt\RSA::_character_handler() - * @see \phpseclib\Crypt\RSA::_stop_element_handler() - * @var Mixed + * @see self::_character_handler() + * @see self::_stop_element_handler() + * @var mixed * @access private */ var $current; @@ -437,8 +430,8 @@ class RSA * OpenSSL configuration file name. * * Set to null to use system configuration file. - * @see \phpseclib\Crypt\RSA::createKey() - * @var Mixed + * @see self::createKey() + * @var mixed * @Access public */ var $configFile; @@ -446,7 +439,7 @@ class RSA /** * Public key comment field. * - * @var String + * @var string * @access private */ var $comment = 'phpseclib-generated-key'; @@ -473,11 +466,7 @@ function __construct() case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'): define('CRYPT_RSA_MODE', self::MODE_INTERNAL); break; - // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0 - case !function_exists('openssl_pkey_get_details'): - define('CRYPT_RSA_MODE', self::MODE_INTERNAL); - break; - case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile): + case extension_loaded('openssl') && file_exists($this->configFile): // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work ob_start(); @phpinfo(); @@ -505,6 +494,7 @@ function __construct() case !isset($versions['Header']): case !isset($versions['Library']): case $versions['Header'] == $versions['Library']: + case version_compare($versions['Header'], '1.0.0') >= 0 && version_compare($versions['Library'], '1.0.0') >= 0: define('CRYPT_RSA_MODE', self::MODE_OPENSSL); break; default: @@ -537,9 +527,9 @@ function __construct() * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing. * * @access public - * @param optional Integer $bits - * @param optional Integer $timeout - * @param optional array $p + * @param int $bits + * @param int $timeout + * @param array $p */ function createKey($bits = 1024, $timeout = false, $partial = array()) { @@ -717,9 +707,9 @@ function createKey($bits = 1024, $timeout = false, $partial = array()) * Convert a private key to the appropriate format. * * @access private - * @see setPrivateKeyFormat() - * @param String $RSAPrivateKey - * @return String + * @see self::setPrivateKeyFormat() + * @param string $RSAPrivateKey + * @return string */ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) { @@ -946,9 +936,9 @@ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) * Convert a public key to the appropriate format * * @access private - * @see setPublicKeyFormat() - * @param String $RSAPrivateKey - * @return String + * @see self::setPublicKeyFormat() + * @param string $RSAPrivateKey + * @return string */ function _convertPublicKey($n, $e) { @@ -1024,11 +1014,11 @@ function _convertPublicKey($n, $e) * Break a public or private key down into its constituant components * * @access private - * @see _convertPublicKey() - * @see _convertPrivateKey() - * @param String $key - * @param Integer $type - * @return Array + * @see self::_convertPublicKey() + * @see self::_convertPrivateKey() + * @param string $key + * @param int $type + * @return array */ function _parseKey($key, $type) { @@ -1423,7 +1413,7 @@ function. As is, the definitive authority on this encoding scheme isn't the IET * More specifically, this returns the size of the modulo in bits. * * @access public - * @return Integer + * @return int */ function getSize() { @@ -1436,9 +1426,9 @@ function getSize() * Called by xml_set_element_handler() * * @access private - * @param Resource $parser - * @param String $name - * @param Array $attribs + * @param resource $parser + * @param string $name + * @param array $attribs */ function _start_element_handler($parser, $name, $attribs) { @@ -1477,8 +1467,8 @@ function _start_element_handler($parser, $name, $attribs) * Called by xml_set_element_handler() * * @access private - * @param Resource $parser - * @param String $name + * @param resource $parser + * @param string $name */ function _stop_element_handler($parser, $name) { @@ -1494,8 +1484,8 @@ function _stop_element_handler($parser, $name) * Called by xml_set_character_data_handler() * * @access private - * @param Resource $parser - * @param String $data + * @param resource $parser + * @param string $data */ function _data_handler($parser, $data) { @@ -1511,8 +1501,8 @@ function _data_handler($parser, $data) * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed) * * @access public - * @param String $key - * @param Integer $type optional + * @param string $key + * @param int $type optional */ function loadKey($key, $type = false) { @@ -1577,7 +1567,6 @@ function loadKey($key, $type = false) break; } } - } else { $components = $this->_parseKey($key, $type); } @@ -1626,10 +1615,10 @@ function loadKey($key, $type = false) * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false. * Or rather, pass in $password such that empty($password) && !is_string($password) is true. * - * @see createKey() - * @see loadKey() + * @see self::createKey() + * @see self::loadKey() * @access public - * @param String $password + * @param string $password */ function setPassword($password = false) { @@ -1651,11 +1640,11 @@ function setPassword($password = false) * * Returns true on success, false on failure * - * @see getPublicKey() + * @see self::getPublicKey() * @access public - * @param String $key optional - * @param Integer $type optional - * @return Boolean + * @param string $key optional + * @param int $type optional + * @return bool */ function setPublicKey($key = false, $type = false) { @@ -1711,16 +1700,16 @@ function setPublicKey($key = false, $type = false) * * Returns true on success, false on failure * - * @see getPublicKey() + * @see self::getPublicKey() * @access public - * @param String $key optional - * @param Integer $type optional - * @return Boolean + * @param string $key optional + * @param int $type optional + * @return bool */ function setPrivateKey($key = false, $type = false) { if ($key === false && !empty($this->publicExponent)) { - unset($this->publicExponent); + $this->publicExponent = false; return true; } @@ -1728,7 +1717,7 @@ function setPrivateKey($key = false, $type = false) if (!$rsa->loadKey($key, $type)) { return false; } - unset($rsa->publicExponent); + $rsa->publicExponent = false; // don't overwrite the old key if the new key is invalid $this->loadKey($rsa); @@ -1742,10 +1731,10 @@ function setPrivateKey($key = false, $type = false) * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this * function won't return it since this library, for the most part, doesn't distinguish between public and private keys. * - * @see getPublicKey() + * @see self::getPublicKey() * @access public - * @param String $key - * @param Integer $type optional + * @param string $key + * @param int $type optional */ function getPublicKey($type = self::PUBLIC_FORMAT_PKCS8) { @@ -1768,10 +1757,11 @@ function getPublicKey($type = self::PUBLIC_FORMAT_PKCS8) * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716) * * @access public - * @param String $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned + * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned * for invalid values. + * @return mixed */ - public function getPublicKeyFingerprint($algorithm = 'md5') + function getPublicKeyFingerprint($algorithm = 'md5') { if (empty($this->modulus) || empty($this->publicExponent)) { return false; @@ -1792,7 +1782,6 @@ public function getPublicKeyFingerprint($algorithm = 'md5') default: return false; } - } /** @@ -1800,10 +1789,11 @@ public function getPublicKeyFingerprint($algorithm = 'md5') * * The private key is only returned if the currently loaded key contains the constituent prime numbers. * - * @see getPublicKey() + * @see self::getPublicKey() * @access public - * @param String $key - * @param Integer $type optional + * @param string $key + * @param int $type optional + * @return mixed */ function getPrivateKey($type = self::PUBLIC_FORMAT_PKCS1) { @@ -1824,10 +1814,10 @@ function getPrivateKey($type = self::PUBLIC_FORMAT_PKCS1) * Returns the private key without the prime number constituants. Structurally identical to a public key that * hasn't been set as the public key * - * @see getPrivateKey() + * @see self::getPrivateKey() * @access private - * @param String $key - * @param Integer $type optional + * @param string $key + * @param int $type optional */ function _getPrivatePublicKey($mode = self::PUBLIC_FORMAT_PKCS8) { @@ -1846,6 +1836,7 @@ function _getPrivatePublicKey($mode = self::PUBLIC_FORMAT_PKCS8) * __toString() magic method * * @access public + * @return string */ function __toString() { @@ -1861,6 +1852,7 @@ function __toString() * __clone() magic method * * @access public + * @return Crypt_RSA */ function __clone() { @@ -1873,8 +1865,8 @@ function __clone() * Generates the smallest and largest numbers requiring $bits bits * * @access private - * @param Integer $bits - * @return Array + * @param int $bits + * @return array */ function _generateMinMax($bits) { @@ -1902,8 +1894,8 @@ function _generateMinMax($bits) * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private - * @param String $string - * @return Integer + * @param string $string + * @return int */ function _decodeLength(&$string) { @@ -1923,8 +1915,8 @@ function _decodeLength(&$string) * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private - * @param Integer $length - * @return String + * @param int $length + * @return string */ function _encodeLength($length) { @@ -1941,9 +1933,9 @@ function _encodeLength($length) * * Inspired by array_shift * - * @param String $string - * @param optional Integer $index - * @return String + * @param string $string + * @param int $index + * @return string * @access private */ function _string_shift(&$string, $index = 1) @@ -1956,9 +1948,9 @@ function _string_shift(&$string, $index = 1) /** * Determines the private key format * - * @see createKey() + * @see self::createKey() * @access public - * @param Integer $format + * @param int $format */ function setPrivateKeyFormat($format) { @@ -1968,9 +1960,9 @@ function setPrivateKeyFormat($format) /** * Determines the public key format * - * @see createKey() + * @see self::createKey() * @access public - * @param Integer $format + * @param int $format */ function setPublicKeyFormat($format) { @@ -1984,7 +1976,7 @@ function setPublicKeyFormat($format) * decryption. If $hash isn't supported, sha1 is used. * * @access public - * @param String $hash + * @param string $hash */ function setHash($hash) { @@ -2013,7 +2005,7 @@ function setHash($hash) * best if Hash and MGFHash are set to the same thing this is not a requirement. * * @access public - * @param String $hash + * @param string $hash */ function setMGFHash($hash) { @@ -2042,7 +2034,7 @@ function setMGFHash($hash) * of the hash function Hash) and 0. * * @access public - * @param Integer $format + * @param int $format */ function setSaltLength($sLen) { @@ -2056,8 +2048,8 @@ function setSaltLength($sLen) * * @access private * @param \phpseclib\Math\BigInteger $x - * @param Integer $xLen - * @return String + * @param int $xLen + * @return string */ function _i2osp($x, $xLen) { @@ -2075,7 +2067,7 @@ function _i2osp($x, $xLen) * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}. * * @access private - * @param String $x + * @param string $x * @return \phpseclib\Math\BigInteger */ function _os2ip($x) @@ -2094,8 +2086,14 @@ function _os2ip($x) */ function _exponentiate($x) { - if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) { - return $x->modPow($this->exponent, $this->modulus); + switch (true) { + case empty($this->primes): + case $this->primes[1]->equals($this->zero): + case empty($this->coefficients): + case $this->coefficients[2]->equals($this->zero): + case empty($this->exponents): + case $this->exponents[1]->equals($this->zero): + return $x->modPow($this->exponent, $this->modulus); } $num_primes = count($this->primes); @@ -2169,7 +2167,7 @@ function _exponentiate($x) * @access private * @param \phpseclib\Math\BigInteger $x * @param \phpseclib\Math\BigInteger $r - * @param Integer $i + * @param int $i * @return \phpseclib\Math\BigInteger */ function _blind($x, $r, $i) @@ -2194,9 +2192,9 @@ function _blind($x, $r, $i) * Thanks for the heads up singpolyma! * * @access private - * @param String $x - * @param String $y - * @return Boolean + * @param string $x + * @param string $y + * @return bool */ function _equals($x, $y) { @@ -2290,9 +2288,9 @@ function _rsavp1($s) * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}. * * @access private - * @param String $mgfSeed - * @param Integer $mgfLen - * @return String + * @param string $mgfSeed + * @param int $mgfLen + * @return string */ function _mgf1($mgfSeed, $maskLen) { @@ -2315,9 +2313,9 @@ function _mgf1($mgfSeed, $maskLen) * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}. * * @access private - * @param String $m - * @param String $l - * @return String + * @param string $m + * @param string $l + * @return string */ function _rsaes_oaep_encrypt($m, $l = '') { @@ -2378,9 +2376,9 @@ function _rsaes_oaep_encrypt($m, $l = '') * this document. * * @access private - * @param String $c - * @param String $l - * @return String + * @param string $c + * @param string $l + * @return string */ function _rsaes_oaep_decrypt($c, $l = '') { @@ -2437,8 +2435,8 @@ function _rsaes_oaep_decrypt($c, $l = '') * Doesn't use padding and is not recommended. * * @access private - * @param String $m - * @return String + * @param string $m + * @return string */ function _raw_encrypt($m) { @@ -2453,8 +2451,8 @@ function _raw_encrypt($m) * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}. * * @access private - * @param String $m - * @return String + * @param string $m + * @return string */ function _rsaes_pkcs1_v1_5_encrypt($m) { @@ -2512,8 +2510,8 @@ function _rsaes_pkcs1_v1_5_encrypt($m) * not private key encrypted ciphertext's. * * @access private - * @param String $c - * @return String + * @param string $c + * @return string */ function _rsaes_pkcs1_v1_5_decrypt($c) { @@ -2561,8 +2559,8 @@ function _rsaes_pkcs1_v1_5_decrypt($c) * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}. * * @access private - * @param String $m - * @param Integer $emBits + * @param string $m + * @param int $emBits */ function _emsa_pss_encode($m, $emBits) { @@ -2570,7 +2568,7 @@ function _emsa_pss_encode($m, $emBits) // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8) - $sLen = $this->sLen === false ? $this->hLen : $this->sLen; + $sLen = $this->sLen !== null ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { @@ -2597,10 +2595,10 @@ function _emsa_pss_encode($m, $emBits) * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}. * * @access private - * @param String $m - * @param String $em - * @param Integer $emBits - * @return String + * @param string $m + * @param string $em + * @param int $emBits + * @return string */ function _emsa_pss_verify($m, $em, $emBits) { @@ -2608,7 +2606,7 @@ function _emsa_pss_verify($m, $em, $emBits) // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8); - $sLen = $this->sLen === false ? $this->hLen : $this->sLen; + $sLen = $this->sLen !== null ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { @@ -2644,8 +2642,8 @@ function _emsa_pss_verify($m, $em, $emBits) * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}. * * @access private - * @param String $m - * @return String + * @param string $m + * @return string */ function _rsassa_pss_sign($m) { @@ -2670,9 +2668,9 @@ function _rsassa_pss_sign($m) * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}. * * @access private - * @param String $m - * @param String $s - * @return String + * @param string $m + * @param string $s + * @return string */ function _rsassa_pss_verify($m, $s) { @@ -2710,9 +2708,9 @@ function _rsassa_pss_verify($m, $s) * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}. * * @access private - * @param String $m - * @param Integer $emLen - * @return String + * @param string $m + * @param int $emLen + * @return string */ function _emsa_pkcs1_v1_5_encode($m, $emLen) { @@ -2762,8 +2760,8 @@ function _emsa_pkcs1_v1_5_encode($m, $emLen) * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}. * * @access private - * @param String $m - * @return String + * @param string $m + * @return string */ function _rsassa_pkcs1_v1_5_sign($m) { @@ -2792,8 +2790,8 @@ function _rsassa_pkcs1_v1_5_sign($m) * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}. * * @access private - * @param String $m - * @return String + * @param string $m + * @return string */ function _rsassa_pkcs1_v1_5_verify($m, $s) { @@ -2836,7 +2834,7 @@ function _rsassa_pkcs1_v1_5_verify($m, $s) * Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1. * * @access public - * @param Integer $mode + * @param int $mode */ function setEncryptionMode($mode) { @@ -2849,7 +2847,7 @@ function setEncryptionMode($mode) * Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1 * * @access public - * @param Integer $mode + * @param int $mode */ function setSignatureMode($mode) { @@ -2860,7 +2858,7 @@ function setSignatureMode($mode) * Set public key comment. * * @access public - * @param String $comment + * @param string $comment */ function setComment($comment) { @@ -2871,7 +2869,7 @@ function setComment($comment) * Get public key comment. * * @access public - * @return String + * @return string */ function getComment() { @@ -2885,10 +2883,10 @@ function getComment() * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will * be concatenated together. * - * @see decrypt() + * @see self::decrypt() * @access public - * @param String $plaintext - * @return String + * @param string $plaintext + * @return string */ function encrypt($plaintext) { @@ -2931,10 +2929,10 @@ function encrypt($plaintext) /** * Decryption * - * @see encrypt() + * @see self::encrypt() * @access public - * @param String $plaintext - * @return String + * @param string $plaintext + * @return string */ function decrypt($ciphertext) { @@ -2973,10 +2971,10 @@ function decrypt($ciphertext) /** * Create a signature * - * @see verify() + * @see self::verify() * @access public - * @param String $message - * @return String + * @param string $message + * @return string */ function sign($message) { @@ -2996,11 +2994,11 @@ function sign($message) /** * Verifies a signature * - * @see sign() + * @see self::sign() * @access public - * @param String $message - * @param String $signature - * @return Boolean + * @param string $message + * @param string $signature + * @return bool */ function verify($message, $signature) { @@ -3021,8 +3019,8 @@ function verify($message, $signature) * Extract raw BER from Base64 encoding * * @access private - * @param String $str - * @return String + * @param string $str + * @return string */ function _extractBER($str) { @@ -3035,7 +3033,7 @@ function _extractBER($str) * subject=/O=organization/OU=org unit/CN=common name * issuer=/O=organization/CN=common name */ - $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1); + $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1); // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff $temp = preg_replace('#-+[^-]+-+#', '', $temp); // remove new lines diff --git a/phpseclib/phpseclib/phpseclib/Crypt/Random.php b/phpseclib/phpseclib/phpseclib/Crypt/Random.php index 9fb1d15bb..170d1c377 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/Random.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/Random.php @@ -24,14 +24,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\AES; -use phpseclib\Crypt\Base; -use phpseclib\Crypt\Blowfish; -use phpseclib\Crypt\DES; -use phpseclib\Crypt\RC4; -use phpseclib\Crypt\TripleDES; -use phpseclib\Crypt\Twofish; - /** * Pure-PHP Random Number Generator * @@ -48,15 +40,28 @@ class Random * microoptimizations because this function has the potential of being called a huge number of times. * eg. for RSA key generation. * - * @param Integer $length - * @return String + * @param int $length + * @return string */ - public static function string($length) + static function string($length) { + if (version_compare(PHP_VERSION, '7.0.0', '>=')) { + try { + return \random_bytes($length); + } catch (\Throwable $e) { + // If a sufficient source of randomness is unavailable, random_bytes() will throw an + // object that implements the Throwable interface (Exception, TypeError, Error). + // We don't actually need to do anything here. The string() method should just continue + // as normal. Note, however, that if we don't have a sufficient source of randomness for + // random_bytes(), most of the other calls here will fail too, so we'll end up using + // the PHP implementation. + } + } + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call. // ie. class_alias is a function that was introduced in PHP 5.3 - if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) { + if (extension_loaded('mcrypt') && function_exists('class_alias')) { return mcrypt_create_iv($length); } // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was, @@ -72,12 +77,12 @@ public static function string($length) // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80 // // we're calling it, all the same, in the off chance that the mcrypt extension is not available - if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) { + if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) { return openssl_random_pseudo_bytes($length); } } else { // method 1. the fastest - if (function_exists('openssl_random_pseudo_bytes')) { + if (extension_loaded('openssl')) { return openssl_random_pseudo_bytes($length); } // method 2 @@ -95,7 +100,7 @@ public static function string($length) // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir // restrictions or some such - if (function_exists('mcrypt_create_iv')) { + if (extension_loaded('mcrypt')) { return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); } } @@ -135,13 +140,13 @@ public static function string($length) session_start(); $v = $seed = $_SESSION['seed'] = pack('H*', sha1( - serialize($_SERVER) . - serialize($_POST) . - serialize($_GET) . - serialize($_COOKIE) . - serialize($GLOBALS) . - serialize($_SESSION) . - serialize($_OLD_SESSION) + (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') . + (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') . + (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') . + (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') . + phpseclib_safe_serialize($GLOBALS) . + phpseclib_safe_serialize($_SESSION) . + phpseclib_safe_serialize($_OLD_SESSION) )); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; @@ -228,3 +233,38 @@ public static function string($length) return substr($result, 0, $length); } } + +if (!function_exists('phpseclib_safe_serialize')) { + /** + * Safely serialize variables + * + * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier. + * PHP 5.3 will emit a warning. + * + * @param mixed $arr + * @access public + */ + function phpseclib_safe_serialize(&$arr) + { + if (is_object($arr)) { + return ''; + } + if (!is_array($arr)) { + return serialize($arr); + } + // prevent circular array recursion + if (isset($arr['__phpseclib_marker'])) { + return ''; + } + $safearr = array(); + $arr['__phpseclib_marker'] = true; + foreach (array_keys($arr) as $key) { + // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage + if ($key !== '__phpseclib_marker') { + $safearr[$key] = phpseclib_safe_serialize($arr[$key]); + } + } + unset($arr['__phpseclib_marker']); + return serialize($safearr); + } +} diff --git a/phpseclib/phpseclib/phpseclib/Crypt/Rijndael.php b/phpseclib/phpseclib/phpseclib/Crypt/Rijndael.php index 90c75d836..3648a1972 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/Rijndael.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/Rijndael.php @@ -7,11 +7,11 @@ * * PHP version 5 * - * If {@link \phpseclib\Crypt\Rijndael::setBlockLength() setBlockLength()} isn't called, it'll be assumed to be 128 bits. If - * {@link \phpseclib\Crypt\Rijndael::setKeyLength() setKeyLength()} isn't called, it'll be calculated from - * {@link \phpseclib\Crypt\Rijndael::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's + * If {@link self::setBlockLength() setBlockLength()} isn't called, it'll be assumed to be 128 bits. If + * {@link self::setKeyLength() setKeyLength()} isn't called, it'll be calculated from + * {@link self::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's * 136-bits it'll be null-padded to 192-bits and 192 bits will be the key length until - * {@link \phpseclib\Crypt\Rijndael::setKey() setKey()} is called, again, at which point, it'll be recalculated. + * {@link self::setKey() setKey()} is called, again, at which point, it'll be recalculated. * * Not all Rijndael implementations may support 160-bits or 224-bits as the block length / key length. mcrypt, for example, * does not. AES, itself, only supports block lengths of 128 and key lengths of 128, 192, and 256. @@ -54,8 +54,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; - /** * Pure-PHP implementation of Rijndael. * @@ -65,28 +63,18 @@ */ class Rijndael extends Base { - /** - * The default password key_size used by setPassword() - * - * @see \phpseclib\Crypt\Base::password_key_size - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer - * @access private - */ - var $password_key_size = 16; - /** * The mcrypt specific name of the cipher * - * Mcrypt is useable for 128/192/256-bit $block_size/$key_size. For 160/224 not. + * Mcrypt is useable for 128/192/256-bit $block_size/$key_length. For 160/224 not. * \phpseclib\Crypt\Rijndael determines automatically whether mcrypt is useable - * or not for the current $block_size/$key_size. + * or not for the current $block_size/$key_length. * In case of, $cipher_name_mcrypt will be set dynamically at run time accordingly. * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::engine - * @see isValidEngine() - * @var String + * @see self::isValidEngine() + * @var string * @access private */ var $cipher_name_mcrypt = 'rijndael-128'; @@ -96,25 +84,16 @@ class Rijndael extends Base * * @see \phpseclib\Crypt\Base::password_default_salt * @see \phpseclib\Crypt\Base::setPassword() - * @var String + * @var string * @access private */ var $password_default_salt = 'phpseclib'; - /** - * Has the key length explicitly been set or should it be derived from the key, itself? - * - * @see setKeyLength() - * @var Boolean - * @access private - */ - var $explicit_key_length = false; - /** * The Key Schedule * - * @see _setup() - * @var Array + * @see self::_setup() + * @var array * @access private */ var $w; @@ -122,8 +101,8 @@ class Rijndael extends Base /** * The Inverse Key Schedule * - * @see _setup() - * @var Array + * @see self::_setup() + * @var array * @access private */ var $dw; @@ -131,8 +110,8 @@ class Rijndael extends Base /** * The Block Length divided by 32 * - * @see setBlockLength() - * @var Integer + * @see self::setBlockLength() + * @var int * @access private * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4. Exists in conjunction with $block_size * because the encryption / decryption / key schedule creation requires this number and not $block_size. We could @@ -142,23 +121,23 @@ class Rijndael extends Base var $Nb = 4; /** - * The Key Length + * The Key Length (in bytes) * - * @see setKeyLength() - * @var Integer + * @see self::setKeyLength() + * @var int * @access private * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk - * because the encryption / decryption / key schedule creation requires this number and not $key_size. We could - * derive this from $key_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu + * because the encryption / decryption / key schedule creation requires this number and not $key_length. We could + * derive this from $key_length or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu * of that, we'll just precompute it once. */ - var $key_size = 16; + var $key_length = 16; /** * The Key Length divided by 32 * - * @see setKeyLength() - * @var Integer + * @see self::setKeyLength() + * @var int * @access private * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4 */ @@ -167,7 +146,7 @@ class Rijndael extends Base /** * The Number of Rounds * - * @var Integer + * @var int * @access private * @internal The max value is 14, the min value is 10. */ @@ -176,7 +155,7 @@ class Rijndael extends Base /** * Shift offsets * - * @var Array + * @var array * @access private */ var $c; @@ -184,77 +163,13 @@ class Rijndael extends Base /** * Holds the last used key- and block_size information * - * @var Array + * @var array * @access private */ var $kl; /** - * Default Constructor. - * - * Determines whether or not the mcrypt extension should be used. - * - * $mode could be: - * - * - \phpseclib\Crypt\Base::MODE_ECB - * - * - \phpseclib\Crypt\Base::MODE_CBC - * - * - \phpseclib\Crypt\Base::MODE_CTR - * - * - \phpseclib\Crypt\Base::MODE_CFB - * - * - \phpseclib\Crypt\Base::MODE_OFB - * - * If not explictly set, \phpseclib\Crypt\Base::MODE_CBC will be used. - * - * @see \phpseclib\Crypt\Base::Crypt_Base() - * @param optional Integer $mode - * @access public - - /** - * Sets the key. - * - * Keys can be of any length. Rijndael, itself, requires the use of a key that's between 128-bits and 256-bits long and - * whose length is a multiple of 32. If the key is less than 256-bits and the key length isn't set, we round the length - * up to the closest valid key length, padding $key with null bytes. If the key is more than 256-bits, we trim the - * excess bits. - * - * If the key is not explicitly set, it'll be assumed to be all null bytes. - * - * Note: 160/224-bit keys must explicitly set by setKeyLength(), otherwise they will be round/pad up to 192/256 bits. - * - * @see \phpseclib\Crypt\Base:setKey() - * @see setKeyLength() - * @access public - * @param String $key - */ - function setKey($key) - { - if (!$this->explicit_key_length) { - $length = strlen($key); - switch (true) { - case $length <= 16: - $this->key_size = 16; - break; - case $length <= 20: - $this->key_size = 20; - break; - case $length <= 24: - $this->key_size = 24; - break; - case $length <= 28: - $this->key_size = 28; - break; - default: - $this->key_size = 32; - } - } - parent::setKey($key); - } - - /** - * Sets the key length + * Sets the key length. * * Valid key lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. @@ -271,30 +186,28 @@ function setKey($key) * This results then in slower encryption. * * @access public - * @param Integer $length + * @param int $length */ function setKeyLength($length) { switch (true) { - case $length == 160: - $this->key_size = 20; - break; - case $length == 224: - $this->key_size = 28; - break; case $length <= 128: - $this->key_size = 16; + $this->key_length = 16; + break; + case $length <= 160: + $this->key_length = 20; break; case $length <= 192: - $this->key_size = 24; + $this->key_length = 24; + break; + case $length <= 224: + $this->key_length = 28; break; default: - $this->key_size = 32; + $this->key_length = 32; } - $this->explicit_key_length = true; - $this->changed = true; - $this->_setEngine(); + parent::setKeyLength($length); } /** @@ -304,7 +217,7 @@ function setKeyLength($length) * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. * * @access public - * @param Integer $length + * @param int $length */ function setBlockLength($length) { @@ -325,10 +238,10 @@ function setBlockLength($length) * * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine() * - * @see \phpseclib\Crypt\Base::Crypt_Base() - * @param Integer $engine + * @see \phpseclib\Crypt\Base::__construct() + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { @@ -337,12 +250,12 @@ function isValidEngine($engine) if ($this->block_size != 16) { return false; } - $this->cipher_name_openssl_ecb = 'aes-' . ($this->key_size << 3) . '-ecb'; - $this->cipher_name_openssl = 'aes-' . ($this->key_size << 3) . '-' . $this->_openssl_translate_mode(); + $this->cipher_name_openssl_ecb = 'aes-' . ($this->key_length << 3) . '-ecb'; + $this->cipher_name_openssl = 'aes-' . ($this->key_length << 3) . '-' . $this->_openssl_translate_mode(); break; case self::ENGINE_MCRYPT: $this->cipher_name_mcrypt = 'rijndael-' . ($this->block_size << 3); - if ($this->key_size % 8) { // is it a 160/224-bit key? + if ($this->key_length % 8) { // is it a 160/224-bit key? // mcrypt is not usable for them, only for 128/192/256-bit keys return false; } @@ -351,24 +264,12 @@ function isValidEngine($engine) return parent::isValidEngine($engine); } - /** - * Setup the \phpseclib\Crypt\Base::ENGINE_MCRYPT $engine - * - * @see \phpseclib\Crypt\Base::_setupMcrypt() - * @access private - */ - function _setupMcrypt() - { - $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, "\0"); - parent::_setupMcrypt(); - } - /** * Encrypts a block * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _encryptBlock($in) { @@ -468,8 +369,8 @@ function _encryptBlock($in) * Decrypts a block * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _decryptBlock($in) { @@ -573,15 +474,13 @@ function _setupKey() 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000 ); - $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, "\0"); - - if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->key_size === $this->kl['key_size'] && $this->block_size === $this->kl['block_size']) { + if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->key_length === $this->kl['key_length'] && $this->block_size === $this->kl['block_size']) { // already expanded return; } - $this->kl = array('key' => $this->key, 'key_size' => $this->key_size, 'block_size' => $this->block_size); + $this->kl = array('key' => $this->key, 'key_length' => $this->key_length, 'block_size' => $this->block_size); - $this->Nk = $this->key_size >> 2; + $this->Nk = $this->key_length >> 2; // see Rijndael-ammended.pdf#page=44 $this->Nr = max($this->Nk, $this->Nb) + 6; @@ -673,13 +572,13 @@ function _setupKey() * Performs S-Box substitutions * * @access private - * @param Integer $word + * @param int $word */ function _subWord($word) { static $sbox; if (empty($sbox)) { - list(,,,, $sbox) = $this->_getTables(); + list(, , , , $sbox) = $this->_getTables(); } return $sbox[$word & 0x000000FF] | @@ -691,11 +590,11 @@ function _subWord($word) /** * Provides the mixColumns and sboxes tables * - * @see Crypt_Rijndael:_encryptBlock() - * @see Crypt_Rijndael:_setupInlineCrypt() - * @see Crypt_Rijndael:_subWord() + * @see self::_encryptBlock() + * @see self::_setupInlineCrypt() + * @see self::_subWord() * @access private - * @return Array &$tables + * @return array &$tables */ function &_getTables() { @@ -780,11 +679,11 @@ function &_getTables() /** * Provides the inverse mixColumns and inverse sboxes tables * - * @see Crypt_Rijndael:_decryptBlock() - * @see Crypt_Rijndael:_setupInlineCrypt() - * @see Crypt_Rijndael:_setupKey() + * @see self::_decryptBlock() + * @see self::_setupInlineCrypt() + * @see self::_setupKey() * @access private - * @return Array &$tables + * @return array &$tables */ function &_getInvTables() { @@ -878,7 +777,7 @@ function _setupInlineCrypt() // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. // (Currently, for Crypt_Rijndael/AES, one generated $lambda_function cost on php5.5@32bit ~80kb unfreeable mem and ~130kb on php5.5@64bit) // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one. - $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); // Generation of a uniqe hash for our generated code $code_hash = "Crypt_Rijndael, {$this->mode}, {$this->Nr}, {$this->Nb}"; diff --git a/phpseclib/phpseclib/phpseclib/Crypt/TripleDES.php b/phpseclib/phpseclib/phpseclib/Crypt/TripleDES.php index d4caa3989..a2c41668a 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/TripleDES.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/TripleDES.php @@ -36,9 +36,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; -use phpseclib\Crypt\DES; - /** * Pure-PHP implementation of Triple DES. * @@ -48,7 +45,6 @@ */ class TripleDES extends DES { - /** * Encrypt / decrypt using inner chaining * @@ -60,26 +56,24 @@ class TripleDES extends DES * Encrypt / decrypt using outer chaining * * Outer chaining is used by SSH-2 and when the mode is set to \phpseclib\Crypt\Base::MODE_CBC. - */ + */ const MODE_CBC3 = Base::MODE_CBC; /** - * The default password key_size used by setPassword() + * Key Length (in bytes) * - * @see \phpseclib\Crypt\DES::password_key_size - * @see \phpseclib\Crypt\Base::password_key_size - * @see \phpseclib\Crypt\Base::setPassword() - * @var Integer + * @see \phpseclib\Crypt\TripleDES::setKeyLength() + * @var int * @access private */ - var $password_key_size = 24; + var $key_length = 24; /** * The default salt used by setPassword() * * @see \phpseclib\Crypt\Base::password_default_salt * @see \phpseclib\Crypt\Base::setPassword() - * @var String + * @var string * @access private */ var $password_default_salt = 'phpseclib'; @@ -89,7 +83,7 @@ class TripleDES extends DES * * @see \phpseclib\Crypt\DES::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt - * @var String + * @var string * @access private */ var $cipher_name_mcrypt = 'tripledes'; @@ -98,7 +92,7 @@ class TripleDES extends DES * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len - * @var Integer + * @var int * @access private */ var $cfb_init_len = 750; @@ -106,17 +100,17 @@ class TripleDES extends DES /** * max possible size of $key * - * @see \phpseclib\Crypt\TripleDES::setKey() + * @see self::setKey() * @see \phpseclib\Crypt\DES::setKey() - * @var String + * @var string * @access private */ - var $key_size_max = 24; + var $key_length_max = 24; /** * Internal flag whether using self::MODE_3CBC or not * - * @var Boolean + * @var bool * @access private */ var $mode_3cbc; @@ -126,7 +120,7 @@ class TripleDES extends DES * * Used only if $mode_3cbc === true * - * @var Array + * @var array * @access private */ var $des; @@ -154,7 +148,7 @@ class TripleDES extends DES * * @see \phpseclib\Crypt\DES::__construct() * @see \phpseclib\Crypt\Base::__construct() - * @param optional Integer $mode + * @param int $mode * @access public */ function __construct($mode = Base::MODE_CBC) @@ -189,10 +183,10 @@ function __construct($mode = Base::MODE_CBC) * * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine() * - * @see \phpseclib\Crypt\Base::Crypt_Base() - * @param Integer $engine + * @see \phpseclib\Crypt\Base::__construct() + * @param int $engine * @access public - * @return Boolean + * @return bool */ function isValidEngine($engine) { @@ -213,7 +207,7 @@ function isValidEngine($engine) * * @see \phpseclib\Crypt\Base::setIV() * @access public - * @param String $iv + * @param string $iv */ function setIV($iv) { @@ -225,6 +219,32 @@ function setIV($iv) } } + /** + * Sets the key length. + * + * Valid key lengths are 64, 128 and 192 + * + * @see \phpseclib\Crypt\Base:setKeyLength() + * @access public + * @param int $length + */ + function setKeyLength($length) + { + $length >>= 3; + switch (true) { + case $length <= 8: + $this->key_length = 8; + break; + case $length <= 16: + $this->key_length = 16; + break; + default: + $this->key_length = 24; + } + + parent::setKeyLength($length); + } + /** * Sets the key. * @@ -238,11 +258,11 @@ function setIV($iv) * @access public * @see \phpseclib\Crypt\DES::setKey() * @see \phpseclib\Crypt\Base::setKey() - * @param String $key + * @param string $key */ function setKey($key) { - $length = strlen($key); + $length = $this->explicit_key_length ? $this->key_length : strlen($key); if ($length > 8) { $key = str_pad(substr($key, 0, 24), 24, chr(0)); // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this: @@ -269,8 +289,8 @@ function setKey($key) * * @see \phpseclib\Crypt\Base::encrypt() * @access public - * @param String $plaintext - * @return String $cipertext + * @param string $plaintext + * @return string $cipertext */ function encrypt($plaintext) { @@ -296,8 +316,8 @@ function encrypt($plaintext) * * @see \phpseclib\Crypt\Base::decrypt() * @access public - * @param String $ciphertext - * @return String $plaintext + * @param string $ciphertext + * @return string $plaintext */ function decrypt($ciphertext) { @@ -351,7 +371,7 @@ function decrypt($ciphertext) * however, they are also less intuitive and more likely to cause you problems. * * @see \phpseclib\Crypt\Base::enableContinuousBuffer() - * @see \phpseclib\Crypt\TripleDES::disableContinuousBuffer() + * @see self::disableContinuousBuffer() * @access public */ function enableContinuousBuffer() @@ -370,7 +390,7 @@ function enableContinuousBuffer() * The default behavior. * * @see \phpseclib\Crypt\Base::disableContinuousBuffer() - * @see \phpseclib\Crypt\TripleDES::enableContinuousBuffer() + * @see self::enableContinuousBuffer() * @access public */ function disableContinuousBuffer() @@ -421,11 +441,11 @@ function _setupKey() /** * Sets the internal crypt engine * - * @see \phpseclib\Crypt\Base::Crypt_Base() + * @see \phpseclib\Crypt\Base::__construct() * @see \phpseclib\Crypt\Base::setPreferredEngine() - * @param Integer $engine + * @param int $engine * @access public - * @return Integer + * @return int */ function setPreferredEngine($engine) { diff --git a/phpseclib/phpseclib/phpseclib/Crypt/Twofish.php b/phpseclib/phpseclib/phpseclib/Crypt/Twofish.php index 9c32de679..3dd4ea1d3 100644 --- a/phpseclib/phpseclib/phpseclib/Crypt/Twofish.php +++ b/phpseclib/phpseclib/phpseclib/Crypt/Twofish.php @@ -37,8 +37,6 @@ namespace phpseclib\Crypt; -use phpseclib\Crypt\Base; - /** * Pure-PHP implementation of Twofish. * @@ -53,7 +51,7 @@ class Twofish extends Base * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt - * @var String + * @var string * @access private */ var $cipher_name_mcrypt = 'twofish'; @@ -62,7 +60,7 @@ class Twofish extends Base * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len - * @var Integer + * @var int * @access private */ var $cfb_init_len = 800; @@ -70,10 +68,10 @@ class Twofish extends Base /** * Q-Table * - * @var Array + * @var array * @access private */ - var $q0 = array ( + var $q0 = array( 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, @@ -111,10 +109,10 @@ class Twofish extends Base /** * Q-Table * - * @var Array + * @var array * @access private */ - var $q1 = array ( + var $q1 = array( 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, @@ -152,10 +150,10 @@ class Twofish extends Base /** * M-Table * - * @var Array + * @var array * @access private */ - var $m0 = array ( + var $m0 = array( 0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8, 0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B, 0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1, @@ -193,10 +191,10 @@ class Twofish extends Base /** * M-Table * - * @var Array + * @var array * @access private */ - var $m1 = array ( + var $m1 = array( 0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4, 0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A, 0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141, @@ -234,10 +232,10 @@ class Twofish extends Base /** * M-Table * - * @var Array + * @var array * @access private */ - var $m2 = array ( + var $m2 = array( 0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA, 0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7, 0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783, @@ -275,10 +273,10 @@ class Twofish extends Base /** * M-Table * - * @var Array + * @var array * @access private */ - var $m3 = array ( + var $m3 = array( 0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF, 0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836, 0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77, @@ -316,7 +314,7 @@ class Twofish extends Base /** * The Key Schedule Array * - * @var Array + * @var array * @access private */ var $K = array(); @@ -324,7 +322,7 @@ class Twofish extends Base /** * The Key depended S-Table 0 * - * @var Array + * @var array * @access private */ var $S0 = array(); @@ -332,7 +330,7 @@ class Twofish extends Base /** * The Key depended S-Table 1 * - * @var Array + * @var array * @access private */ var $S1 = array(); @@ -340,7 +338,7 @@ class Twofish extends Base /** * The Key depended S-Table 2 * - * @var Array + * @var array * @access private */ var $S2 = array(); @@ -348,7 +346,7 @@ class Twofish extends Base /** * The Key depended S-Table 3 * - * @var Array + * @var array * @access private */ var $S3 = array(); @@ -356,41 +354,42 @@ class Twofish extends Base /** * Holds the last used key * - * @var Array + * @var array * @access private */ var $kl; /** - * Sets the key. + * The Key Length (in bytes) * - * Keys can be of any length. Twofish, itself, requires the use of a key that's 128, 192 or 256-bits long. - * If the key is less than 256-bits we round the length up to the closest valid key length, - * padding $key with null bytes. If the key is more than 256-bits, we trim the excess bits. + * @see Crypt_Twofish::setKeyLength() + * @var int + * @access private + */ + var $key_length = 16; + + /** + * Sets the key length. * - * If the key is not explicitly set, it'll be assumed a 128 bits key to be all null bytes. + * Valid key lengths are 128, 192 or 256 bits * * @access public - * @see \phpseclib\Crypt\Base::setKey() - * @param String $key + * @param int $length */ - function setKey($key) + function setKeyLength($length) { - $keylength = strlen($key); switch (true) { - case $keylength <= 16: - $key = str_pad($key, 16, "\0"); - break; - case $keylength <= 24: - $key = str_pad($key, 24, "\0"); + case $length <= 128: + $this->key_length = 16; break; - case $keylength < 32: - $key = str_pad($key, 32, "\0"); + case $length <= 192: + $this->key_length = 24; break; - case $keylength > 32: - $key = substr($key, 0, 32); + default: + $this->key_length = 32; } - parent::setKey($key); + + parent::setKeyLength($length); } /** @@ -421,9 +420,9 @@ function _setupKey() switch (strlen($this->key)) { case 16: - list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]); - list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]); - for ($i = 0, $j = 1; $i < 40; $i+= 2,$j+= 2) { + list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]); + list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]); + for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^ $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^ $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^ @@ -444,9 +443,9 @@ function _setupKey() } break; case 24: - list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]); - list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]); - list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]); + list($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]); + list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]); + list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]); for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ @@ -468,10 +467,10 @@ function _setupKey() } break; default: // 32 - list ($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]); - list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]); - list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]); - list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]); + list($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]); + list($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]); + list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]); + list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]); for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ @@ -504,9 +503,9 @@ function _setupKey() * _mdsrem function using by the twofish cipher algorithm * * @access private - * @param String $A - * @param String $B - * @return Array + * @param string $A + * @param string $B + * @return array */ function _mdsrem($A, $B) { @@ -552,8 +551,8 @@ function _mdsrem($A, $B) * Encrypts a block * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _encryptBlock($in) { @@ -608,8 +607,8 @@ function _encryptBlock($in) * Decrypts a block * * @access private - * @param String $in - * @return String + * @param string $in + * @return string */ function _decryptBlock($in) { @@ -672,9 +671,9 @@ function _setupInlineCrypt() // Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one. // (Currently, for Crypt_Twofish, one generated $lambda_function cost on php5.5@32bit ~140kb unfreeable mem and ~240kb on php5.5@64bit) - $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); - // Generation of a uniqe hash for our generated code + // Generation of a unique hash for our generated code $code_hash = "Crypt_Twofish, {$this->mode}"; if ($gen_hi_opt_code) { $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); diff --git a/phpseclib/phpseclib/phpseclib/File/ANSI.php b/phpseclib/phpseclib/phpseclib/File/ANSI.php index 1daf787a4..1f3eecb30 100644 --- a/phpseclib/phpseclib/phpseclib/File/ANSI.php +++ b/phpseclib/phpseclib/phpseclib/File/ANSI.php @@ -32,7 +32,7 @@ class ANSI /** * Max Width * - * @var Integer + * @var int * @access private */ var $max_x; @@ -40,7 +40,7 @@ class ANSI /** * Max Height * - * @var Integer + * @var int * @access private */ var $max_y; @@ -48,7 +48,7 @@ class ANSI /** * Max History * - * @var Integer + * @var int * @access private */ var $max_history; @@ -56,7 +56,7 @@ class ANSI /** * History * - * @var Array + * @var array * @access private */ var $history; @@ -64,7 +64,7 @@ class ANSI /** * History Attributes * - * @var Array + * @var array * @access private */ var $history_attrs; @@ -72,7 +72,7 @@ class ANSI /** * Current Column * - * @var Integer + * @var int * @access private */ var $x; @@ -80,7 +80,7 @@ class ANSI /** * Current Row * - * @var Integer + * @var int * @access private */ var $y; @@ -88,7 +88,7 @@ class ANSI /** * Old Column * - * @var Integer + * @var int * @access private */ var $old_x; @@ -96,7 +96,7 @@ class ANSI /** * Old Row * - * @var Integer + * @var int * @access private */ var $old_y; @@ -104,7 +104,7 @@ class ANSI /** * An empty attribute cell * - * @var Object + * @var object * @access private */ var $base_attr_cell; @@ -112,7 +112,7 @@ class ANSI /** * The current attribute cell * - * @var Object + * @var object * @access private */ var $attr_cell; @@ -120,7 +120,7 @@ class ANSI /** * An empty attribute row * - * @var Array + * @var array * @access private */ var $attr_row; @@ -128,7 +128,7 @@ class ANSI /** * The current screen text * - * @var Array + * @var array * @access private */ var $screen; @@ -136,7 +136,7 @@ class ANSI /** * The current screen attributes * - * @var Array + * @var array * @access private */ var $attrs; @@ -144,7 +144,7 @@ class ANSI /** * Current ANSI code * - * @var String + * @var string * @access private */ var $ansi; @@ -152,7 +152,7 @@ class ANSI /** * Tokenization * - * @var Array + * @var array * @access private */ var $tokenization; @@ -184,8 +184,8 @@ function __construct() * * Resets the screen as well * - * @param Integer $x - * @param Integer $y + * @param int $x + * @param int $y * @access public */ function setDimensions($x, $y) @@ -203,8 +203,8 @@ function setDimensions($x, $y) /** * Set the number of lines that should be logged past the terminal height * - * @param Integer $x - * @param Integer $y + * @param int $x + * @param int $y * @access public */ function setHistory($history) @@ -215,7 +215,7 @@ function setHistory($history) /** * Load a string * - * @param String $source + * @param string $source * @access public */ function loadString($source) @@ -227,7 +227,7 @@ function loadString($source) /** * Appdend a string * - * @param String $source + * @param string $source * @access public */ function appendString($source) @@ -458,7 +458,7 @@ function _newLine() * Returns the current coordinate without preformating * * @access private - * @return String + * @return string */ function _processCoordinate($last_attr, $cur_attr, $char) { @@ -515,7 +515,7 @@ function _processCoordinate($last_attr, $cur_attr, $char) * Returns the current screen without preformating * * @access private - * @return String + * @return string */ function _getScreen() { @@ -539,7 +539,7 @@ function _getScreen() * Returns the current screen * * @access public - * @return String + * @return string */ function getScreen() { @@ -550,7 +550,7 @@ function getScreen() * Returns the current screen and the x previous lines * * @access public - * @return String + * @return string */ function getHistory() { diff --git a/phpseclib/phpseclib/phpseclib/File/ASN1.php b/phpseclib/phpseclib/phpseclib/File/ASN1.php index 717f4f8de..c11dd7434 100644 --- a/phpseclib/phpseclib/phpseclib/File/ASN1.php +++ b/phpseclib/phpseclib/phpseclib/File/ASN1.php @@ -104,7 +104,7 @@ class ASN1 /** * ASN.1 object identifier * - * @var Array + * @var array * @access private * @link http://en.wikipedia.org/wiki/Object_identifier */ @@ -113,7 +113,7 @@ class ASN1 /** * Default date format * - * @var String + * @var string * @access private * @link http://php.net/class.datetime */ @@ -122,10 +122,10 @@ class ASN1 /** * Default date format * - * @var Array + * @var array * @access private - * @see \phpseclib\File\ASN1::setTimeFormat() - * @see \phpseclib\File\ASN1::asn1map() + * @see self::setTimeFormat() + * @see self::asn1map() * @link http://php.net/class.datetime */ var $encoded; @@ -135,9 +135,9 @@ class ASN1 * * If the mapping type is self::TYPE_ANY what do we actually encode it as? * - * @var Array + * @var array * @access private - * @see \phpseclib\File\ASN1::_encode_der() + * @see self::_encode_der() */ var $filters; @@ -148,7 +148,7 @@ class ASN1 * Unambiguous types get the direct mapping (int/real/bool). * Others are mapped as a choice, with an extra indexing level. * - * @var Array + * @var array * @access public */ var $ANYmap = array( @@ -182,7 +182,7 @@ class ASN1 * Non-convertable types are absent from this table. * size == 0 indicates variable length encoding. * - * @var Array + * @var array * @access public */ var $stringTypeSize = array( @@ -200,8 +200,8 @@ class ASN1 * * Serves a similar purpose to openssl's asn1parse * - * @param String $encoded - * @return Array + * @param string $encoded + * @return array * @access public */ function decodeBER($encoded) @@ -222,16 +222,17 @@ function decodeBER($encoded) * $encoded is passed by reference for the recursive calls done for self::TYPE_BIT_STRING and * self::TYPE_OCTET_STRING. In those cases, the indefinite length is used. * - * @param String $encoded - * @param Integer $start - * @return Array + * @param string $encoded + * @param int $start + * @param int $encoded_pos + * @return array * @access private */ - function _decode_ber($encoded, $start = 0) + function _decode_ber($encoded, $start = 0, $encoded_pos = 0) { $current = array('start' => $start); - $type = ord($this->_string_shift($encoded)); + $type = ord($encoded[$encoded_pos++]); $start++; $constructed = ($type >> 5) & 1; @@ -243,23 +244,24 @@ function _decode_ber($encoded, $start = 0) do { $loop = ord($encoded[0]) >> 7; $tag <<= 7; - $tag |= ord($this->_string_shift($encoded)) & 0x7F; + $tag |= ord($encoded[$encoded_pos++]) & 0x7F; $start++; } while ($loop); } // Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13 - $length = ord($this->_string_shift($encoded)); + $length = ord($encoded[$encoded_pos++]); $start++; if ($length == 0x80) { // indefinite length // "[A sender shall] use the indefinite form (see 8.1.3.6) if the encoding is constructed and is not all // immediately available." -- paragraph 8.1.3.2.c - $length = strlen($encoded); + $length = strlen($encoded) - $encoded_pos; } elseif ($length & 0x80) { // definite length, long form // technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only // support it up to four. $length&= 0x7F; - $temp = $this->_string_shift($encoded, $length); + $temp = substr($encoded, $encoded_pos, $length); + $encoded_pos += $length; // tags of indefinte length don't really have a header length; this length includes the tag $current+= array('headerlength' => $length + 2); $start+= $length; @@ -268,11 +270,12 @@ function _decode_ber($encoded, $start = 0) $current+= array('headerlength' => 2); } - if ($length > strlen($encoded)) { + if ($length > (strlen($encoded) - $encoded_pos)) { return false; } - $content = $this->_string_shift($encoded, $length); + $content = substr($encoded, $encoded_pos, $length); + $content_pos = 0; // at this point $length can be overwritten. it's only accurate for definite length things as is @@ -305,7 +308,7 @@ function _decode_ber($encoded, $start = 0) $temp = $this->_decode_ber($content, $start); $length = $temp['length']; // end-of-content octets - see paragraph 8.1.5 - if (substr($content, $length, 2) == "\0\0") { + if (substr($content, $content_pos + $length, 2) == "\0\0") { $length+= 2; $start+= $length; $newcontent[] = $temp; @@ -314,7 +317,7 @@ function _decode_ber($encoded, $start = 0) $start+= $length; $remainingLength-= $length; $newcontent[] = $temp; - $this->_string_shift($content, $length); + $content_pos += $length; } return array( @@ -338,11 +341,11 @@ function _decode_ber($encoded, $start = 0) //if (strlen($content) != 1) { // return false; //} - $current['content'] = (bool) ord($content[0]); + $current['content'] = (bool) ord($content[$content_pos]); break; case self::TYPE_INTEGER: case self::TYPE_ENUMERATED: - $current['content'] = new BigInteger($content, -256); + $current['content'] = new BigInteger(substr($content, $content_pos), -256); break; case self::TYPE_REAL: // not currently supported return false; @@ -351,10 +354,10 @@ function _decode_ber($encoded, $start = 0) // the number of unused bits in the final subsequent octet. The number shall be in the range zero to // seven. if (!$constructed) { - $current['content'] = $content; + $current['content'] = substr($content, $content_pos); } else { - $temp = $this->_decode_ber($content, $start); - $length-= strlen($content); + $temp = $this->_decode_ber($content, $start, $content_pos); + $length-= (strlen($content) - $content_pos); $last = count($temp) - 1; for ($i = 0; $i < $last; $i++) { // all subtags should be bit strings @@ -372,13 +375,13 @@ function _decode_ber($encoded, $start = 0) break; case self::TYPE_OCTET_STRING: if (!$constructed) { - $current['content'] = $content; + $current['content'] = substr($content, $content_pos); } else { $current['content'] = ''; $length = 0; - while (substr($content, 0, 2) != "\0\0") { - $temp = $this->_decode_ber($content, $length + $start); - $this->_string_shift($content, $temp['length']); + while (substr($content, $content_pos, 2) != "\0\0") { + $temp = $this->_decode_ber($content, $length + $start, $content_pos); + $content_pos += $temp['length']; // all subtags should be octet strings //if ($temp['type'] != self::TYPE_OCTET_STRING) { // return false; @@ -386,7 +389,7 @@ function _decode_ber($encoded, $start = 0) $current['content'].= $temp['content']; $length+= $temp['length']; } - if (substr($content, 0, 2) == "\0\0") { + if (substr($content, $content_pos, 2) == "\0\0") { $length+= 2; // +2 for the EOC } } @@ -401,26 +404,28 @@ function _decode_ber($encoded, $start = 0) case self::TYPE_SET: $offset = 0; $current['content'] = array(); - while (strlen($content)) { + $content_len = strlen($content); + while ($content_pos < $content_len) { // if indefinite length construction was used and we have an end-of-content string next // see paragraphs 8.1.1.3, 8.1.3.2, 8.1.3.6, 8.1.5, and (for an example) 8.6.4.2 - if (!isset($current['headerlength']) && substr($content, 0, 2) == "\0\0") { + if (!isset($current['headerlength']) && substr($content, $content_pos, 2) == "\0\0") { $length = $offset + 2; // +2 for the EOC break 2; } - $temp = $this->_decode_ber($content, $start + $offset); - $this->_string_shift($content, $temp['length']); + $temp = $this->_decode_ber($content, $start + $offset, $content_pos); + $content_pos += $temp['length']; $current['content'][] = $temp; $offset+= $temp['length']; } break; case self::TYPE_OBJECT_IDENTIFIER: - $temp = ord($this->_string_shift($content)); + $temp = ord($content[$content_pos++]); $current['content'] = sprintf('%d.%d', floor($temp / 40), $temp % 40); $valuen = 0; // process septets - while (strlen($content)) { - $temp = ord($this->_string_shift($content)); + $content_len = strlen($content); + while ($content_pos < $content_len) { + $temp = ord($content[$content_pos++]); $valuen <<= 7; $valuen |= $temp & 0x7F; if (~$temp & 0x80) { @@ -461,11 +466,11 @@ function _decode_ber($encoded, $start = 0) case self::TYPE_UTF8_STRING: // ???? case self::TYPE_BMP_STRING: - $current['content'] = $content; + $current['content'] = substr($content, $content_pos); break; case self::TYPE_UTC_TIME: case self::TYPE_GENERALIZED_TIME: - $current['content'] = $this->_decodeTime($content, $tag); + $current['content'] = $this->_decodeTime(substr($content, $content_pos), $tag); default: } @@ -482,10 +487,10 @@ function _decode_ber($encoded, $start = 0) * * "Special" mappings may be applied on a per tag-name basis via $special. * - * @param Array $decoded - * @param Array $mapping - * @param Array $special - * @return Array + * @param array $decoded + * @param array $mapping + * @param array $special + * @return array * @access public */ function asn1map($decoded, $mapping, $special = array()) @@ -497,7 +502,7 @@ function asn1map($decoded, $mapping, $special = array()) switch (true) { case $mapping['type'] == self::TYPE_ANY: $intype = $decoded['type']; - if (isset($decoded['constant']) || !isset($this->ANYmap[$intype]) || ($this->encoded[$decoded['start']] & 0x20)) { + if (isset($decoded['constant']) || !isset($this->ANYmap[$intype]) || (ord($this->encoded[$decoded['start']]) & 0x20)) { return new Element(substr($this->encoded, $decoded['start'], $decoded['length'])); } $inmap = $this->ANYmap[$intype]; @@ -616,7 +621,7 @@ function asn1map($decoded, $mapping, $special = array()) } // Fail mapping if all input items have not been consumed. - return $i < $n? null: $map; + return $i < $n ? null: $map; // the main diff between sets and sequences is the encapsulation of the foreach in another for loop case self::TYPE_SET: @@ -774,10 +779,10 @@ function asn1map($decoded, $mapping, $special = array()) * * "Special" mappings can be applied via $special. * - * @param String $source - * @param String $mapping - * @param Integer $idx - * @return String + * @param string $source + * @param string $mapping + * @param int $idx + * @return string * @access public */ function encodeDER($source, $mapping, $special = array()) @@ -789,10 +794,10 @@ function encodeDER($source, $mapping, $special = array()) /** * ASN.1 Encode (Helper function) * - * @param String $source - * @param String $mapping - * @param Integer $idx - * @return String + * @param string $source + * @param string $mapping + * @param int $idx + * @return string * @access private */ function _encode_der($source, $mapping, $idx = null, $special = array()) @@ -819,10 +824,10 @@ function _encode_der($source, $mapping, $idx = null, $special = array()) case self::TYPE_SET: // Children order is not important, thus process in sequence. case self::TYPE_SEQUENCE: $tag|= 0x20; // set the constructed bit - $value = ''; // ignore the min and max if (isset($mapping['min']) && isset($mapping['max'])) { + $value = array(); $child = $mapping['children']; foreach ($source as $content) { @@ -830,11 +835,21 @@ function _encode_der($source, $mapping, $idx = null, $special = array()) if ($temp === false) { return false; } - $value.= $temp; + $value[]= $temp; } + /* "The encodings of the component values of a set-of value shall appear in ascending order, the encodings being compared + as octet strings with the shorter components being padded at their trailing end with 0-octets. + NOTE - The padding octets are for comparison purposes only and do not appear in the encodings." + + -- sec 11.6 of http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ + if ($mapping['type'] == self::TYPE_SET) { + sort($value); + } + $value = implode($value, ''); break; } + $value = ''; foreach ($mapping['children'] as $key => $child) { if (!array_key_exists($key, $source)) { if (!isset($child['optional'])) { @@ -1089,8 +1104,8 @@ function _encode_der($source, $mapping, $idx = null, $special = array()) * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private - * @param Integer $length - * @return String + * @param int $length + * @return string */ function _encodeLength($length) { @@ -1108,9 +1123,9 @@ function _encodeLength($length) * Called by _decode_ber() and in the case of implicit tags asn1map(). * * @access private - * @param String $content - * @param Integer $tag - * @return String + * @param string $content + * @param int $tag + * @return string */ function _decodeTime($content, $tag) { @@ -1157,7 +1172,7 @@ function _decodeTime($content, $tag) * Sets the time / date format for asn1map(). * * @access public - * @param String $format + * @param string $format */ function setTimeFormat($format) { @@ -1170,7 +1185,7 @@ function setTimeFormat($format) * Load the relevant OIDs for a particular ASN.1 semantic mapping. * * @access public - * @param Array $oids + * @param array $oids */ function loadOIDs($oids) { @@ -1183,7 +1198,7 @@ function loadOIDs($oids) * See \phpseclib\File\X509, etc, for an example. * * @access public - * @param Array $filters + * @param array $filters */ function loadFilters($filters) { @@ -1195,9 +1210,9 @@ function loadFilters($filters) * * Inspired by array_shift * - * @param String $string - * @param optional Integer $index - * @return String + * @param string $string + * @param int $index + * @return string * @access private */ function _string_shift(&$string, $index = 1) @@ -1213,10 +1228,10 @@ function _string_shift(&$string, $index = 1) * This is a lazy conversion, dealing only with character size. * No real conversion table is used. * - * @param String $in - * @param optional Integer $from - * @param optional Integer $to - * @return String + * @param string $in + * @param int $from + * @param int $to + * @return string * @access public */ function convert($in, $from = self::TYPE_UTF8_STRING, $to = self::TYPE_UTF8_STRING) diff --git a/phpseclib/phpseclib/phpseclib/File/ASN1/Element.php b/phpseclib/phpseclib/phpseclib/File/ASN1/Element.php index d0da53bdd..68246e2b5 100644 --- a/phpseclib/phpseclib/phpseclib/File/ASN1/Element.php +++ b/phpseclib/phpseclib/phpseclib/File/ASN1/Element.php @@ -28,7 +28,7 @@ class Element /** * Raw element value * - * @var String + * @var string * @access private */ var $element; @@ -36,7 +36,7 @@ class Element /** * Constructor * - * @param String $encoded + * @param string $encoded * @return \phpseclib\File\ASN1\Element * @access public */ diff --git a/phpseclib/phpseclib/phpseclib/File/X509.php b/phpseclib/phpseclib/phpseclib/File/X509.php index cfdfbe2ec..863d9e991 100644 --- a/phpseclib/phpseclib/phpseclib/File/X509.php +++ b/phpseclib/phpseclib/phpseclib/File/X509.php @@ -27,9 +27,8 @@ namespace phpseclib\File; use phpseclib\Crypt\Hash; -use phpseclib\Crypt\RSA; use phpseclib\Crypt\Random; -use phpseclib\File\ASN1; +use phpseclib\Crypt\RSA; use phpseclib\File\ASN1\Element; use phpseclib\Math\BigInteger; @@ -57,27 +56,27 @@ class X509 */ /** * Return internal array representation - */ + */ const DN_ARRAY = 0; /** * Return string - */ + */ const DN_STRING = 1; /** * Return ASN.1 name string - */ + */ const DN_ASN1 = 2; /** * Return OpenSSL compatible array - */ + */ const DN_OPENSSL = 3; /** * Return canonical ASN.1 RDNs string - */ + */ const DN_CANON = 4; /** * Return name hash for file indexing - */ + */ const DN_HASH = 5; /**#@-*/ @@ -91,24 +90,30 @@ class X509 * Save as PEM * * ie. a base64-encoded PEM with a header and a footer - */ + */ const FORMAT_PEM = 0; /** * Save as DER - */ + */ const FORMAT_DER = 1; /** * Save as a SPKAC * * Only works on CSRs. Not currently supported. - */ + */ const FORMAT_SPKAC = 2; + /** + * Auto-detect the format + * + * Used only by the load*() functions + */ + const FORMAT_AUTO_DETECT = 3; /**#@-*/ /** * Attribute value disposition. * If disposition is >= 0, this is the index of the target value. - */ + */ const ATTR_ALL = -1; // All attribute values (array). const ATTR_APPEND = -2; // Add a value. const ATTR_REPLACE = -3; // Clear first, then add a value. @@ -116,7 +121,7 @@ class X509 /** * ASN.1 syntax for X.509 certificates * - * @var Array + * @var array * @access private */ var $Certificate; @@ -139,6 +144,7 @@ class X509 var $CertificatePolicies; var $AuthorityInfoAccessSyntax; var $SubjectAltName; + var $SubjectDirectoryAttributes; var $PrivateKeyUsagePeriod; var $IssuerAltName; var $PolicyMappings; @@ -162,10 +168,18 @@ class X509 var $SignedPublicKeyAndChallenge; /**#@-*/ + /**#@+ + * ASN.1 syntax for various DN attributes + * + * @access private + */ + var $PostalAddress; + /**#@-*/ + /** * ASN.1 syntax for Certificate Signing Requests (RFC2986) * - * @var Array + * @var array * @access private */ var $CertificationRequest; @@ -173,7 +187,7 @@ class X509 /** * ASN.1 syntax for Certificate Revocation Lists (RFC5280) * - * @var Array + * @var array * @access private */ var $CertificateList; @@ -181,7 +195,7 @@ class X509 /** * Distinguished Name * - * @var Array + * @var array * @access private */ var $dn; @@ -189,7 +203,7 @@ class X509 /** * Public key * - * @var String + * @var string * @access private */ var $publicKey; @@ -197,7 +211,7 @@ class X509 /** * Private key * - * @var String + * @var string * @access private */ var $privateKey; @@ -205,7 +219,7 @@ class X509 /** * Object identifiers for X.509 certificates * - * @var Array + * @var array * @access private * @link http://en.wikipedia.org/wiki/Object_identifier */ @@ -214,7 +228,7 @@ class X509 /** * The certificate authorities * - * @var Array + * @var array * @access private */ var $CAs; @@ -222,7 +236,7 @@ class X509 /** * The currently loaded certificate * - * @var Array + * @var array * @access private */ var $currentCert; @@ -230,10 +244,10 @@ class X509 /** * The signature subject * - * There's no guarantee \phpseclib\File\X509 is going to reencode an X.509 cert in the same way it was originally + * There's no guarantee \phpseclib\File\X509 is going to re-encode an X.509 cert in the same way it was originally * encoded so we take save the portion of the original cert that the signature would have made for. * - * @var String + * @var string * @access private */ var $signatureSubject; @@ -241,7 +255,7 @@ class X509 /** * Certificate Start Date * - * @var String + * @var string * @access private */ var $startDate; @@ -249,7 +263,7 @@ class X509 /** * Certificate End Date * - * @var String + * @var string * @access private */ var $endDate; @@ -257,7 +271,7 @@ class X509 /** * Serial Number * - * @var String + * @var string * @access private */ var $serialNumber; @@ -268,7 +282,7 @@ class X509 * See {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.1 RFC5280#section-4.2.1.1} and * {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.2 RFC5280#section-4.2.1.2}. * - * @var String + * @var string * @access private */ var $currentKeyIdentifier; @@ -276,7 +290,7 @@ class X509 /** * CA Flag * - * @var Boolean + * @var bool * @access private */ var $caFlag = false; @@ -284,7 +298,7 @@ class X509 /** * SPKAC Challenge * - * @var String + * @var string * @access private */ var $challenge; @@ -1064,6 +1078,13 @@ function __construct() ) ); + $this->SubjectDirectoryAttributes = array( + 'type' => ASN1::TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $Attribute + ); + // adapted from $Attributes = array( @@ -1231,6 +1252,14 @@ function __construct() ) ); + $this->PostalAddress = array( + 'type' => ASN1::TYPE_SEQUENCE, + 'optional' => true, + 'min' => 1, + 'max' => -1, + 'children' => $this->DirectoryString + ); + // OIDs from RFC5280 and those RFCs mentioned in RFC5280#section-4.1.1.2 $this->oids = array( '1.3.6.1.5.5.7' => 'id-pkix', @@ -1265,6 +1294,7 @@ function __construct() '2.5.4.9' => 'id-at-streetAddress', '2.5.4.45' => 'id-at-uniqueIdentifier', '2.5.4.72' => 'id-at-role', + '2.5.4.16' => 'id-at-postalAddress', '0.9.2342.19200300.100.1.25' => 'id-domainComponent', '1.2.840.113549.1.9' => 'pkcs-9', @@ -1402,11 +1432,12 @@ function __construct() * * Returns an associative array describing the X.509 cert or a false if the cert failed to load * - * @param String $cert + * @param string $cert + * @param int $mode * @access public - * @return Mixed + * @return mixed */ - function loadX509($cert) + function loadX509($cert, $mode = self::FORMAT_AUTO_DETECT) { if (is_array($cert) && isset($cert['tbsCertificate'])) { unset($this->currentCert); @@ -1427,7 +1458,13 @@ function loadX509($cert) $asn1 = new ASN1(); - $cert = $this->_extractBER($cert); + if ($mode != self::FORMAT_DER) { + $newcert = $this->_extractBER($cert); + if ($mode == self::FORMAT_PEM && $cert == $newcert) { + return false; + } + $cert = $newcert; + } if ($cert === false) { $this->currentCert = false; @@ -1447,7 +1484,11 @@ function loadX509($cert) $this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); - $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1); + if ($this->_isSubArrayValid($x509, 'tbsCertificate/extensions')) { + $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1); + } + $this->_mapInDNs($x509, 'tbsCertificate/issuer/rdnSequence', $asn1); + $this->_mapInDNs($x509, 'tbsCertificate/subject/rdnSequence', $asn1); $key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']; $key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key); @@ -1464,10 +1505,10 @@ function loadX509($cert) /** * Save X.509 certificate * - * @param Array $cert - * @param Integer $format optional + * @param array $cert + * @param int $format optional * @access public - * @return String + * @return string */ function saveX509($cert, $format = self::FORMAT_PEM) { @@ -1524,6 +1565,8 @@ function saveX509($cert, $format = self::FORMAT_PEM) $asn1->loadFilters($filters); $this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1); + $this->_mapOutDNs($cert, 'tbsCertificate/issuer/rdnSequence', $asn1); + $this->_mapOutDNs($cert, 'tbsCertificate/subject/rdnSequence', $asn1); $cert = $asn1->encodeDER($cert, $this->Certificate); @@ -1540,16 +1583,16 @@ function saveX509($cert, $format = self::FORMAT_PEM) * Map extension values from octet string to extension-specific internal * format. * - * @param Array ref $root - * @param String $path - * @param Object $asn1 + * @param array ref $root + * @param string $path + * @param object $asn1 * @access private */ function _mapInExtensions(&$root, $path, $asn1) { - $extensions = &$this->_subArray($root, $path); + $extensions = &$this->_subArrayUnchecked($root, $path); - if (is_array($extensions)) { + if ($extensions) { for ($i = 0; $i < count($extensions); $i++) { $id = $extensions[$i]['extnId']; $value = &$extensions[$i]['extnValue']; @@ -1590,9 +1633,9 @@ function _mapInExtensions(&$root, $path, $asn1) * Map extension values from extension-specific internal format to * octet string. * - * @param Array ref $root - * @param String $path - * @param Object $asn1 + * @param array ref $root + * @param string $path + * @param object $asn1 * @access private */ function _mapOutExtensions(&$root, $path, $asn1) @@ -1656,9 +1699,9 @@ function _mapOutExtensions(&$root, $path, $asn1) * Map attribute values from ANY type to attribute-specific internal * format. * - * @param Array ref $root - * @param String $path - * @param Object $asn1 + * @param array ref $root + * @param string $path + * @param object $asn1 * @access private */ function _mapInAttributes(&$root, $path, $asn1) @@ -1681,7 +1724,7 @@ function _mapInAttributes(&$root, $path, $asn1) if ($mapped !== false) { $values[$j] = $mapped; } - if ($id == 'pkcs-9-at-extensionRequest') { + if ($id == 'pkcs-9-at-extensionRequest' && $this->_isSubArrayValid($values, $j)) { $this->_mapInExtensions($values, $j, $asn1); } } elseif ($map) { @@ -1697,9 +1740,9 @@ function _mapInAttributes(&$root, $path, $asn1) * Map attribute values from attribute-specific internal format to * ANY type. * - * @param Array ref $root - * @param String $path - * @param Object $asn1 + * @param array ref $root + * @param string $path + * @param object $asn1 * @access private */ function _mapOutAttributes(&$root, $path, $asn1) @@ -1736,12 +1779,74 @@ function _mapOutAttributes(&$root, $path, $asn1) } } + /** + * Map DN values from ANY type to DN-specific internal + * format. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapInDNs(&$root, $path, $asn1) + { + $dns = &$this->_subArray($root, $path); + + if (is_array($dns)) { + for ($i = 0; $i < count($dns); $i++) { + for ($j = 0; $j < count($dns[$i]); $j++) { + $type = $dns[$i][$j]['type']; + $value = &$dns[$i][$j]['value']; + if (is_object($value) && $value instanceof Element) { + $map = $this->_getMapping($type); + if (!is_bool($map)) { + $decoded = $asn1->decodeBER($value); + $value = $asn1->asn1map($decoded[0], $map); + } + } + } + } + } + } + + /** + * Map DN values from DN-specific internal format to + * ANY type. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapOutDNs(&$root, $path, $asn1) + { + $dns = &$this->_subArray($root, $path); + + if (is_array($dns)) { + $size = count($dns); + for ($i = 0; $i < $size; $i++) { + for ($j = 0; $j < count($dns[$i]); $j++) { + $type = $dns[$i][$j]['type']; + $value = &$dns[$i][$j]['value']; + if (is_object($value) && $value instanceof Element) { + continue; + } + + $map = $this->_getMapping($type); + if (!is_bool($map)) { + $value = new Element($asn1->encodeDER($value, $map)); + } + } + } + } + } + /** * Associate an extension ID to an extension mapping * - * @param String $extnId + * @param string $extnId * @access private - * @return Mixed + * @return mixed */ function _getMapping($extnId) { @@ -1768,6 +1873,8 @@ function _getMapping($extnId) return $this->AuthorityInfoAccessSyntax; case 'id-ce-subjectAltName': return $this->SubjectAltName; + case 'id-ce-subjectDirectoryAttributes': + return $this->SubjectDirectoryAttributes; case 'id-ce-privateKeyUsagePeriod': return $this->PrivateKeyUsagePeriod; case 'id-ce-issuerAltName': @@ -1827,6 +1934,8 @@ function _getMapping($extnId) return $this->CertificateIssuer; case 'id-ce-holdInstructionCode': return $this->HoldInstructionCode; + case 'id-at-postalAddress': + return $this->PostalAddress; } return false; @@ -1835,9 +1944,9 @@ function _getMapping($extnId) /** * Load an X.509 certificate as a certificate authority * - * @param String $cert + * @param string $cert * @access public - * @return Boolean + * @return bool */ function loadCA($cert) { @@ -1902,9 +2011,9 @@ function loadCA($cert) * component or component fragment. E.g., *.a.com matches foo.a.com but * not bar.foo.a.com. f*.com matches foo.com but not bar.com. * - * @param String $url + * @param string $url * @access public - * @return Boolean + * @return bool */ function validateURL($url) { @@ -1960,7 +2069,7 @@ function validateURL($url) * * If $date isn't defined it is assumed to be the current date. * - * @param Integer $date optional + * @param int $date optional * @access public */ function validateDate($date = null) @@ -1999,9 +2108,9 @@ function validateDate($date = null) * * The behavior of this function is inspired by {@link http://php.net/openssl-verify openssl_verify}. * - * @param Boolean $caonly optional + * @param bool $caonly optional * @access public - * @return Mixed + * @return mixed */ function validateSignature($caonly = true) { @@ -2018,14 +2127,16 @@ function validateSignature($caonly = true) switch (true) { case isset($this->currentCert['tbsCertificate']): // self-signed cert - if ($this->currentCert['tbsCertificate']['issuer'] === $this->currentCert['tbsCertificate']['subject']) { - $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); - $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier'); - switch (true) { - case !is_array($authorityKey): - case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: - $signingCert = $this->currentCert; // working cert - } + switch (true) { + case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertificate']['issuer'] === $this->currentCert['tbsCertificate']['subject']: + case defined('FILE_X509_IGNORE_TYPE') && $this->getIssuerDN(self::DN_STRING) === $this->getDN(self::DN_STRING): + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier'); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + $signingCert = $this->currentCert; // working cert + } } if (!empty($this->CAs)) { @@ -2033,15 +2144,17 @@ function validateSignature($caonly = true) // even if the cert is a self-signed one we still want to see if it's a CA; // if not, we'll conditionally return an error $ca = $this->CAs[$i]; - if ($this->currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) { - $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); - $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); - switch (true) { - case !is_array($authorityKey): - case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: - $signingCert = $ca; // working cert - break 2; - } + switch (true) { + case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']: + case defined('FILE_X509_IGNORE_TYPE') && $this->getDN(self::DN_STRING, $this->currentCert['tbsCertificate']['issuer']) === $this->getDN(self::DN_STRING, $ca['tbsCertificate']['subject']): + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + $signingCert = $ca; // working cert + break 3; + } } } if (count($this->CAs) == $i && $caonly) { @@ -2077,15 +2190,17 @@ function validateSignature($caonly = true) if (!empty($this->CAs)) { for ($i = 0; $i < count($this->CAs); $i++) { $ca = $this->CAs[$i]; - if ($this->currentCert['tbsCertList']['issuer'] === $ca['tbsCertificate']['subject']) { - $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); - $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); - switch (true) { - case !is_array($authorityKey): - case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: - $signingCert = $ca; // working cert - break 2; - } + switch (true) { + case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertList']['issuer'] === $ca['tbsCertificate']['subject']: + case defined('FILE_X509_IGNORE_TYPE') && $this->getDN(self::DN_STRING, $this->currentCert['tbsCertList']['issuer']) === $this->getDN(self::DN_STRING, $ca['tbsCertificate']['subject']): + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + $signingCert = $ca; // working cert + break 3; + } } } } @@ -2109,13 +2224,13 @@ function validateSignature($caonly = true) * * Returns true if the signature is verified, false if it is not correct or null on error * - * @param String $publicKeyAlgorithm - * @param String $publicKey - * @param String $signatureAlgorithm - * @param String $signature - * @param String $signatureSubject + * @param string $publicKeyAlgorithm + * @param string $publicKey + * @param string $signatureAlgorithm + * @param string $signature + * @param string $signatureSubject * @access private - * @return Integer + * @return int */ function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject) { @@ -2154,10 +2269,10 @@ function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm * * Reformats a public key to a format supported by phpseclib (if applicable) * - * @param String $algorithm - * @param String $key + * @param string $algorithm + * @param string $key * @access private - * @return String + * @return string */ function _reformatKey($algorithm, $key) { @@ -2180,15 +2295,13 @@ function _reformatKey($algorithm, $key) * * Takes in a base64 encoded "blob" and returns a human readable IP address * - * @param String $ip + * @param string $ip * @access private - * @return String + * @return string */ function _decodeIP($ip) { - $ip = base64_decode($ip); - list(, $ip) = unpack('N', $ip); - return long2ip($ip); + return inet_ntop(base64_decode($ip)); } /** @@ -2196,21 +2309,21 @@ function _decodeIP($ip) * * Takes a human readable IP address into a base64-encoded "blob" * - * @param String $ip + * @param string $ip * @access private - * @return String + * @return string */ function _encodeIP($ip) { - return base64_encode(pack('N', ip2long($ip))); + return base64_encode(inet_pton($ip)); } /** * "Normalizes" a Distinguished Name property * - * @param String $propName + * @param string $propName * @access private - * @return Mixed + * @return mixed */ function _translateDNProp($propName) { @@ -2289,6 +2402,9 @@ function _translateDNProp($propName) case 'uniqueidentifier': case 'x500uniqueidentifier': return 'id-at-uniqueIdentifier'; + case 'postaladdress': + case 'id-at-postaladdress': + return 'id-at-postalAddress'; default: return false; } @@ -2297,11 +2413,11 @@ function _translateDNProp($propName) /** * Set a Distinguished Name property * - * @param String $propName - * @param Mixed $propValue - * @param String $type optional + * @param string $propName + * @param mixed $propValue + * @param string $type optional * @access public - * @return Boolean + * @return bool */ function setDNProp($propName, $propValue, $type = 'utf8String') { @@ -2331,7 +2447,7 @@ function setDNProp($propName, $propValue, $type = 'utf8String') /** * Remove Distinguished Name properties * - * @param String $propName + * @param string $propName * @access public */ function removeDNProp($propName) @@ -2358,10 +2474,10 @@ function removeDNProp($propName) /** * Get Distinguished Name properties * - * @param String $propName - * @param Array $dn optional - * @param Boolean $withType optional - * @return Mixed + * @param string $propName + * @param array $dn optional + * @param bool $withType optional + * @return mixed * @access public */ function getDNProp($propName, $dn = null, $withType = false) @@ -2378,25 +2494,38 @@ function getDNProp($propName, $dn = null, $withType = false) return false; } + $asn1 = new ASN1(); + $asn1->loadOIDs($this->oids); + $filters = array(); + $filters['value'] = array('type' => ASN1::TYPE_UTF8_STRING); + $asn1->loadFilters($filters); + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); $dn = $dn['rdnSequence']; $result = array(); - $asn1 = new ASN1(); for ($i = 0; $i < count($dn); $i++) { if ($dn[$i][0]['type'] == $propName) { $v = $dn[$i][0]['value']; - if (!$withType && is_array($v)) { - foreach ($v as $type => $s) { - $type = array_search($type, $asn1->ANYmap, true); - if ($type !== false && isset($asn1->stringTypeSize[$type])) { - $s = $asn1->convert($s, $type); - if ($s !== false) { - $v = $s; - break; + if (!$withType) { + if (is_array($v)) { + foreach ($v as $type => $s) { + $type = array_search($type, $asn1->ANYmap, true); + if ($type !== false && isset($asn1->stringTypeSize[$type])) { + $s = $asn1->convert($s, $type); + if ($s !== false) { + $v = $s; + break; + } } } - } - if (is_array($v)) { - $v = array_pop($v); // Always strip data type. + if (is_array($v)) { + $v = array_pop($v); // Always strip data type. + } + } elseif (is_object($v) && $v instanceof Element) { + $map = $this->_getMapping($propName); + if (!is_bool($map)) { + $decoded = $asn1->decodeBER($v); + $v = $asn1->asn1map($decoded[0], $map); + } } } $result[] = $v; @@ -2409,11 +2538,11 @@ function getDNProp($propName, $dn = null, $withType = false) /** * Set a Distinguished Name * - * @param Mixed $dn - * @param Boolean $merge optional - * @param String $type optional + * @param mixed $dn + * @param bool $merge optional + * @param string $type optional * @access public - * @return Boolean + * @return bool */ function setDN($dn, $merge = false, $type = 'utf8String') { @@ -2437,7 +2566,7 @@ function setDN($dn, $merge = false, $type = 'utf8String') } // handles everything else - $results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); + $results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=|postalAddress=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); for ($i = 1; $i < count($results); $i+=2) { $prop = trim($results[$i], ', =/'); $value = $results[$i + 1]; @@ -2452,10 +2581,10 @@ function setDN($dn, $merge = false, $type = 'utf8String') /** * Get the Distinguished Name for a certificates subject * - * @param Mixed $format optional - * @param Array $dn optional + * @param mixed $format optional + * @param array $dn optional * @access public - * @return Boolean + * @return bool */ function getDN($format = self::DN_ARRAY, $dn = null) { @@ -2472,33 +2601,19 @@ function getDN($format = self::DN_ARRAY, $dn = null) $filters = array(); $filters['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING); $asn1->loadFilters($filters); + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); return $asn1->encodeDER($dn, $this->Name); - case self::DN_OPENSSL: - $dn = $this->getDN(self::DN_STRING, $dn); - if ($dn === false) { - return false; - } - $attrs = preg_split('#((?:^|, *|/)[a-z][a-z0-9]*=)#i', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); - $dn = array(); - for ($i = 1; $i < count($attrs); $i += 2) { - $prop = trim($attrs[$i], ', =/'); - $value = $attrs[$i + 1]; - if (!isset($dn[$prop])) { - $dn[$prop] = $value; - } else { - $dn[$prop] = array_merge((array) $dn[$prop], array($value)); - } - } - return $dn; case self::DN_CANON: // No SEQUENCE around RDNs and all string values normalized as - // trimmed lowercase UTF-8 with all spacing as one blank. + // trimmed lowercase UTF-8 with all spacing as one blank. + // constructed RDNs will not be canonicalized $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $filters = array(); $filters['value'] = array('type' => ASN1::TYPE_UTF8_STRING); $asn1->loadFilters($filters); $result = ''; + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); foreach ($dn['rdnSequence'] as $rdn) { foreach ($rdn as $i => $attr) { $attr = &$rdn[$i]; @@ -2530,7 +2645,15 @@ function getDN($format = self::DN_ARRAY, $dn = null) // Default is to return a string. $start = true; $output = ''; + + $result = array(); $asn1 = new ASN1(); + $asn1->loadOIDs($this->oids); + $filters = array(); + $filters['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING); + $asn1->loadFilters($filters); + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); + foreach ($dn['rdnSequence'] as $field) { $prop = $field[0]['type']; $value = $field[0]['value']; @@ -2538,33 +2661,37 @@ function getDN($format = self::DN_ARRAY, $dn = null) $delim = ', '; switch ($prop) { case 'id-at-countryName': - $desc = 'C='; + $desc = 'C'; break; case 'id-at-stateOrProvinceName': - $desc = 'ST='; + $desc = 'ST'; break; case 'id-at-organizationName': - $desc = 'O='; + $desc = 'O'; break; case 'id-at-organizationalUnitName': - $desc = 'OU='; + $desc = 'OU'; break; case 'id-at-commonName': - $desc = 'CN='; + $desc = 'CN'; break; case 'id-at-localityName': - $desc = 'L='; + $desc = 'L'; break; case 'id-at-surname': - $desc = 'SN='; + $desc = 'SN'; break; case 'id-at-uniqueIdentifier': $delim = '/'; - $desc = 'x500UniqueIdentifier='; + $desc = 'x500UniqueIdentifier'; + break; + case 'id-at-postalAddress': + $delim = '/'; + $desc = 'postalAddress'; break; default: $delim = '/'; - $desc = preg_replace('#.+-([^-]+)$#', '$1', $prop) . '='; + $desc = preg_replace('#.+-([^-]+)$#', '$1', $prop); } if (!$start) { @@ -2584,20 +2711,26 @@ function getDN($format = self::DN_ARRAY, $dn = null) if (is_array($value)) { $value = array_pop($value); // Always strip data type. } + } elseif (is_object($value) && $value instanceof Element) { + $callback = create_function('$x', 'return "\x" . bin2hex($x[0]);'); + $value = strtoupper(preg_replace_callback('#[^\x20-\x7E]#', $callback, $value->element)); } - $output.= $desc . $value; + $output.= $desc . '=' . $value; + $result[$desc] = isset($result[$desc]) ? + array_merge((array) $dn[$prop], array($value)) : + $value; $start = false; } - return $output; + return $format == self::DN_OPENSSL ? $result : $output; } /** * Get the Distinguished Name for a certificate/crl issuer * - * @param Integer $format optional + * @param int $format optional * @access public - * @return Mixed + * @return mixed */ function getIssuerDN($format = self::DN_ARRAY) { @@ -2617,9 +2750,9 @@ function getIssuerDN($format = self::DN_ARRAY) * Get the Distinguished Name for a certificate/csr subject * Alias of getDN() * - * @param Integer $format optional + * @param int $format optional * @access public - * @return Mixed + * @return mixed */ function getSubjectDN($format = self::DN_ARRAY) { @@ -2640,10 +2773,10 @@ function getSubjectDN($format = self::DN_ARRAY) /** * Get an individual Distinguished Name property for a certificate/crl issuer * - * @param String $propName - * @param Boolean $withType optional + * @param string $propName + * @param bool $withType optional * @access public - * @return Mixed + * @return mixed */ function getIssuerDNProp($propName, $withType = false) { @@ -2662,10 +2795,10 @@ function getIssuerDNProp($propName, $withType = false) /** * Get an individual Distinguished Name property for a certificate/csr subject * - * @param String $propName - * @param Boolean $withType optional + * @param string $propName + * @param bool $withType optional * @access public - * @return Mixed + * @return mixed */ function getSubjectDNProp($propName, $withType = false) { @@ -2687,7 +2820,7 @@ function getSubjectDNProp($propName, $withType = false) * Get the certificate chain for the current cert * * @access public - * @return Mixed + * @return mixed */ function getChain() { @@ -2733,9 +2866,9 @@ function getChain() * * Key needs to be a \phpseclib\Crypt\RSA object * - * @param Object $key + * @param object $key * @access public - * @return Boolean + * @return bool */ function setPublicKey($key) { @@ -2748,7 +2881,7 @@ function setPublicKey($key) * * Key needs to be a \phpseclib\Crypt\RSA object * - * @param Object $key + * @param object $key * @access public */ function setPrivateKey($key) @@ -2761,7 +2894,7 @@ function setPrivateKey($key) * * Used for SPKAC CSR's * - * @param String $challenge + * @param string $challenge * @access public */ function setChallenge($challenge) @@ -2775,7 +2908,7 @@ function setChallenge($challenge) * Returns a \phpseclib\Crypt\RSA object or a false. * * @access public - * @return Mixed + * @return mixed */ function getPublicKey() { @@ -2813,11 +2946,11 @@ function getPublicKey() /** * Load a Certificate Signing Request * - * @param String $csr + * @param string $csr * @access public - * @return Mixed + * @return mixed */ - function loadCSR($csr) + function loadCSR($csr, $mode = self::FORMAT_AUTO_DETECT) { if (is_array($csr) && isset($csr['certificationRequestInfo'])) { unset($this->currentCert); @@ -2836,7 +2969,13 @@ function loadCSR($csr) $asn1 = new ASN1(); - $csr = $this->_extractBER($csr); + if ($mode != self::FORMAT_DER) { + $newcsr = $this->_extractBER($csr); + if ($mode == self::FORMAT_PEM && $csr == $newcsr) { + return false; + } + $csr = $newcsr; + } $orig = $csr; if ($csr === false) { @@ -2858,8 +2997,10 @@ function loadCSR($csr) return false; } - $this->dn = $csr['certificationRequestInfo']['subject']; $this->_mapInAttributes($csr, 'certificationRequestInfo/attributes', $asn1); + $this->_mapInDNs($csr, 'certificationRequestInfo/subject/rdnSequence', $asn1); + + $this->dn = $csr['certificationRequestInfo']['subject']; $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); @@ -2886,10 +3027,10 @@ function loadCSR($csr) /** * Save CSR request * - * @param Array $csr - * @param Integer $format optional + * @param array $csr + * @param int $format optional * @access public - * @return String + * @return string */ function saveCSR($csr, $format = self::FORMAT_PEM) { @@ -2906,6 +3047,9 @@ function saveCSR($csr, $format = self::FORMAT_PEM) case 'rsaEncryption': $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'] = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']))); + $csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['parameters'] = null; + $csr['signatureAlgorithm']['parameters'] = null; + $csr['certificationRequestInfo']['signature']['parameters'] = null; } } @@ -2919,6 +3063,7 @@ function saveCSR($csr, $format = self::FORMAT_PEM) $asn1->loadFilters($filters); + $this->_mapOutDNs($csr, 'certificationRequestInfo/subject/rdnSequence', $asn1); $this->_mapOutAttributes($csr, 'certificationRequestInfo/attributes', $asn1); $csr = $asn1->encodeDER($csr, $this->CertificationRequest); @@ -2938,9 +3083,9 @@ function saveCSR($csr, $format = self::FORMAT_PEM) * * https://developer.mozilla.org/en-US/docs/HTML/Element/keygen * - * @param String $csr + * @param string $csr * @access public - * @return Mixed + * @return mixed */ function loadSPKAC($spkac) { @@ -2956,7 +3101,7 @@ function loadSPKAC($spkac) $asn1 = new ASN1(); - // OpenSSL produces SPKAC's that are preceeded by the string SPKAC= + // OpenSSL produces SPKAC's that are preceded by the string SPKAC= $temp = preg_replace('#(?:SPKAC=)|[ \r\n\\\]#', '', $spkac); $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; if ($temp != false) { @@ -3009,10 +3154,10 @@ function loadSPKAC($spkac) /** * Save a SPKAC CSR request * - * @param Array $csr - * @param Integer $format optional + * @param array $csr + * @param int $format optional * @access public - * @return String + * @return string */ function saveSPKAC($spkac, $format = self::FORMAT_PEM) { @@ -3043,7 +3188,7 @@ function saveSPKAC($spkac, $format = self::FORMAT_PEM) return $spkac; // case self::FORMAT_PEM: default: - // OpenSSL's implementation of SPKAC requires the SPKAC be preceeded by SPKAC= and since there are pretty much + // OpenSSL's implementation of SPKAC requires the SPKAC be preceded by SPKAC= and since there are pretty much // no other SPKAC decoders phpseclib will use that same format return 'SPKAC=' . base64_encode($spkac); } @@ -3052,11 +3197,11 @@ function saveSPKAC($spkac, $format = self::FORMAT_PEM) /** * Load a Certificate Revocation List * - * @param String $crl + * @param string $crl * @access public - * @return Mixed + * @return mixed */ - function loadCRL($crl) + function loadCRL($crl, $mode = self::FORMAT_AUTO_DETECT) { if (is_array($crl) && isset($crl['tbsCertList'])) { $this->currentCert = $crl; @@ -3066,7 +3211,13 @@ function loadCRL($crl) $asn1 = new ASN1(); - $crl = $this->_extractBER($crl); + if ($mode != self::FORMAT_DER) { + $newcrl = $this->_extractBER($crl); + if ($mode == self::FORMAT_PEM && $crl == $newcrl) { + return false; + } + $crl = $newcrl; + } $orig = $crl; if ($crl === false) { @@ -3090,11 +3241,19 @@ function loadCRL($crl) $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); - $this->_mapInExtensions($crl, 'tbsCertList/crlExtensions', $asn1); - $rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates'); - if (is_array($rclist)) { - foreach ($rclist as $i => $extension) { - $this->_mapInExtensions($rclist, "$i/crlEntryExtensions", $asn1); + $this->_mapInDNs($crl, 'tbsCertList/issuer/rdnSequence', $asn1); + if ($this->_isSubArrayValid($crl, 'tbsCertList/crlExtensions')) { + $this->_mapInExtensions($crl, 'tbsCertList/crlExtensions', $asn1); + } + if ($this->_isSubArrayValid($crl, 'tbsCertList/revokedCertificates')) { + $rclist_ref = &$this->_subArrayUnchecked($crl, 'tbsCertList/revokedCertificates'); + if ($rclist_ref) { + $rclist = $crl['tbsCertList']['revokedCertificates']; + foreach ($rclist as $i => $extension) { + if ($this->_isSubArrayValid($rclist, "$i/crlEntryExtensions", $asn1)) { + $this->_mapInExtensions($rclist_ref, "$i/crlEntryExtensions", $asn1); + } + } } } @@ -3107,10 +3266,10 @@ function loadCRL($crl) /** * Save Certificate Revocation List. * - * @param Array $crl - * @param Integer $format optional + * @param array $crl + * @param int $format optional * @access public - * @return String + * @return string */ function saveCRL($crl, $format = self::FORMAT_PEM) { @@ -3142,6 +3301,7 @@ function saveCRL($crl, $format = self::FORMAT_PEM) $asn1->loadFilters($filters); + $this->_mapOutDNs($crl, 'tbsCertList/issuer/rdnSequence', $asn1); $this->_mapOutExtensions($crl, 'tbsCertList/crlExtensions', $asn1); $rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates'); if (is_array($rclist)) { @@ -3169,9 +3329,9 @@ function saveCRL($crl, $format = self::FORMAT_PEM) * - 5.1.2.6 Revoked Certificates * by choosing utcTime iff year of date given is before 2050 and generalTime else. * - * @param String $date in format date('D, d M Y H:i:s O') + * @param string $date in format date('D, d M Y H:i:s O') * @access private - * @return Array + * @return array */ function _timeField($date) { @@ -3192,9 +3352,9 @@ function _timeField($date) * * @param \phpseclib\File\X509 $issuer * @param \phpseclib\File\X509 $subject - * @param String $signatureAlgorithm optional + * @param string $signatureAlgorithm optional * @access public - * @return Mixed + * @return mixed */ function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption') { @@ -3371,7 +3531,7 @@ function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption') * Sign a CSR * * @access public - * @return Mixed + * @return mixed */ function signCSR($signatureAlgorithm = 'sha1WithRSAEncryption') { @@ -3429,7 +3589,7 @@ function signCSR($signatureAlgorithm = 'sha1WithRSAEncryption') * Sign a SPKAC * * @access public - * @return Mixed + * @return mixed */ function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption') { @@ -3497,9 +3657,9 @@ function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption') * * @param \phpseclib\File\X509 $issuer * @param \phpseclib\File\X509 $crl - * @param String $signatureAlgorithm optional + * @param string $signatureAlgorithm optional * @access public - * @return Mixed + * @return mixed */ function signCRL($issuer, $crl, $signatureAlgorithm = 'sha1WithRSAEncryption') { @@ -3624,11 +3784,11 @@ function signCRL($issuer, $crl, $signatureAlgorithm = 'sha1WithRSAEncryption') /** * X.509 certificate signing helper function. * - * @param Object $key + * @param object $key * @param \phpseclib\File\X509 $subject - * @param String $signatureAlgorithm + * @param string $signatureAlgorithm * @access public - * @return Mixed + * @return mixed */ function _sign($key, $signatureAlgorithm) { @@ -3655,7 +3815,7 @@ function _sign($key, $signatureAlgorithm) /** * Set certificate start date * - * @param String $date + * @param string $date * @access public */ function setStartDate($date) @@ -3666,7 +3826,7 @@ function setStartDate($date) /** * Set certificate end date * - * @param String $date + * @param string $date * @access public */ function setEndDate($date) @@ -3691,7 +3851,7 @@ function setEndDate($date) /** * Set Serial Number * - * @param String $serial + * @param string $serial * @param $base optional * @access public */ @@ -3710,14 +3870,82 @@ function makeCA() $this->caFlag = true; } + /** + * Check for validity of subarray + * + * This is intended for use in conjunction with _subArrayUnchecked(), + * implementing the checks included in _subArray() but without copying + * a potentially large array by passing its reference by-value to is_array(). + * + * @param array $root + * @param string $path + * @return boolean + * @access private + */ + function _isSubArrayValid($root, $path) + { + if (!is_array($root)) { + return false; + } + + foreach (explode('/', $path) as $i) { + if (!is_array($root)) { + return false; + } + + if (!isset($root[$i])) { + return true; + } + + $root = $root[$i]; + } + + return true; + } + + /** + * Get a reference to a subarray + * + * This variant of _subArray() does no is_array() checking, + * so $root should be checked with _isSubArrayValid() first. + * + * This is here for performance reasons: + * Passing a reference (i.e. $root) by-value (i.e. to is_array()) + * creates a copy. If $root is an especially large array, this is expensive. + * + * @param array $root + * @param string $path absolute path with / as component separator + * @param bool $create optional + * @access private + * @return array|false + */ + function &_subArrayUnchecked(&$root, $path, $create = false) + { + $false = false; + + foreach (explode('/', $path) as $i) { + if (!isset($root[$i])) { + if (!$create) { + return $false; + } + + $root[$i] = array(); + } + + $root = &$root[$i]; + } + + return $root; + } + /** * Get a reference to a subarray * * @param array $root - * @param String $path absolute path with / as component separator - * @param Boolean $create optional + * @param string $path absolute path with / as component separator + * @param bool $create optional * @access private - * @return array item ref or false + * @return array|false */ function &_subArray(&$root, $path, $create = false) { @@ -3750,10 +3978,10 @@ function &_subArray(&$root, $path, $create = false) * Get a reference to an extension subarray * * @param array $root - * @param String $path optional absolute path with / as component separator - * @param Boolean $create optional + * @param string $path optional absolute path with / as component separator + * @param bool $create optional * @access private - * @return array ref or false + * @return array|false */ function &_extensions(&$root, $path = null, $create = false) { @@ -3804,10 +4032,10 @@ function &_extensions(&$root, $path = null, $create = false) /** * Remove an Extension * - * @param String $id - * @param String $path optional + * @param string $id + * @param string $path optional * @access private - * @return Boolean + * @return bool */ function _removeExtension($id, $path = null) { @@ -3834,11 +4062,11 @@ function _removeExtension($id, $path = null) * * Returns the extension if it exists and false if not * - * @param String $id - * @param Array $cert optional - * @param String $path optional + * @param string $id + * @param array $cert optional + * @param string $path optional * @access private - * @return Mixed + * @return mixed */ function _getExtension($id, $cert = null, $path = null) { @@ -3861,9 +4089,9 @@ function _getExtension($id, $cert = null, $path = null) * Returns a list of all extensions in use * * @param array $cert optional - * @param String $path optional + * @param string $path optional * @access private - * @return Array + * @return array */ function _getExtensions($cert = null, $path = null) { @@ -3882,13 +4110,13 @@ function _getExtensions($cert = null, $path = null) /** * Set an Extension * - * @param String $id - * @param Mixed $value - * @param Boolean $critical optional - * @param Boolean $replace optional - * @param String $path optional + * @param string $id + * @param mixed $value + * @param bool $critical optional + * @param bool $replace optional + * @param string $path optional * @access private - * @return Boolean + * @return bool */ function _setExtension($id, $value, $critical = false, $replace = true, $path = null) { @@ -3918,9 +4146,9 @@ function _setExtension($id, $value, $critical = false, $replace = true, $path = /** * Remove a certificate, CSR or CRL Extension * - * @param String $id + * @param string $id * @access public - * @return Boolean + * @return bool */ function removeExtension($id) { @@ -3932,10 +4160,10 @@ function removeExtension($id) * * Returns the extension if it exists and false if not * - * @param String $id - * @param Array $cert optional + * @param string $id + * @param array $cert optional * @access public - * @return Mixed + * @return mixed */ function getExtension($id, $cert = null) { @@ -3947,7 +4175,7 @@ function getExtension($id, $cert = null) * * @param array $cert optional * @access public - * @return Array + * @return array */ function getExtensions($cert = null) { @@ -3957,12 +4185,12 @@ function getExtensions($cert = null) /** * Set a certificate, CSR or CRL Extension * - * @param String $id - * @param Mixed $value - * @param Boolean $critical optional - * @param Boolean $replace optional + * @param string $id + * @param mixed $value + * @param bool $critical optional + * @param bool $replace optional * @access public - * @return Boolean + * @return bool */ function setExtension($id, $value, $critical = false, $replace = true) { @@ -3972,10 +4200,10 @@ function setExtension($id, $value, $critical = false, $replace = true) /** * Remove a CSR attribute. * - * @param String $id - * @param Integer $disposition optional + * @param string $id + * @param int $disposition optional * @access public - * @return Boolean + * @return bool */ function removeAttribute($id, $disposition = self::ATTR_ALL) { @@ -4022,11 +4250,11 @@ function removeAttribute($id, $disposition = self::ATTR_ALL) * * Returns the attribute if it exists and false if not * - * @param String $id - * @param Integer $disposition optional - * @param Array $csr optional + * @param string $id + * @param int $disposition optional + * @param array $csr optional * @access public - * @return Mixed + * @return mixed */ function getAttribute($id, $disposition = self::ATTR_ALL, $csr = null) { @@ -4066,7 +4294,7 @@ function getAttribute($id, $disposition = self::ATTR_ALL, $csr = null) * * @param array $csr optional * @access public - * @return Array + * @return array */ function getAttributes($csr = null) { @@ -4089,11 +4317,11 @@ function getAttributes($csr = null) /** * Set a CSR attribute * - * @param String $id - * @param Mixed $value - * @param Boolean $disposition optional + * @param string $id + * @param mixed $value + * @param bool $disposition optional * @access public - * @return Boolean + * @return bool */ function setAttribute($id, $value, $disposition = self::ATTR_ALL) { @@ -4147,7 +4375,7 @@ function setAttribute($id, $value, $disposition = self::ATTR_ALL) * * This is used by the id-ce-authorityKeyIdentifier and the id-ce-subjectKeyIdentifier extensions. * - * @param String $value + * @param string $value * @access public */ function setKeyIdentifier($value) @@ -4172,10 +4400,10 @@ function setKeyIdentifier($value) * - \phpseclib\File\ASN1\Element object * - PEM or DER string * - * @param Mixed $key optional - * @param Integer $method optional + * @param mixed $key optional + * @param int $method optional * @access public - * @return String binary key identifier + * @return string binary key identifier */ function computeKeyIdentifier($key = null, $method = 1) { @@ -4249,7 +4477,7 @@ function computeKeyIdentifier($key = null, $method = 1) * Format a public key as appropriate * * @access private - * @return Array + * @return array */ function _formatSubjectPublicKey() { @@ -4270,7 +4498,7 @@ function _formatSubjectPublicKey() * Set the domain name's which the cert is to be valid for * * @access public - * @return Array + * @return array */ function setDomain() { @@ -4283,7 +4511,7 @@ function setDomain() * Set the IP Addresses's which the cert is to be valid for * * @access public - * @param String $ipAddress optional + * @param string $ipAddress optional */ function setIPAddress() { @@ -4300,8 +4528,8 @@ function setIPAddress() * Helper function to build domain array * * @access private - * @param String $domain - * @return Array + * @param string $domain + * @return array */ function _dnsName($domain) { @@ -4314,8 +4542,8 @@ function _dnsName($domain) * (IPv6 is not currently supported) * * @access private - * @param String $address - * @return Array + * @param string $address + * @return array */ function _iPAddress($address) { @@ -4326,10 +4554,10 @@ function _iPAddress($address) * Get the index of a revoked certificate. * * @param array $rclist - * @param String $serial - * @param Boolean $create optional + * @param string $serial + * @param bool $create optional * @access private - * @return Integer or false + * @return int|false */ function _revokedCertificate(&$rclist, $serial, $create = false) { @@ -4354,10 +4582,10 @@ function _revokedCertificate(&$rclist, $serial, $create = false) /** * Revoke a certificate. * - * @param String $serial - * @param String $date optional + * @param string $serial + * @param string $date optional * @access public - * @return Boolean + * @return bool */ function revoke($serial, $date = null) { @@ -4381,9 +4609,9 @@ function revoke($serial, $date = null) /** * Unrevoke a certificate. * - * @param String $serial + * @param string $serial * @access public - * @return Boolean + * @return bool */ function unrevoke($serial) { @@ -4401,9 +4629,9 @@ function unrevoke($serial) /** * Get a revoked certificate. * - * @param String $serial + * @param string $serial * @access public - * @return Mixed + * @return mixed */ function getRevoked($serial) { @@ -4447,10 +4675,10 @@ function listRevoked($crl = null) /** * Remove a Revoked Certificate Extension * - * @param String $serial - * @param String $id + * @param string $serial + * @param string $id * @access public - * @return Boolean + * @return bool */ function removeRevokedCertificateExtension($serial, $id) { @@ -4468,11 +4696,11 @@ function removeRevokedCertificateExtension($serial, $id) * * Returns the extension if it exists and false if not * - * @param String $serial - * @param String $id - * @param Array $crl optional + * @param string $serial + * @param string $id + * @param array $crl optional * @access public - * @return Mixed + * @return mixed */ function getRevokedCertificateExtension($serial, $id, $crl = null) { @@ -4492,10 +4720,10 @@ function getRevokedCertificateExtension($serial, $id, $crl = null) /** * Returns a list of all extensions in use for a given revoked certificate * - * @param String $serial + * @param string $serial * @param array $crl optional * @access public - * @return Array + * @return array */ function getRevokedCertificateExtensions($serial, $crl = null) { @@ -4515,13 +4743,13 @@ function getRevokedCertificateExtensions($serial, $crl = null) /** * Set a Revoked Certificate Extension * - * @param String $serial - * @param String $id - * @param Mixed $value - * @param Boolean $critical optional - * @param Boolean $replace optional + * @param string $serial + * @param string $id + * @param mixed $value + * @param bool $critical optional + * @param bool $replace optional * @access public - * @return Boolean + * @return bool */ function setRevokedCertificateExtension($serial, $id, $value, $critical = false, $replace = true) { @@ -4540,8 +4768,8 @@ function setRevokedCertificateExtension($serial, $id, $value, $critical = false, * Extract raw BER from Base64 encoding * * @access private - * @param String $str - * @return String + * @param string $str + * @return string */ function _extractBER($str) { @@ -4554,7 +4782,7 @@ function _extractBER($str) * subject=/O=organization/OU=org unit/CN=common name * issuer=/O=organization/CN=common name */ - $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1); + $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1); // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff $temp = preg_replace('#-+[^-]+-+#', '', $temp); // remove new lines @@ -4562,4 +4790,31 @@ function _extractBER($str) $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; return $temp != false ? $temp : $str; } + + /** + * Returns the OID corresponding to a name + * + * What's returned in the associative array returned by loadX509() (or load*()) is either a name or an OID if + * no OID to name mapping is available. The problem with this is that what may be an unmapped OID in one version + * of phpseclib may not be unmapped in the next version, so apps that are looking at this OID may not be able + * to work from version to version. + * + * This method will return the OID if a name is passed to it and if no mapping is avialable it'll assume that + * what's being passed to it already is an OID and return that instead. A few examples. + * + * getOID('2.16.840.1.101.3.4.2.1') == '2.16.840.1.101.3.4.2.1' + * getOID('id-sha256') == '2.16.840.1.101.3.4.2.1' + * getOID('zzz') == 'zzz' + * + * @access public + * @return string + */ + function getOID($name) + { + static $reverseMap; + if (!isset($reverseMap)) { + $reverseMap = array_flip($this->oids); + } + return isset($reverseMap[$name]) ? $reverseMap[$name] : $name; + } } diff --git a/phpseclib/phpseclib/phpseclib/Math/BigInteger.php b/phpseclib/phpseclib/phpseclib/Math/BigInteger.php index bc7b22694..4b13d7c64 100644 --- a/phpseclib/phpseclib/phpseclib/Math/BigInteger.php +++ b/phpseclib/phpseclib/phpseclib/Math/BigInteger.php @@ -75,19 +75,19 @@ class BigInteger const MONTGOMERY = 0; /** * @see BigInteger::_barrett() - */ + */ const BARRETT = 1; /** * @see BigInteger::_mod2() - */ + */ const POWEROF2 = 2; /** * @see BigInteger::_remainder() - */ + */ const CLASSIC = 3; /** * @see BigInteger::__clone() - */ + */ const NONE = 4; /**#@-*/ @@ -101,11 +101,11 @@ class BigInteger */ /** * $result[self::VALUE] contains the value. - */ + */ const VALUE = 0; /** * $result[self::SIGN] contains the sign. - */ + */ const SIGN = 1; /**#@-*/ @@ -118,11 +118,11 @@ class BigInteger * Cache constants * * $cache[self::VARIABLE] tells us whether or not the cached data is still valid. - */ + */ const VARIABLE = 0; /** * $cache[self::DATA] contains the cached data. - */ + */ const DATA = 1; /**#@-*/ @@ -134,19 +134,19 @@ class BigInteger */ /** * To use the pure-PHP implementation - */ + */ const MODE_INTERNAL = 1; /** * To use the BCMath library * * (if enabled; otherwise, the internal implementation will be used) - */ + */ const MODE_BCMATH = 2; /** * To use the GMP library * * (if present; otherwise, either the BCMath or the internal implementation will be used) - */ + */ const MODE_GMP = 3; /**#@-*/ @@ -156,7 +156,7 @@ class BigInteger * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication? * * @access private - */ + */ const KARATSUBA_CUTOFF = 25; /**#@+ @@ -172,13 +172,13 @@ class BigInteger /** * $max10 in greatest $max10Len satisfying * $max10 = 10**$max10Len <= 2**$base. - */ + */ protected static $max10; /** * $max10Len in greatest $max10Len satisfying * $max10 = 10**$max10Len <= 2**$base. - */ + */ protected static $max10Len; protected static $maxDigit2; /**#@-*/ @@ -186,7 +186,7 @@ class BigInteger /** * Holds the BigInteger's value. * - * @var Array + * @var array * @access private */ var $value; @@ -194,22 +194,15 @@ class BigInteger /** * Holds the BigInteger's magnitude. * - * @var Boolean + * @var bool * @access private */ var $is_negative = false; - /** - * Random number generator function - * - * @access private - */ - var $generator = 'mt_rand'; - /** * Precision * - * @see setPrecision() + * @see self::setPrecision() * @access private */ var $precision = -1; @@ -217,7 +210,7 @@ class BigInteger /** * Precision Bitmask * - * @see setPrecision() + * @see self::setPrecision() * @access private */ var $bitmask = false; @@ -229,9 +222,9 @@ class BigInteger * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value, * however, $this->hex is only calculated when $this->__sleep() is called. * - * @see __sleep() - * @see __wakeup() - * @var String + * @see self::__sleep() + * @see self::__wakeup() + * @var string * @access private */ var $hex; @@ -251,8 +244,8 @@ class BigInteger * ?> * * - * @param optional $x base-10 number or base-$base number if $base set. - * @param optional integer $base + * @param $x base-10 number or base-$base number if $base set. + * @param int $base * @return \phpseclib\Math\BigInteger * @access public */ @@ -271,7 +264,7 @@ function __construct($x = 0, $base = 10) } } - if (function_exists('openssl_public_encrypt') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { + if (extension_loaded('openssl') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work ob_start(); @phpinfo(); @@ -299,6 +292,7 @@ function __construct($x = 0, $base = 10) case !isset($versions['Header']): case !isset($versions['Library']): case $versions['Header'] == $versions['Library']: + case version_compare($versions['Header'], '1.0.0') >= 0 && version_compare($versions['Library'], '1.0.0') >= 0: define('MATH_BIGINTEGER_OPENSSL_ENABLED', true); break; default: @@ -330,7 +324,6 @@ function __construct($x = 0, $base = 10) self::$max10 = 10000000; self::$max10Len = 7; self::$maxDigit2 = pow(2, 52); // pow() prevents truncation - break; } } @@ -423,13 +416,13 @@ function __construct($x = 0, $base = 10) $this->is_negative = false; break; case self::MODE_BCMATH: - $x = ( strlen($x) & 1 ) ? '0' . $x : $x; + $x = (strlen($x) & 1) ? '0' . $x : $x; $temp = new static(pack('H*', $x), 256); $this->value = $this->is_negative ? '-' . $temp->value : $temp->value; $this->is_negative = false; break; default: - $x = ( strlen($x) & 1 ) ? '0' . $x : $x; + $x = (strlen($x) & 1) ? '0' . $x : $x; $temp = new static(pack('H*', $x), 256); $this->value = $temp->value; } @@ -522,8 +515,8 @@ function __construct($x = 0, $base = 10) * ?> * * - * @param Boolean $twos_compliment - * @return String + * @param bool $twos_compliment + * @return string * @access public * @internal Converts a base-2**26 number to base-2**8 */ @@ -556,7 +549,7 @@ function toBytes($twos_compliment = false) } $temp = gmp_strval(gmp_abs($this->value), 16); - $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp; + $temp = (strlen($temp) & 1) ? '0' . $temp : $temp; $temp = pack('H*', $temp); return $this->precision > 0 ? @@ -617,8 +610,8 @@ function toBytes($twos_compliment = false) * ?> * * - * @param Boolean $twos_compliment - * @return String + * @param bool $twos_compliment + * @return string * @access public * @internal Converts a base-2**26 number to base-2**8 */ @@ -642,8 +635,8 @@ function toHex($twos_compliment = false) * ?> * * - * @param Boolean $twos_compliment - * @return String + * @param bool $twos_compliment + * @return string * @access public * @internal Converts a base-2**26 number to base-2**2 */ @@ -678,7 +671,7 @@ function toBits($twos_compliment = false) * ?> * * - * @return String + * @return string * @access public * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10) */ @@ -730,7 +723,7 @@ function toString() * {@link http://php.net/language.oop5.basic#51624} * * @access public - * @see __clone() + * @see self::__clone() * @return \phpseclib\Math\BigInteger */ function copy() @@ -738,7 +731,6 @@ function copy() $temp = new static(); $temp->value = $this->value; $temp->is_negative = $this->is_negative; - $temp->generator = $this->generator; $temp->precision = $this->precision; $temp->bitmask = $this->bitmask; return $temp; @@ -767,7 +759,7 @@ function __toString() * PHP5, call BigInteger::copy(), instead. * * @access public - * @see copy() + * @see self::copy() * @return \phpseclib\Math\BigInteger */ function __clone() @@ -780,21 +772,17 @@ function __clone() * * Will be called, automatically, when serialize() is called on a BigInteger object. * - * @see __wakeup() + * @see self::__wakeup() * @access public */ function __sleep() { $this->hex = $this->toHex(true); $vars = array('hex'); - if ($this->generator != 'mt_rand') { - $vars[] = 'generator'; - } if ($this->precision > 0) { $vars[] = 'precision'; } return $vars; - } /** @@ -802,7 +790,7 @@ function __sleep() * * Will be called, automatically, when unserialize() is called on a BigInteger object. * - * @see __sleep() + * @see self::__sleep() * @access public */ function __wakeup() @@ -816,6 +804,39 @@ function __wakeup() } } + /** + * __debugInfo() magic method + * + * Will be called, automatically, when print_r() or var_dump() are called + * + * @access public + */ + function __debugInfo() + { + $opts = array(); + switch (MATH_BIGINTEGER_MODE) { + case self::MODE_GMP: + $engine = 'gmp'; + break; + case self::MODE_BCMATH: + $engine = 'bcmath'; + break; + case self::MODE_INTERNAL: + $engine = 'internal'; + $opts[] = PHP_INT_SIZE == 8 ? '64-bit' : '32-bit'; + } + if (MATH_BIGINTEGER_MODE != self::MODE_GMP && defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { + $opts[] = 'OpenSSL'; + } + if (!empty($opts)) { + $engine.= ' (' . implode($opts, ', ') . ')'; + } + return array( + 'value' => '0x' . $this->toHex(true), + 'engine' => $engine + ); + } + /** * Adds two BigIntegers. * @@ -863,11 +884,11 @@ function add($y) /** * Performs addition. * - * @param Array $x_value - * @param Boolean $x_negative - * @param Array $y_value - * @param Boolean $y_negative - * @return Array + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return array * @access private */ function _add($x_value, $x_negative, $y_value, $y_negative) @@ -992,11 +1013,11 @@ function subtract($y) /** * Performs subtraction. * - * @param Array $x_value - * @param Boolean $x_negative - * @param Array $y_value - * @param Boolean $y_negative - * @return Array + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return array * @access private */ function _subtract($x_value, $x_negative, $y_value, $y_negative) @@ -1125,11 +1146,11 @@ function multiply($x) /** * Performs multiplication. * - * @param Array $x_value - * @param Boolean $x_negative - * @param Array $y_value - * @param Boolean $y_negative - * @return Array + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return array * @access private */ function _multiply($x_value, $x_negative, $y_value, $y_negative) @@ -1164,9 +1185,9 @@ function _multiply($x_value, $x_negative, $y_value, $y_negative) * * Modeled after 'multiply' in MutableBigInteger.java. * - * @param Array $x_value - * @param Array $y_value - * @return Array + * @param array $x_value + * @param array $y_value + * @return array * @access private */ function _regularMultiply($x_value, $y_value) @@ -1228,9 +1249,9 @@ function _regularMultiply($x_value, $y_value) * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}. * - * @param Array $x_value - * @param Array $y_value - * @return Array + * @param array $x_value + * @param array $y_value + * @return array * @access private */ function _karatsuba($x_value, $y_value) @@ -1267,8 +1288,8 @@ function _karatsuba($x_value, $y_value) /** * Performs squaring * - * @param Array $x - * @return Array + * @param array $x + * @return array * @access private */ function _square($x = false) @@ -1285,8 +1306,8 @@ function _square($x = false) * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} / * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information. * - * @param Array $value - * @return Array + * @param array $value + * @return array * @access private */ function _baseSquare($value) @@ -1324,8 +1345,8 @@ function _baseSquare($value) * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}. * - * @param Array $value - * @return Array + * @param array $value + * @return array * @access private */ function _karatsubaSquare($value) @@ -1379,7 +1400,7 @@ function _karatsubaSquare($value) * * * @param \phpseclib\Math\BigInteger $y - * @return Array + * @return array * @access public * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}. */ @@ -1495,7 +1516,7 @@ function divide($y) ); $y_window = array( $y_value[$y_max], - ( $y_max > 0 ) ? $y_value[$y_max - 1] : 0 + ($y_max > 0) ? $y_value[$y_max - 1] : 0 ); $q_index = $i - $y_max - 1; @@ -1559,9 +1580,9 @@ function divide($y) * * abc / x = a00 / x + b0 / x + c / x * - * @param Array $dividend - * @param Array $divisor - * @return Array + * @param array $dividend + * @param array $divisor + * @return array * @access private */ function _divide_digit($dividend, $divisor) @@ -1687,10 +1708,10 @@ function modPow($e, $n) } if (MATH_BIGINTEGER_MODE == self::MODE_BCMATH) { - $temp = new static(); - $temp->value = bcpowmod($this->value, $e->value, $n->value, 0); + $temp = new static(); + $temp->value = bcpowmod($this->value, $e->value, $n->value, 0); - return $this->_normalize($temp); + return $this->_normalize($temp); } if (empty($e->value)) { @@ -1741,7 +1762,7 @@ function modPow($e, $n) $mod2->value = array(1); $mod2->_lshift($j); - $part1 = ( $mod1->value != array(1) ) ? $this->_slidingWindow($e, $mod1, self::MONTGOMERY) : new static(); + $part1 = ($mod1->value != array(1)) ? $this->_slidingWindow($e, $mod1, self::MONTGOMERY) : new static(); $part2 = $this->_slidingWindow($e, $mod2, self::POWEROF2); $y1 = $mod2->modInverse($mod1); @@ -1784,7 +1805,7 @@ function powMod($e, $n) * * @param \phpseclib\Math\BigInteger $e * @param \phpseclib\Math\BigInteger $n - * @param Integer $mode + * @param int $mode * @return \phpseclib\Math\BigInteger * @access private */ @@ -1804,7 +1825,7 @@ function _slidingWindow($e, $n, $mode) // calculate the appropriate window size. // $window_size == 3 if $window_ranges is between 25 and 81, for example. - for ($i = 0, $window_size = 1; $e_length > $window_ranges[$i] && $i < count($window_ranges); ++$window_size, ++$i) { + for ($i = 0, $window_size = 1; $i < count($window_ranges) && $e_length > $window_ranges[$i]; ++$window_size, ++$i) { } $n_value = $n->value; @@ -1836,13 +1857,14 @@ function _slidingWindow($e, $n, $mode) } } - for ($k = 0; $k <= $j; ++$k) {// eg. the length of substr($e_bits, $i, $j+1) + // eg. the length of substr($e_bits, $i, $j + 1) + for ($k = 0; $k <= $j; ++$k) { $result = $this->_squareReduce($result, $n_value, $mode); } $result = $this->_multiplyReduce($result, $powers[bindec(substr($e_bits, $i, $j + 1))], $n_value, $mode); - $i+=$j + 1; + $i += $j + 1; } } @@ -1857,12 +1879,12 @@ function _slidingWindow($e, $n, $mode) * * For most $modes this will return the remainder. * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $n - * @param Integer $mode - * @return Array + * @param array $x + * @param array $n + * @param int $mode + * @return array */ function _reduce($x, $n, $mode) { @@ -1894,12 +1916,12 @@ function _reduce($x, $n, $mode) /** * Modular reduction preperation * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $n - * @param Integer $mode - * @return Array + * @param array $x + * @param array $n + * @param int $mode + * @return array */ function _prepareReduce($x, $n, $mode) { @@ -1912,13 +1934,13 @@ function _prepareReduce($x, $n, $mode) /** * Modular multiply * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $y - * @param Array $n - * @param Integer $mode - * @return Array + * @param array $x + * @param array $y + * @param array $n + * @param int $mode + * @return array */ function _multiplyReduce($x, $y, $n, $mode) { @@ -1932,12 +1954,12 @@ function _multiplyReduce($x, $y, $n, $mode) /** * Modular square * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $n - * @param Integer $mode - * @return Array + * @param array $x + * @param array $n + * @param int $mode + * @return array */ function _squareReduce($x, $n, $mode) { @@ -1953,7 +1975,7 @@ function _squareReduce($x, $n, $mode) * Calculates $x%$n, where $n = 2**$e, for some $e. Since this is basically the same as doing $x & ($n-1), * we'll just use this function as a wrapper for doing that. * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private * @param \phpseclib\Math\BigInteger * @return \phpseclib\Math\BigInteger @@ -1983,11 +2005,11 @@ function _mod2($n) * (x >> 1) + (x >> 1) != x / 2 + x / 2. If x is even, they're the same, but if x is odd, they're not. See the in-line * comments for details. * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private - * @param Array $n - * @param Array $m - * @return Array + * @param array $n + * @param array $m + * @return array */ function _barrett($n, $m) { @@ -2080,11 +2102,11 @@ function _barrett($n, $m) * For numbers with more than four digits BigInteger::_barrett() is faster. The difference between that and this * is that this function does not fold the denominator into a smaller form. * - * @see _slidingWindow() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $n - * @return Array + * @param array $x + * @param array $n + * @return array */ function _regularBarrett($x, $n) { @@ -2151,13 +2173,13 @@ function _regularBarrett($x, $n) * * If you're going to be doing array_slice($product->value, 0, $stop), some cycles can be saved. * - * @see _regularBarrett() - * @param Array $x_value - * @param Boolean $x_negative - * @param Array $y_value - * @param Boolean $y_negative - * @param Integer $stop - * @return Array + * @see self::_regularBarrett() + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @param int $stop + * @return array * @access private */ function _multiplyLower($x_value, $x_negative, $y_value, $y_negative, $stop) @@ -2232,12 +2254,12 @@ function _multiplyLower($x_value, $x_negative, $y_value, $y_negative, $stop) * improved upon (basically, by using the comba method). gcd($n, 2) must be equal to one for this function * to work correctly. * - * @see _prepMontgomery() - * @see _slidingWindow() + * @see self::_prepMontgomery() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $n - * @return Array + * @param array $x + * @param array $n + * @return array */ function _montgomery($x, $n) { @@ -2279,13 +2301,13 @@ function _montgomery($x, $n) * Interleaves the montgomery reduction and long multiplication algorithms together as described in * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=13 HAC 14.36} * - * @see _prepMontgomery() - * @see _montgomery() + * @see self::_prepMontgomery() + * @see self::_montgomery() * @access private - * @param Array $x - * @param Array $y - * @param Array $m - * @return Array + * @param array $x + * @param array $y + * @param array $m + * @return array */ function _montgomeryMultiply($x, $y, $m) { @@ -2331,12 +2353,12 @@ function _montgomeryMultiply($x, $y, $m) /** * Prepare a number for use in Montgomery Modular Reductions * - * @see _montgomery() - * @see _slidingWindow() + * @see self::_montgomery() + * @see self::_slidingWindow() * @access private - * @param Array $x - * @param Array $n - * @return Array + * @param array $x + * @param array $n + * @return array */ function _prepMontgomery($x, $n) { @@ -2370,10 +2392,10 @@ function _prepMontgomery($x, $n) * * Thanks to Pedro Gimeno Fortea for input! * - * @see _montgomery() + * @see self::_montgomery() * @access private - * @param Array $x - * @return Integer + * @param array $x + * @return int */ function _modInverse67108864($x) // 2**26 == 67,108,864 { @@ -2409,7 +2431,7 @@ function _modInverse67108864($x) // 2**26 == 67,108,864 * * * @param \phpseclib\Math\BigInteger $n - * @return mixed false, if no modular inverse exists, \phpseclib\Math\BigInteger, otherwise. + * @return \phpseclib\Math\BigInteger|false * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=21 HAC 14.64} for more information. */ @@ -2420,7 +2442,7 @@ function modInverse($n) $temp = new static(); $temp->value = gmp_invert($this->value, $n->value); - return ( $temp->value === false ) ? false : $this->_normalize($temp); + return ($temp->value === false) ? false : $this->_normalize($temp); } static $zero, $one; @@ -2454,7 +2476,7 @@ function modInverse($n) * * Say you have 693 and 609. The GCD is 21. Bezout's identity states that there exist integers x and y such that * 693*x + 609*y == 21. In point of fact, there are actually an infinite number of x and y combinations and which - * combination is returned is dependant upon which mode is in use. See + * combination is returned is dependent upon which mode is in use. See * {@link http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity Bezout's identity - Wikipedia} for more information. * * Here's an example: @@ -2649,9 +2671,9 @@ function abs() * Note how the same comparison operator is used. If you want to test for equality, use $x->equals($y). * * @param \phpseclib\Math\BigInteger $y - * @return Integer < 0 if $this is less than $y; > 0 if $this is greater than $y, and 0 if they are equal. + * @return int < 0 if $this is less than $y; > 0 if $this is greater than $y, and 0 if they are equal. * @access public - * @see equals() + * @see self::equals() * @internal Could return $this->subtract($x), but that's not as fast as what we do do. */ function compare($y) @@ -2669,24 +2691,24 @@ function compare($y) /** * Compares two numbers. * - * @param Array $x_value - * @param Boolean $x_negative - * @param Array $y_value - * @param Boolean $y_negative - * @return Integer - * @see compare() + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return int + * @see self::compare() * @access private */ function _compare($x_value, $x_negative, $y_value, $y_negative) { if ($x_negative != $y_negative) { - return ( !$x_negative && $y_negative ) ? 1 : -1; + return (!$x_negative && $y_negative) ? 1 : -1; } $result = $x_negative ? -1 : 1; if (count($x_value) != count($y_value)) { - return ( count($x_value) > count($y_value) ) ? $result : -$result; + return (count($x_value) > count($y_value)) ? $result : -$result; } $size = max(count($x_value), count($y_value)); @@ -2695,7 +2717,7 @@ function _compare($x_value, $x_negative, $y_value, $y_negative) for ($i = count($x_value) - 1; $i >= 0; --$i) { if ($x_value[$i] != $y_value[$i]) { - return ( $x_value[$i] > $y_value[$i] ) ? $result : -$result; + return ($x_value[$i] > $y_value[$i]) ? $result : -$result; } } @@ -2708,9 +2730,9 @@ function _compare($x_value, $x_negative, $y_value, $y_negative) * If you need to see if one number is greater than or less than another number, use BigInteger::compare() * * @param \phpseclib\Math\BigInteger $x - * @return Boolean + * @return bool * @access public - * @see compare() + * @see self::compare() */ function equals($x) { @@ -2728,7 +2750,7 @@ function equals($x) * Some bitwise operations give different results depending on the precision being used. Examples include left * shift, not, and rotates. * - * @param Integer $bits + * @param int $bits * @access public */ function setPrecision($bits) @@ -2877,6 +2899,9 @@ function bitwise_not() // calculuate "not" without regard to $this->precision // (will always result in a smaller number. ie. ~1 isn't 1111 1110 - it's 0) $temp = $this->toBytes(); + if ($temp == '') { + return ''; + } $pre_msb = decbin(ord($temp[0])); $temp = ~$temp; $msb = decbin(ord($temp[0])); @@ -2906,7 +2931,7 @@ function bitwise_not() * * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift. * - * @param Integer $shift + * @param int $shift * @return \phpseclib\Math\BigInteger * @access public * @internal The only version that yields any speed increases is the internal version. @@ -2944,7 +2969,7 @@ function bitwise_rightShift($shift) * * Shifts BigInteger's by $shift bits, effectively multiplying by 2**$shift. * - * @param Integer $shift + * @param int $shift * @return \phpseclib\Math\BigInteger * @access public * @internal The only version that yields any speed increases is the internal version. @@ -2982,7 +3007,7 @@ function bitwise_leftShift($shift) * * Instead of the top x bits being dropped they're appended to the shifted bit string. * - * @param Integer $shift + * @param int $shift * @return \phpseclib\Math\BigInteger * @access public */ @@ -3027,7 +3052,7 @@ function bitwise_leftRotate($shift) * * Instead of the bottom x bits being dropped they're prepended to the shifted bit string. * - * @param Integer $shift + * @param int $shift * @return \phpseclib\Math\BigInteger * @access public */ @@ -3041,7 +3066,7 @@ function bitwise_rightRotate($shift) * * Byte length is equal to $length. Uses \phpseclib\Crypt\Random if it's loaded and mt_rand if it's not. * - * @param Integer $length + * @param int $length * @return \phpseclib\Math\BigInteger * @access private */ @@ -3076,7 +3101,7 @@ function _random_number_helper($size) * $max->random($min) * * @param \phpseclib\Math\BigInteger $arg1 - * @param optional \phpseclib\Math\BigInteger $arg2 + * @param \phpseclib\Math\BigInteger $arg2 * @return \phpseclib\Math\BigInteger * @access public * @internal The API for creating random numbers used to be $a->random($min, $max), where $a was a BigInteger object. @@ -3153,13 +3178,13 @@ function random($arg1, $arg2 = false) /** * Generate a random prime number. * - * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed, - * give up and return false. + * If there's not a prime within the given range, false will be returned. + * If more than $timeout seconds have elapsed, give up and return false. * * @param \phpseclib\Math\BigInteger $arg1 - * @param optional \phpseclib\Math\BigInteger $arg2 - * @param optional Integer $timeout - * @return Mixed + * @param \phpseclib\Math\BigInteger $arg2 + * @param int $timeout + * @return Math_BigInteger|false * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ @@ -3199,7 +3224,7 @@ function randomPrime($arg1, $arg2 = false, $timeout = false) $x = $this->random($min, $max); // gmp_nextprime() requires PHP 5 >= 5.2.0 per . - if (MATH_BIGINTEGER_MODE == self::MODE_GMP && function_exists('gmp_nextprime')) { + if (MATH_BIGINTEGER_MODE == self::MODE_GMP && extension_loaded('gmp')) { $p = new static(); $p->value = gmp_nextprime($x->value); @@ -3260,7 +3285,7 @@ function randomPrime($arg1, $arg2 = false, $timeout = false) * * If the current number is odd it'll be unchanged. If it's even, one will be added to it. * - * @see randomPrime() + * @see self::randomPrime() * @access private */ function _make_odd() @@ -3286,8 +3311,8 @@ function _make_odd() * $t parameter is distributability. BigInteger::randomPrime() can be distributed across multiple pageloads * on a website instead of just one. * - * @param optional \phpseclib\Math\BigInteger $t - * @return Boolean + * @param \phpseclib\Math\BigInteger $t + * @return bool * @access public * @internal Uses the * {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See @@ -3439,7 +3464,7 @@ function isPrime($t = false) * * Shifts BigInteger's by $shift bits. * - * @param Integer $shift + * @param int $shift * @access private */ function _lshift($shift) @@ -3474,7 +3499,7 @@ function _lshift($shift) * * Shifts BigInteger's by $shift bits. * - * @param Integer $shift + * @param int $shift * @access private */ function _rshift($shift) @@ -3510,7 +3535,7 @@ function _rshift($shift) * * @param \phpseclib\Math\BigInteger * @return \phpseclib\Math\BigInteger - * @see _trim() + * @see self::_trim() * @access private */ function _normalize($result) @@ -3520,7 +3545,7 @@ function _normalize($result) switch (MATH_BIGINTEGER_MODE) { case self::MODE_GMP: - if (!empty($result->bitmask->value)) { + if ($this->bitmask !== false) { $result->value = gmp_and($result->value, $result->bitmask->value); } @@ -3558,7 +3583,7 @@ function _normalize($result) * * Removes leading zeros * - * @param Array $value + * @param array $value * @return \phpseclib\Math\BigInteger * @access private */ @@ -3579,7 +3604,7 @@ function _trim($value) * * @param $input Array * @param $multiplier mixed - * @return Array + * @return array * @access private */ function _array_repeat($input, $multiplier) @@ -3594,7 +3619,7 @@ function _array_repeat($input, $multiplier) * * @param $x String * @param $shift Integer - * @return String + * @return string * @access private */ function _base256_lshift(&$x, $shift) @@ -3623,7 +3648,7 @@ function _base256_lshift(&$x, $shift) * * @param $x String * @param $shift Integer - * @return String + * @return string * @access private */ function _base256_rshift(&$x, $shift) @@ -3663,8 +3688,8 @@ function _base256_rshift(&$x, $shift) /** * Converts 32-bit integers to bytes. * - * @param Integer $x - * @return String + * @param int $x + * @return string * @access private */ function _int2bytes($x) @@ -3675,8 +3700,8 @@ function _int2bytes($x) /** * Converts bytes to 32-bit integers * - * @param String $x - * @return Integer + * @param string $x + * @return int * @access private */ function _bytes2int($x) @@ -3690,10 +3715,10 @@ function _bytes2int($x) * * The ability to DER-encode integers is needed to create RSA public keys for use with OpenSSL * - * @see modPow() + * @see self::modPow() * @access private - * @param Integer $length - * @return String + * @param int $length + * @return string */ function _encodeASN1Length($length) { @@ -3714,9 +3739,9 @@ function _encodeASN1Length($length) * we'll guarantee that the dividend is divisible by first subtracting the remainder. * * @access private - * @param Integer $x - * @param Integer $y - * @return Integer + * @param int $x + * @param int $y + * @return int */ function _safe_divide($x, $y) { diff --git a/phpseclib/phpseclib/phpseclib/Net/SCP.php b/phpseclib/phpseclib/phpseclib/Net/SCP.php index 678297e0a..b9efacf8c 100644 --- a/phpseclib/phpseclib/phpseclib/Net/SCP.php +++ b/phpseclib/phpseclib/phpseclib/Net/SCP.php @@ -17,7 +17,7 @@ * exit('bad login'); * } * $scp = new \phpseclib\Net\SCP($ssh); - + * * $scp->put('abcd', str_repeat('x', 1024*1024)); * ?> * @@ -32,9 +32,6 @@ namespace phpseclib\Net; -use phpseclib\Net\SSH1; -use phpseclib\Net\SSH2; - /** * Pure-PHP implementations of SCP. * @@ -54,7 +51,7 @@ class SCP const SOURCE_LOCAL_FILE = 1; /** * Reads data from a string. - */ + */ const SOURCE_STRING = 2; /**#@-*/ @@ -65,18 +62,18 @@ class SCP */ /** * SSH1 is being used. - */ + */ const MODE_SSH1 = 1; /** * SSH2 is being used. - */ + */ const MODE_SSH2 = 2; /**#@-*/ /** * SSH Object * - * @var Object + * @var object * @access private */ var $ssh; @@ -84,7 +81,7 @@ class SCP /** * Packet Size * - * @var Integer + * @var int * @access private */ var $packet_size; @@ -92,7 +89,7 @@ class SCP /** * Mode * - * @var Integer + * @var int * @access private */ var $mode; @@ -102,9 +99,9 @@ class SCP * * Connects to an SSH server * - * @param String $host - * @param optional Integer $port - * @param optional Integer $timeout + * @param string $host + * @param int $port + * @param int $timeout * @return \phpseclib\Net\SCP * @access public */ @@ -136,11 +133,11 @@ function __construct($ssh) * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take * care of that, yourself. * - * @param String $remote_file - * @param String $data - * @param optional Integer $mode - * @param optional Callable $callback - * @return Boolean + * @param string $remote_file + * @param string $data + * @param int $mode + * @param callable $callback + * @return bool * @access public */ function put($remote_file, $data, $mode = self::SOURCE_STRING, $callback = null) @@ -212,9 +209,9 @@ function put($remote_file, $data, $mode = self::SOURCE_STRING, $callback = null) * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the * operation * - * @param String $remote_file - * @param optional String $local_file - * @return Mixed + * @param string $remote_file + * @param string $local_file + * @return mixed * @access public */ function get($remote_file, $local_file = false) @@ -270,7 +267,7 @@ function get($remote_file, $local_file = false) /** * Sends a packet to an SSH server * - * @param String $data + * @param string $data * @access private */ function _send($data) @@ -288,7 +285,7 @@ function _send($data) /** * Receives a packet from an SSH server * - * @return String + * @return string * @access private */ function _receive() diff --git a/phpseclib/phpseclib/phpseclib/Net/SFTP.php b/phpseclib/phpseclib/phpseclib/Net/SFTP.php index 60d8923d8..ec7429549 100644 --- a/phpseclib/phpseclib/phpseclib/Net/SFTP.php +++ b/phpseclib/phpseclib/phpseclib/Net/SFTP.php @@ -37,8 +37,6 @@ namespace phpseclib\Net; -use phpseclib\Net\SSH2; - /** * Pure-PHP implementations of SFTP. * @@ -56,7 +54,7 @@ class SFTP extends SSH2 * @see \phpseclib\Net\SSH2::_send_channel_packet() * @see \phpseclib\Net\SSH2::_get_channel_packet() * @access private - */ + */ const CHANNEL = 0x100; /**#@+ @@ -65,11 +63,11 @@ class SFTP extends SSH2 */ /** * Reads data from a local file. - */ + */ const SOURCE_LOCAL_FILE = 1; /** * Reads data from a string. - */ + */ // this value isn't really used anymore but i'm keeping it reserved for historical reasons const SOURCE_STRING = 2; /** @@ -79,19 +77,19 @@ class SFTP extends SSH2 const SOURCE_CALLBACK = 16; /** * Resumes an upload - */ + */ const RESUME = 4; /** * Append a local file to an already existing remote file - */ + */ const RESUME_START = 8; /**#@-*/ /** * Packet Types * - * @see \phpseclib\Net\SFTP::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $packet_types = array(); @@ -99,8 +97,8 @@ class SFTP extends SSH2 /** * Status Codes * - * @see \phpseclib\Net\SFTP::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $status_codes = array(); @@ -111,8 +109,8 @@ class SFTP extends SSH2 * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support * concurrent actions, so it's somewhat academic, here. * - * @var Integer - * @see \phpseclib\Net\SFTP::_send_sftp_packet() + * @var int + * @see self::_send_sftp_packet() * @access private */ var $request_id = false; @@ -123,8 +121,8 @@ class SFTP extends SSH2 * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support * concurrent actions, so it's somewhat academic, here. * - * @var Integer - * @see \phpseclib\Net\SFTP::_get_sftp_packet() + * @var int + * @see self::_get_sftp_packet() * @access private */ var $packet_type = -1; @@ -132,8 +130,8 @@ class SFTP extends SSH2 /** * Packet Buffer * - * @var String - * @see \phpseclib\Net\SFTP::_get_sftp_packet() + * @var string + * @see self::_get_sftp_packet() * @access private */ var $packet_buffer = ''; @@ -141,8 +139,8 @@ class SFTP extends SSH2 /** * Extensions supported by the server * - * @var Array - * @see \phpseclib\Net\SFTP::_initChannel() + * @var array + * @see self::_initChannel() * @access private */ var $extensions = array(); @@ -150,8 +148,8 @@ class SFTP extends SSH2 /** * Server SFTP version * - * @var Integer - * @see \phpseclib\Net\SFTP::_initChannel() + * @var int + * @see self::_initChannel() * @access private */ var $version; @@ -159,9 +157,9 @@ class SFTP extends SSH2 /** * Current working directory * - * @var String - * @see \phpseclib\Net\SFTP::_realpath() - * @see \phpseclib\Net\SFTP::chdir() + * @var string + * @see self::_realpath() + * @see self::chdir() * @access private */ var $pwd = false; @@ -169,8 +167,8 @@ class SFTP extends SSH2 /** * Packet Type Log * - * @see \phpseclib\Net\SFTP::getLog() - * @var Array + * @see self::getLog() + * @var array * @access private */ var $packet_type_log = array(); @@ -178,8 +176,8 @@ class SFTP extends SSH2 /** * Packet Log * - * @see \phpseclib\Net\SFTP::getLog() - * @var Array + * @see self::getLog() + * @var array * @access private */ var $packet_log = array(); @@ -187,9 +185,9 @@ class SFTP extends SSH2 /** * Error information * - * @see \phpseclib\Net\SFTP::getSFTPErrors() - * @see \phpseclib\Net\SFTP::getLastSFTPError() - * @var String + * @see self::getSFTPErrors() + * @see self::getLastSFTPError() + * @var string * @access private */ var $sftp_errors = array(); @@ -200,10 +198,10 @@ class SFTP extends SSH2 * Rather than always having to open a directory and close it immediately there after to see if a file is a directory * we'll cache the results. * - * @see \phpseclib\Net\SFTP::_update_stat_cache() - * @see \phpseclib\Net\SFTP::_remove_from_stat_cache() - * @see \phpseclib\Net\SFTP::_query_stat_cache() - * @var Array + * @see self::_update_stat_cache() + * @see self::_remove_from_stat_cache() + * @see self::_query_stat_cache() + * @var array * @access private */ var $stat_cache = array(); @@ -211,9 +209,9 @@ class SFTP extends SSH2 /** * Max SFTP Packet Size * - * @see \phpseclib\Net\SFTP::__construct() - * @see \phpseclib\Net\SFTP::get() - * @var Array + * @see self::__construct() + * @see self::get() + * @var array * @access private */ var $max_sftp_packet; @@ -221,9 +219,9 @@ class SFTP extends SSH2 /** * Stat Cache Flag * - * @see \phpseclib\Net\SFTP::disableStatCache() - * @see \phpseclib\Net\SFTP::enableStatCache() - * @var Boolean + * @see self::disableStatCache() + * @see self::enableStatCache() + * @var bool * @access private */ var $use_stat_cache = true; @@ -231,9 +229,9 @@ class SFTP extends SSH2 /** * Sort Options * - * @see \phpseclib\Net\SFTP::_comparator() - * @see \phpseclib\Net\SFTP::setListOrder() - * @var Array + * @see self::_comparator() + * @see self::setListOrder() + * @var array * @access private */ var $sortOptions = array(); @@ -243,9 +241,9 @@ class SFTP extends SSH2 * * Connects to an SFTP server * - * @param String $host - * @param optional Integer $port - * @param optional Integer $timeout + * @param string $host + * @param int $port + * @param int $timeout * @return \phpseclib\Net\SFTP * @access public */ @@ -341,7 +339,7 @@ function __construct($host, $port = 22, $timeout = 10) ); // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 // the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name - // the array for that $this->open5_flags and similarily alter the constant names. + // the array for that $this->open5_flags and similarly alter the constant names. $this->open_flags = array( 0x00000001 => 'NET_SFTP_OPEN_READ', 0x00000002 => 'NET_SFTP_OPEN_WRITE', @@ -381,9 +379,9 @@ function __construct($host, $port = 22, $timeout = 10) /** * Login * - * @param String $username - * @param optional String $password - * @return Boolean + * @param string $username + * @param string $password + * @return bool * @access public */ function login($username) @@ -571,7 +569,7 @@ function clearStatCache() /** * Returns the current directory name * - * @return Mixed + * @return mixed * @access public */ function pwd() @@ -582,8 +580,8 @@ function pwd() /** * Logs errors * - * @param String $response - * @param optional Integer $status + * @param string $response + * @param int $status * @access public */ function _logError($response, $status = -1) @@ -602,15 +600,30 @@ function _logError($response, $status = -1) } } + /** + * Returns canonicalized absolute pathname + * + * realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input + * path and returns the canonicalized absolute pathname. + * + * @param string $path + * @return mixed + * @access public + */ + function realpath($path) + { + return $this->_realpath($path); + } + /** * Canonicalize the Server-Side Path Name * * SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns * the absolute (canonicalized) path. * - * @see \phpseclib\Net\SFTP::chdir() - * @param String $path - * @return Mixed + * @see self::chdir() + * @param string $path + * @return mixed * @access private */ function _realpath($path) @@ -665,8 +678,8 @@ function _realpath($path) /** * Changes the current directory * - * @param String $dir - * @return Boolean + * @param string $dir + * @return bool * @access public */ function chdir($dir) @@ -727,9 +740,9 @@ function chdir($dir) /** * Returns a list of files in the given directory * - * @param optional String $dir - * @param optional Boolean $recursive - * @return Mixed + * @param string $dir + * @param bool $recursive + * @return mixed * @access public */ function nlist($dir = '.', $recursive = false) @@ -740,17 +753,17 @@ function nlist($dir = '.', $recursive = false) /** * Helper method for nlist * - * @param String $dir - * @param Boolean $recursive - * @param String $relativeDir - * @return Mixed + * @param string $dir + * @param bool $recursive + * @param string $relativeDir + * @return mixed * @access private */ function _nlist_helper($dir, $recursive, $relativeDir) { $files = $this->_list($dir, false); - if (!$recursive) { + if (!$recursive || $files === false) { return $files; } @@ -776,9 +789,9 @@ function _nlist_helper($dir, $recursive, $relativeDir) /** * Returns a detailed list of files in the given directory * - * @param optional String $dir - * @param optional Boolean $recursive - * @return Mixed + * @param string $dir + * @param bool $recursive + * @return mixed * @access public */ function rawlist($dir = '.', $recursive = false) @@ -810,9 +823,9 @@ function rawlist($dir = '.', $recursive = false) /** * Reads a list, be it detailed or not, of files in the given directory * - * @param String $dir - * @param optional Boolean $raw - * @return Mixed + * @param string $dir + * @param bool $raw + * @return mixed * @access private */ function _list($dir, $raw = true) @@ -920,9 +933,9 @@ function _list($dir, $raw = true) * * Intended for use with uasort() * - * @param Array $a - * @param Array $b - * @return Integer + * @param array $a + * @param array $b + * @return int * @access private */ function _comparator($a, $b) @@ -1020,8 +1033,8 @@ function setListOrder() * * Files larger than 4GB will show up as being exactly 4GB. * - * @param String $filename - * @return Mixed + * @param string $filename + * @return mixed * @access public */ function size($filename) @@ -1040,8 +1053,8 @@ function size($filename) /** * Save files / directories to cache * - * @param String $path - * @param Mixed $value + * @param string $path + * @param mixed $value * @access private */ function _update_stat_cache($path, $value) @@ -1084,8 +1097,8 @@ function _update_stat_cache($path, $value) /** * Remove files / directories from cache * - * @param String $path - * @return Boolean + * @param string $path + * @return bool * @access private */ function _remove_from_stat_cache($path) @@ -1111,8 +1124,8 @@ function _remove_from_stat_cache($path) * * Mainly used by file_exists * - * @param String $dir - * @return Mixed + * @param string $dir + * @return mixed * @access private */ function _query_stat_cache($path) @@ -1134,8 +1147,8 @@ function _query_stat_cache($path) * * Returns an array on success and false otherwise. * - * @param String $filename - * @return Mixed + * @param string $filename + * @return mixed * @access public */ function stat($filename) @@ -1191,8 +1204,8 @@ function stat($filename) * * Returns an array on success and false otherwise. * - * @param String $filename - * @return Mixed + * @param string $filename + * @return mixed * @access public */ function lstat($filename) @@ -1257,9 +1270,9 @@ function lstat($filename) * Determines information without calling \phpseclib\Net\SFTP::_realpath(). * The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT. * - * @param String $filename - * @param Integer $type - * @return Mixed + * @param string $filename + * @param int $type + * @return mixed * @access private */ function _stat($filename, $type) @@ -1286,9 +1299,9 @@ function _stat($filename, $type) /** * Truncates a file to a given length * - * @param String $filename - * @param Integer $new_size - * @return Boolean + * @param string $filename + * @param int $new_size + * @return bool * @access public */ function truncate($filename, $new_size) @@ -1303,10 +1316,10 @@ function truncate($filename, $new_size) * * If the file does not exist, it will be created. * - * @param String $filename - * @param optional Integer $time - * @param optional Integer $atime - * @return Boolean + * @param string $filename + * @param int $time + * @param int $atime + * @return bool * @access public */ function touch($filename, $time = null, $atime = null) @@ -1354,10 +1367,10 @@ function touch($filename, $time = null, $atime = null) * * Returns true on success or false on error. * - * @param String $filename - * @param Integer $uid - * @param optional Boolean $recursive - * @return Boolean + * @param string $filename + * @param int $uid + * @param bool $recursive + * @return bool * @access public */ function chown($filename, $uid, $recursive = false) @@ -1374,10 +1387,10 @@ function chown($filename, $uid, $recursive = false) * * Returns true on success or false on error. * - * @param String $filename - * @param Integer $gid - * @param optional Boolean $recursive - * @return Boolean + * @param string $filename + * @param int $gid + * @param bool $recursive + * @return bool * @access public */ function chgrp($filename, $gid, $recursive = false) @@ -1393,10 +1406,10 @@ function chgrp($filename, $gid, $recursive = false) * Returns the new file permissions on success or false on error. * If $recursive is true than this just returns true or false. * - * @param Integer $mode - * @param String $filename - * @param optional Boolean $recursive - * @return Mixed + * @param int $mode + * @param string $filename + * @param bool $recursive + * @return mixed * @access public */ function chmod($mode, $filename, $recursive = false) @@ -1415,6 +1428,7 @@ function chmod($mode, $filename, $recursive = false) return true; } + $filename = $this->_realPath($filename); // rather than return what the permissions *should* be, we'll return what they actually are. this will also // tell us if the file actually exists. // incidentally, SFTPv4+ adds an additional 32-bit integer field - flags - to the following: @@ -1440,10 +1454,10 @@ function chmod($mode, $filename, $recursive = false) /** * Sets information about a file * - * @param String $filename - * @param String $attr - * @param Boolean $recursive - * @return Boolean + * @param string $filename + * @param string $attr + * @param bool $recursive + * @return bool * @access private */ function _setstat($filename, $attr, $recursive) @@ -1499,10 +1513,10 @@ function _setstat($filename, $attr, $recursive) * * Minimizes directory lookups and SSH_FXP_STATUS requests for speed. * - * @param String $path - * @param String $attr - * @param Integer $i - * @return Boolean + * @param string $path + * @param string $attr + * @param int $i + * @return bool * @access private */ function _setstat_recursive($path, $attr, &$i) @@ -1569,8 +1583,8 @@ function _setstat_recursive($path, $attr, &$i) /** * Return the target of a symbolic link * - * @param String $link - * @return Mixed + * @param string $link + * @return mixed * @access public */ function readlink($link) @@ -1612,9 +1626,9 @@ function readlink($link) * * symlink() creates a symbolic link to the existing target with the specified name link. * - * @param String $target - * @param String $link - * @return Boolean + * @param string $target + * @param string $link + * @return bool * @access public */ function symlink($target, $link) @@ -1623,7 +1637,7 @@ function symlink($target, $link) return false; } - $target = $this->_realpath($target); + //$target = $this->_realpath($target); $link = $this->_realpath($link); $packet = pack('Na*Na*', strlen($target), $target, strlen($link), $link); @@ -1649,8 +1663,8 @@ function symlink($target, $link) /** * Creates a directory. * - * @param String $dir - * @return Boolean + * @param string $dir + * @return bool * @access public */ function mkdir($dir, $mode = -1, $recursive = false) @@ -1684,8 +1698,8 @@ function mkdir($dir, $mode = -1, $recursive = false) /** * Helper function for directory creation * - * @param String $dir - * @return Boolean + * @param string $dir + * @return bool * @access private */ function _mkdir_helper($dir, $attr) @@ -1712,8 +1726,8 @@ function _mkdir_helper($dir, $attr) /** * Removes a directory. * - * @param String $dir - * @return Boolean + * @param string $dir + * @return bool * @access public */ function rmdir($dir) @@ -1788,13 +1802,13 @@ function rmdir($dir) * * Setting $local_start to > 0 or $mode | self::RESUME_START doesn't do anything unless $mode | self::SOURCE_LOCAL_FILE. * - * @param String $remote_file - * @param String|resource $data - * @param optional Integer $mode - * @param optional Integer $start - * @param optional Integer $local_start - * @param optional callable|null $progressCallback - * @return Boolean + * @param string $remote_file + * @param string|resource $data + * @param int $mode + * @param int $start + * @param int $local_start + * @param callable|null $progressCallback + * @return bool * @access public * @internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - \phpseclib\Net\SFTP::setMode(). */ @@ -1876,10 +1890,7 @@ function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $loc if ($local_start >= 0) { fseek($fp, $local_start); - } elseif ($mode & self::RESUME_START) { - // do nothing - } else { - fseek($fp, $offset); + $size-= $local_start; } } elseif ($dataCallback) { $size = 0; @@ -1894,7 +1905,7 @@ function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $loc // make the SFTP packet be exactly 4096 bytes by including the bytes in the NET_SFTP_WRITE packets "header" $sftp_packet_size-= strlen($handle) + 25; $i = 0; - while ($dataCallback || $sent < $size) { + while ($dataCallback || ($size === 0 || $sent < $size)) { if ($dataCallback) { $temp = call_user_func($dataCallback, $sftp_packet_size); if (is_null($temp)) { @@ -1902,7 +1913,11 @@ function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $loc } } else { $temp = isset($fp) ? fread($fp, $sftp_packet_size) : substr($data, $sent, $sftp_packet_size); + if ($temp === false) { + break; + } } + $subtemp = $offset + $sent; $packet = pack('Na*N3a*', strlen($handle), $handle, $subtemp / 4294967296, $subtemp, strlen($temp), $temp); if (!$this->_send_sftp_packet(NET_SFTP_WRITE, $packet)) { @@ -1948,8 +1963,8 @@ function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $loc * Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i * SSH_FXP_WRITEs, in succession, and then reading $i responses. * - * @param Integer $i - * @return Boolean + * @param int $i + * @return bool * @access private */ function _read_put_responses($i) @@ -1974,8 +1989,8 @@ function _read_put_responses($i) /** * Close handle * - * @param String $handle - * @return Boolean + * @param string $handle + * @return bool * @access private */ function _close_handle($handle) @@ -2010,11 +2025,11 @@ function _close_handle($handle) * * $offset and $length can be used to download files in chunks. * - * @param String $remote_file - * @param optional String $local_file - * @param optional Integer $offset - * @param optional Integer $length - * @return Mixed + * @param string $remote_file + * @param string $local_file + * @param int $offset + * @param int $length + * @return mixed * @access public */ function get($remote_file, $local_file = false, $offset = 0, $length = -1) @@ -2126,9 +2141,9 @@ function get($remote_file, $local_file = false, $offset = 0, $length = -1) /** * Deletes a file on the SFTP server. * - * @param String $path - * @param Boolean $recursive - * @return Boolean + * @param string $path + * @param bool $recursive + * @return bool * @access public */ function delete($path, $recursive = true) @@ -2176,9 +2191,9 @@ function delete($path, $recursive = true) * * Minimizes directory lookups and SSH_FXP_STATUS requests for speed. * - * @param String $path - * @param Integer $i - * @return Boolean + * @param string $path + * @param int $i + * @return bool * @access private */ function _delete_recursive($path, &$i) @@ -2243,8 +2258,8 @@ function _delete_recursive($path, &$i) /** * Checks whether a file or directory exists * - * @param String $path - * @return Boolean + * @param string $path + * @return bool * @access public */ function file_exists($path) @@ -2266,8 +2281,8 @@ function file_exists($path) /** * Tells whether the filename is a directory * - * @param String $path - * @return Boolean + * @param string $path + * @return bool * @access public */ function is_dir($path) @@ -2282,8 +2297,8 @@ function is_dir($path) /** * Tells whether the filename is a regular file * - * @param String $path - * @return Boolean + * @param string $path + * @return bool * @access public */ function is_file($path) @@ -2298,8 +2313,8 @@ function is_file($path) /** * Tells whether the filename is a symbolic link * - * @param String $path - * @return Boolean + * @param string $path + * @return bool * @access public */ function is_link($path) @@ -2311,11 +2326,81 @@ function is_link($path) return $result === NET_SFTP_TYPE_SYMLINK; } + /** + * Tells whether a file exists and is readable + * + * @param string $path + * @return bool + * @access public + */ + function is_readable($path) + { + $path = $this->_realpath($path); + + $packet = pack('Na*N2', strlen($path), $path, NET_SFTP_OPEN_READ, 0); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + return true; + case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + } + + /** + * Tells whether the filename is writable + * + * @param string $path + * @return bool + * @access public + */ + function is_writable($path) + { + $path = $this->_realpath($path); + + $packet = pack('Na*N2', strlen($path), $path, NET_SFTP_OPEN_WRITE, 0); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + return true; + case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + } + + /** + * Tells whether the filename is writeable + * + * Alias of is_writable + * + * @param string $path + * @return bool + * @access public + */ + function is_writeable($path) + { + return $this->is_writable($path); + } + /** * Gets last access time of file * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function fileatime($path) @@ -2326,8 +2411,8 @@ function fileatime($path) /** * Gets file modification time * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function filemtime($path) @@ -2338,8 +2423,8 @@ function filemtime($path) /** * Gets file permissions * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function fileperms($path) @@ -2350,8 +2435,8 @@ function fileperms($path) /** * Gets file owner * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function fileowner($path) @@ -2362,8 +2447,8 @@ function fileowner($path) /** * Gets file group * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function filegroup($path) @@ -2374,8 +2459,8 @@ function filegroup($path) /** * Gets file size * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function filesize($path) @@ -2386,8 +2471,8 @@ function filesize($path) /** * Gets file type * - * @param String $path - * @return Mixed + * @param string $path + * @return mixed * @access public */ function filetype($path) @@ -2420,9 +2505,9 @@ function filetype($path) * * Uses cache if appropriate. * - * @param String $path - * @param String $prop - * @return Mixed + * @param string $path + * @param string $prop + * @return mixed * @access private */ function _get_stat_cache_prop($path, $prop) @@ -2435,9 +2520,9 @@ function _get_stat_cache_prop($path, $prop) * * Uses cache if appropriate. * - * @param String $path - * @param String $prop - * @return Mixed + * @param string $path + * @param string $prop + * @return mixed * @access private */ function _get_lstat_cache_prop($path, $prop) @@ -2450,9 +2535,9 @@ function _get_lstat_cache_prop($path, $prop) * * Uses cache if appropriate. * - * @param String $path - * @param String $prop - * @return Mixed + * @param string $path + * @param string $prop + * @return mixed * @access private */ function _get_xstat_cache_prop($path, $prop, $type) @@ -2479,9 +2564,9 @@ function _get_xstat_cache_prop($path, $prop, $type) /** * Renames a file or a directory on the SFTP server * - * @param String $oldname - * @param String $newname - * @return Boolean + * @param string $oldname + * @param string $newname + * @return bool * @access public */ function rename($oldname, $newname) @@ -2529,8 +2614,8 @@ function rename($oldname, $newname) * * See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info. * - * @param String $response - * @return Array + * @param string $response + * @return array * @access private */ function _parseAttributes(&$response) @@ -2583,8 +2668,8 @@ function _parseAttributes(&$response) * * Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway * - * @param Integer $mode - * @return Integer + * @param int $mode + * @return int * @access private */ function _parseMode($mode) @@ -2630,8 +2715,8 @@ function _parseMode($mode) * * If the longname is in an unrecognized format bool(false) is returned. * - * @param String $longname - * @return Mixed + * @param string $longname + * @return mixed * @access private */ function _parseLongname($longname) @@ -2659,11 +2744,11 @@ function _parseLongname($longname) * * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info. * - * @param Integer $type - * @param String $data - * @see \phpseclib\Net\SFTP::_get_sftp_packet() - * @see \phpseclib\Net\SSH2::_send_channel_packet() - * @return Boolean + * @param int $type + * @param string $data + * @see self::_get_sftp_packet() + * @see self::_send_channel_packet() + * @return bool * @access private */ function _send_sftp_packet($type, $data) @@ -2703,8 +2788,8 @@ function _send_sftp_packet($type, $data) * There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA * messages containing one SFTP packet. * - * @see \phpseclib\Net\SFTP::_send_sftp_packet() - * @return String + * @see self::_send_sftp_packet() + * @return string * @access private */ function _get_sftp_packet() @@ -2776,7 +2861,7 @@ function _get_sftp_packet() * Returns a string if NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX, an array if NET_SFTP_LOGGING == NET_SFTP_LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING') * * @access public - * @return String or Array + * @return string or Array */ function getSFTPLog() { @@ -2797,7 +2882,7 @@ function getSFTPLog() /** * Returns all errors * - * @return String + * @return string * @access public */ function getSFTPErrors() @@ -2808,7 +2893,7 @@ function getSFTPErrors() /** * Returns the last error * - * @return String + * @return string * @access public */ function getLastSFTPError() @@ -2819,7 +2904,7 @@ function getLastSFTPError() /** * Get supported SFTP versions * - * @return Array + * @return array * @access public */ function getSupportedVersions() @@ -2834,8 +2919,8 @@ function getSupportedVersions() /** * Disconnect * - * @param Integer $reason - * @return Boolean + * @param int $reason + * @return bool * @access private */ function _disconnect($reason) diff --git a/phpseclib/phpseclib/phpseclib/Net/SFTP/Stream.php b/phpseclib/phpseclib/phpseclib/Net/SFTP/Stream.php index 2758e73c1..08d726ca8 100644 --- a/phpseclib/phpseclib/phpseclib/Net/SFTP/Stream.php +++ b/phpseclib/phpseclib/phpseclib/Net/SFTP/Stream.php @@ -34,14 +34,14 @@ class Stream * * Rather than re-create the connection we re-use instances if possible * - * @var Array + * @var array */ static $instances; /** * SFTP instance * - * @var Object + * @var object * @access private */ var $sftp; @@ -49,7 +49,7 @@ class Stream /** * Path * - * @var String + * @var string * @access private */ var $path; @@ -57,7 +57,7 @@ class Stream /** * Mode * - * @var String + * @var string * @access private */ var $mode; @@ -65,7 +65,7 @@ class Stream /** * Position * - * @var Integer + * @var int * @access private */ var $pos; @@ -73,7 +73,7 @@ class Stream /** * Size * - * @var Integer + * @var int * @access private */ var $size; @@ -81,7 +81,7 @@ class Stream /** * Directory entries * - * @var Array + * @var array * @access private */ var $entries; @@ -89,7 +89,7 @@ class Stream /** * EOF flag * - * @var Boolean + * @var bool * @access private */ var $eof; @@ -99,7 +99,7 @@ class Stream * * Technically this needs to be publically accessible so PHP can set it directly * - * @var Resource + * @var resource * @access public */ var $context; @@ -107,7 +107,7 @@ class Stream /** * Notification callback function * - * @var Callable + * @var callable * @access public */ var $notification; @@ -115,8 +115,8 @@ class Stream /** * Registers this class as a URL wrapper. * - * @param optional String $protocol The wrapper name to be registered. - * @return Boolean True on success, false otherwise. + * @param string $protocol The wrapper name to be registered. + * @return bool True on success, false otherwise. * @access public */ static function register($protocol = 'sftp') @@ -147,13 +147,24 @@ function __construct() * If "notification" is set as a context parameter the message code for successful login is * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE. * - * @param String $path - * @return String + * @param string $path + * @return string * @access private */ function _parse_path($path) { + $orig = $path; extract(parse_url($path) + array('port' => 22)); + if (isset($query)) { + $path.= '?' . $query; + } elseif (preg_match('/(\?|\?#)$/', $orig)) { + $path.= '?'; + } + if (isset($fragment)) { + $path.= '#' . $fragment; + } elseif ($orig[strlen($orig) - 1] == '#') { + $path.= '#'; + } if (!isset($host)) { return false; @@ -239,11 +250,11 @@ function _parse_path($path) /** * Opens file or URL * - * @param String $path - * @param String $mode - * @param Integer $options - * @param String $opened_path - * @return Boolean + * @param string $path + * @param string $mode + * @param int $options + * @param string $opened_path + * @return bool * @access public */ function _stream_open($path, $mode, $options, &$opened_path) @@ -284,8 +295,8 @@ function _stream_open($path, $mode, $options, &$opened_path) /** * Read from stream * - * @param Integer $count - * @return Mixed + * @param int $count + * @return mixed * @access public */ function _stream_read($count) @@ -326,8 +337,8 @@ function _stream_read($count) /** * Write to stream * - * @param String $data - * @return Mixed + * @param string $data + * @return mixed * @access public */ function _stream_write($data) @@ -361,7 +372,7 @@ function _stream_write($data) /** * Retrieve the current position of a stream * - * @return Integer + * @return int * @access public */ function _stream_tell() @@ -379,7 +390,7 @@ function _stream_tell() * will return false. do fread($fp, 1) and feof() will then return true. do fseek($fp, 10) on ablank file and feof() * will return false. do fread($fp, 1) and feof() will then return true. * - * @return Boolean + * @return bool * @access public */ function _stream_eof() @@ -390,9 +401,9 @@ function _stream_eof() /** * Seeks to specific location in a stream * - * @param Integer $offset - * @param Integer $whence - * @return Boolean + * @param int $offset + * @param int $whence + * @return bool * @access public */ function _stream_seek($offset, $whence) @@ -418,10 +429,10 @@ function _stream_seek($offset, $whence) /** * Change stream options * - * @param String $path - * @param Integer $option - * @param Mixed $var - * @return Boolean + * @param string $path + * @param int $option + * @param mixed $var + * @return bool * @access public */ function _stream_metadata($path, $option, $var) @@ -452,8 +463,8 @@ function _stream_metadata($path, $option, $var) /** * Retrieve the underlaying resource * - * @param Integer $cast_as - * @return Resource + * @param int $cast_as + * @return resource * @access public */ function _stream_cast($cast_as) @@ -464,8 +475,8 @@ function _stream_cast($cast_as) /** * Advisory file locking * - * @param Integer $operation - * @return Boolean + * @param int $operation + * @return bool * @access public */ function _stream_lock($operation) @@ -480,9 +491,9 @@ function _stream_lock($operation) * If newname exists, it will be overwritten. This is a departure from what \phpseclib\Net\SFTP * does. * - * @param String $path_from - * @param String $path_to - * @return Boolean + * @param string $path_from + * @param string $path_to + * @return bool * @access public */ function _rename($path_from, $path_to) @@ -532,9 +543,9 @@ function _rename($path_from, $path_to) * string longname * ATTRS attrs * - * @param String $path - * @param Integer $options - * @return Boolean + * @param string $path + * @param int $options + * @return bool * @access public */ function _dir_opendir($path, $options) @@ -551,7 +562,7 @@ function _dir_opendir($path, $options) /** * Read entry from directory handle * - * @return Mixed + * @return mixed * @access public */ function _dir_readdir() @@ -565,7 +576,7 @@ function _dir_readdir() /** * Rewind directory handle * - * @return Boolean + * @return bool * @access public */ function _dir_rewinddir() @@ -577,7 +588,7 @@ function _dir_rewinddir() /** * Close directory handle * - * @return Boolean + * @return bool * @access public */ function _dir_closedir() @@ -590,10 +601,10 @@ function _dir_closedir() * * Only valid $options is STREAM_MKDIR_RECURSIVE * - * @param String $path - * @param Integer $mode - * @param Integer $options - * @return Boolean + * @param string $path + * @param int $mode + * @param int $options + * @return bool * @access public */ function _mkdir($path, $mode, $options) @@ -614,10 +625,10 @@ function _mkdir($path, $mode, $options) * STREAM_MKDIR_RECURSIVE is supposed to be set. Also, when I try it out with rmdir() I get 8 as * $options. What does 8 correspond to? * - * @param String $path - * @param Integer $mode - * @param Integer $options - * @return Boolean + * @param string $path + * @param int $mode + * @param int $options + * @return bool * @access public */ function _rmdir($path, $options) @@ -635,7 +646,7 @@ function _rmdir($path, $options) * * See . Always returns true because \phpseclib\Net\SFTP doesn't cache stuff before writing * - * @return Boolean + * @return bool * @access public */ function _stream_flush() @@ -646,7 +657,7 @@ function _stream_flush() /** * Retrieve information about a file resource * - * @return Mixed + * @return mixed * @access public */ function _stream_stat() @@ -661,8 +672,8 @@ function _stream_stat() /** * Delete a file * - * @param String $path - * @return Boolean + * @param string $path + * @return bool * @access public */ function _unlink($path) @@ -682,9 +693,9 @@ function _unlink($path) * might be worthwhile to reconstruct bits 12-16 (ie. the file type) if mode doesn't have them but we'll * cross that bridge when and if it's reached * - * @param String $path - * @param Integer $flags - * @return Mixed + * @param string $path + * @param int $flags + * @return mixed * @access public */ function _url_stat($path, $flags) @@ -705,8 +716,8 @@ function _url_stat($path, $flags) /** * Truncate stream * - * @param Integer $new_size - * @return Boolean + * @param int $new_size + * @return bool * @access public */ function _stream_truncate($new_size) @@ -727,10 +738,10 @@ function _stream_truncate($new_size) * STREAM_OPTION_WRITE_BUFFER isn't supported for the same reason stream_flush isn't. * The other two aren't supported because of limitations in \phpseclib\Net\SFTP. * - * @param Integer $option - * @param Integer $arg1 - * @param Integer $arg2 - * @return Boolean + * @param int $option + * @param int $arg1 + * @param int $arg2 + * @return bool * @access public */ function _stream_set_option($option, $arg1, $arg2) @@ -757,9 +768,9 @@ function _stream_close() * If NET_SFTP_STREAM_LOGGING is defined all calls will be output on the screen and then (regardless of whether or not * NET_SFTP_STREAM_LOGGING is enabled) the parameters will be passed through to the appropriate method. * - * @param String - * @param Array - * @return Mixed + * @param string + * @param array + * @return mixed * @access public */ function __call($name, $arguments) diff --git a/phpseclib/phpseclib/phpseclib/Net/SSH1.php b/phpseclib/phpseclib/phpseclib/Net/SSH1.php index 918c791e1..cc108a94f 100644 --- a/phpseclib/phpseclib/phpseclib/Net/SSH1.php +++ b/phpseclib/phpseclib/phpseclib/Net/SSH1.php @@ -78,24 +78,24 @@ class SSH1 * IDEA in CFB mode * * Not supported. - */ + */ const CIPHER_IDEA = 1; /** * DES in CBC mode - */ + */ const CIPHER_DES = 2; /** * Triple-DES in CBC mode * * All implementations are required to support this - */ + */ const CIPHER_3DES = 3; /** * TRI's Simple Stream encryption CBC * * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, does define it (see cipher.h), * although it doesn't use it (see cipher.c) - */ + */ const CIPHER_BROKEN_TSS = 4; /** * RC4 @@ -111,14 +111,14 @@ class SSH1 * * This library currently only supports encryption when the same key is being used for both directions. This is * because there's only one $crypto object. Two could be added ($encrypt and $decrypt, perhaps). - */ + */ const CIPHER_RC4 = 5; /** * Blowfish * * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, defines it (see cipher.h) and * uses it (see cipher.c) - */ + */ const CIPHER_BLOWFISH = 6; /**#@-*/ @@ -130,21 +130,21 @@ class SSH1 */ /** * .rhosts or /etc/hosts.equiv - */ + */ const AUTH_RHOSTS = 1; /** * pure RSA authentication - */ + */ const AUTH_RSA = 2; /** * password authentication * * This is the only method that is supported by this library. - */ + */ const AUTH_PASSWORD = 3; /** * .rhosts with RSA host authentication - */ + */ const AUTH_RHOSTS_RSA = 4; /**#@-*/ @@ -162,7 +162,7 @@ class SSH1 * * @see \phpseclib\Net\SSH1::_get_binary_packet() * @access private - */ + */ const RESPONSE_TYPE = 1; /** @@ -170,7 +170,7 @@ class SSH1 * * @see \phpseclib\Net\SSH1::_get_binary_packet() * @access private - */ + */ const RESPONSE_DATA = 2; /**#@+ @@ -191,19 +191,19 @@ class SSH1 */ /** * Returns the message numbers - */ + */ const LOG_SIMPLE = 1; /** * Returns the message content - */ + */ const LOG_COMPLEX = 2; /** * Outputs the content real-time - */ + */ const LOG_REALTIME = 3; /** * Dumps the content real-time to a file - */ + */ const LOG_REALTIME_FILE = 4; /**#@-*/ @@ -213,18 +213,18 @@ class SSH1 */ /** * Returns when a string matching $expect exactly is found - */ + */ const READ_SIMPLE = 1; /** * Returns when a string matching the regular expression $expect is found - */ + */ const READ_REGEX = 2; /**#@-*/ /** * The SSH identifier * - * @var String + * @var string * @access private */ var $identifier = 'SSH-1.5-phpseclib'; @@ -232,7 +232,7 @@ class SSH1 /** * The Socket Object * - * @var Object + * @var object * @access private */ var $fsock; @@ -240,7 +240,7 @@ class SSH1 /** * The cryptography object * - * @var Object + * @var object * @access private */ var $crypto = false; @@ -251,7 +251,7 @@ class SSH1 * The bits that are set represent functions that have been called already. This is used to determine * if a requisite function has been successfully executed. If not, an error should be thrown. * - * @var Integer + * @var int * @access private */ var $bitmap = 0; @@ -261,8 +261,8 @@ class SSH1 * * Logged for debug purposes * - * @see \phpseclib\Net\SSH1::getServerKeyPublicExponent() - * @var String + * @see self::getServerKeyPublicExponent() + * @var string * @access private */ var $server_key_public_exponent; @@ -272,8 +272,8 @@ class SSH1 * * Logged for debug purposes * - * @see \phpseclib\Net\SSH1::getServerKeyPublicModulus() - * @var String + * @see self::getServerKeyPublicModulus() + * @var string * @access private */ var $server_key_public_modulus; @@ -283,8 +283,8 @@ class SSH1 * * Logged for debug purposes * - * @see \phpseclib\Net\SSH1::getHostKeyPublicExponent() - * @var String + * @see self::getHostKeyPublicExponent() + * @var string * @access private */ var $host_key_public_exponent; @@ -294,8 +294,8 @@ class SSH1 * * Logged for debug purposes * - * @see \phpseclib\Net\SSH1::getHostKeyPublicModulus() - * @var String + * @see self::getHostKeyPublicModulus() + * @var string * @access private */ var $host_key_public_modulus; @@ -305,8 +305,8 @@ class SSH1 * * Logged for debug purposes * - * @see \phpseclib\Net\SSH1::getSupportedCiphers() - * @var Array + * @see self::getSupportedCiphers() + * @var array * @access private */ var $supported_ciphers = array( @@ -324,8 +324,8 @@ class SSH1 * * Logged for debug purposes * - * @see \phpseclib\Net\SSH1::getSupportedAuthentications() - * @var Array + * @see self::getSupportedAuthentications() + * @var array * @access private */ var $supported_authentications = array( @@ -338,8 +338,8 @@ class SSH1 /** * Server Identification * - * @see \phpseclib\Net\SSH1::getServerIdentification() - * @var String + * @see self::getServerIdentification() + * @var string * @access private */ var $server_identification = ''; @@ -347,8 +347,8 @@ class SSH1 /** * Protocol Flags * - * @see \phpseclib\Net\SSH1::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $protocol_flags = array(); @@ -356,8 +356,8 @@ class SSH1 /** * Protocol Flag Log * - * @see \phpseclib\Net\SSH1::getLog() - * @var Array + * @see self::getLog() + * @var array * @access private */ var $protocol_flag_log = array(); @@ -365,8 +365,8 @@ class SSH1 /** * Message Log * - * @see \phpseclib\Net\SSH1::getLog() - * @var Array + * @see self::getLog() + * @var array * @access private */ var $message_log = array(); @@ -374,8 +374,8 @@ class SSH1 /** * Real-time log file pointer * - * @see \phpseclib\Net\SSH1::_append_log() - * @var Resource + * @see self::_append_log() + * @var resource * @access private */ var $realtime_log_file; @@ -383,8 +383,8 @@ class SSH1 /** * Real-time log file size * - * @see \phpseclib\Net\SSH1::_append_log() - * @var Integer + * @see self::_append_log() + * @var int * @access private */ var $realtime_log_size; @@ -392,8 +392,8 @@ class SSH1 /** * Real-time log file wrap boolean * - * @see \phpseclib\Net\SSH1::_append_log() - * @var Boolean + * @see self::_append_log() + * @var bool * @access private */ var $realtime_log_wrap; @@ -401,8 +401,8 @@ class SSH1 /** * Interactive Buffer * - * @see \phpseclib\Net\SSH1::read() - * @var Array + * @see self::read() + * @var array * @access private */ var $interactiveBuffer = ''; @@ -410,7 +410,7 @@ class SSH1 /** * Timeout * - * @see \phpseclib\Net\SSH1::setTimeout() + * @see self::setTimeout() * @access private */ var $timeout; @@ -418,7 +418,7 @@ class SSH1 /** * Current Timeout * - * @see \phpseclib\Net\SSH1::_get_channel_packet() + * @see self::_get_channel_packet() * @access private */ var $curTimeout; @@ -426,7 +426,7 @@ class SSH1 /** * Log Boundary * - * @see \phpseclib\Net\SSH1::_format_log + * @see self::_format_log() * @access private */ var $log_boundary = ':'; @@ -434,7 +434,7 @@ class SSH1 /** * Log Long Width * - * @see \phpseclib\Net\SSH1::_format_log + * @see self::_format_log() * @access private */ var $log_long_width = 65; @@ -442,7 +442,7 @@ class SSH1 /** * Log Short Width * - * @see \phpseclib\Net\SSH1::_format_log + * @see self::_format_log() * @access private */ var $log_short_width = 16; @@ -450,9 +450,9 @@ class SSH1 /** * Hostname * - * @see \phpseclib\Net\SSH1::__construct() - * @see \phpseclib\Net\SSH1::_connect() - * @var String + * @see self::__construct() + * @see self::_connect() + * @var string * @access private */ var $host; @@ -460,9 +460,9 @@ class SSH1 /** * Port Number * - * @see \phpseclib\Net\SSH1::__construct() - * @see \phpseclib\Net\SSH1::_connect() - * @var Integer + * @see self::__construct() + * @see self::_connect() + * @var int * @access private */ var $port; @@ -475,9 +475,9 @@ class SSH1 * however, is non-optional. There will be a timeout, whether or not you set it. If you don't it'll be * 10 seconds. It is used by fsockopen() in that function. * - * @see \phpseclib\Net\SSH1::__construct() - * @see \phpseclib\Net\SSH1::_connect() - * @var Integer + * @see self::__construct() + * @see self::_connect() + * @var int * @access private */ var $connectionTimeout; @@ -485,9 +485,9 @@ class SSH1 /** * Default cipher * - * @see \phpseclib\Net\SSH1::__construct() - * @see \phpseclib\Net\SSH1::_connect() - * @var Integer + * @see self::__construct() + * @see self::_connect() + * @var int * @access private */ var $cipher; @@ -497,10 +497,10 @@ class SSH1 * * Connects to an SSHv1 server * - * @param String $host - * @param optional Integer $port - * @param optional Integer $timeout - * @param optional Integer $cipher + * @param string $host + * @param int $port + * @param int $timeout + * @param int $cipher * @return \phpseclib\Net\SSH1 * @access public */ @@ -536,7 +536,7 @@ function __construct($host, $port = 22, $timeout = 10, $cipher = self::CIPHER_3D /** * Connect to an SSHv1 server * - * @return Boolean + * @return bool * @access private */ function _connect() @@ -694,9 +694,9 @@ function _connect() /** * Login * - * @param String $username - * @param optional String $password - * @return Boolean + * @param string $username + * @param string $password + * @return bool * @access public */ function login($username, $password = '') @@ -767,7 +767,7 @@ function login($username, $password = '') * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. * Setting $timeout to false or 0 will mean there is no timeout. * - * @param Mixed $timeout + * @param mixed $timeout */ function setTimeout($timeout) { @@ -788,9 +788,9 @@ function setTimeout($timeout) * * Returns false on failure and the output, otherwise. * - * @see \phpseclib\Net\SSH1::interactiveRead() - * @see \phpseclib\Net\SSH1::interactiveWrite() - * @param String $cmd + * @see self::interactiveRead() + * @see self::interactiveWrite() + * @param string $cmd * @return mixed * @access public */ @@ -838,9 +838,9 @@ function exec($cmd, $block = true) /** * Creates an interactive shell * - * @see \phpseclib\Net\SSH1::interactiveRead() - * @see \phpseclib\Net\SSH1::interactiveWrite() - * @return Boolean + * @see self::interactiveRead() + * @see self::interactiveWrite() + * @return bool * @access private */ function _initShell() @@ -882,9 +882,9 @@ function _initShell() /** * Inputs a command into an interactive shell. * - * @see \phpseclib\Net\SSH1::interactiveWrite() - * @param String $cmd - * @return Boolean + * @see self::interactiveWrite() + * @param string $cmd + * @return bool * @access public */ function write($cmd) @@ -898,10 +898,10 @@ function write($cmd) * $expect can take the form of a string literal or, if $mode == self::READ__REGEX, * a regular expression. * - * @see \phpseclib\Net\SSH1::write() - * @param String $expect - * @param Integer $mode - * @return Boolean + * @see self::write() + * @param string $expect + * @param int $mode + * @return bool * @access public */ function read($expect, $mode = self::READ__SIMPLE) @@ -938,9 +938,9 @@ function read($expect, $mode = self::READ__SIMPLE) /** * Inputs a command into an interactive shell. * - * @see \phpseclib\Net\SSH1::interactiveRead() - * @param String $cmd - * @return Boolean + * @see self::interactiveRead() + * @param string $cmd + * @return bool * @access public */ function interactiveWrite($cmd) @@ -974,8 +974,8 @@ function interactiveWrite($cmd) * does not support ANSI escape sequences in Win32 Console applications", so if you're a Windows user, * there's not going to be much recourse. * - * @see \phpseclib\Net\SSH1::interactiveRead() - * @return String + * @see self::interactiveRead() + * @return string * @access public */ function interactiveRead() @@ -1026,7 +1026,7 @@ function __destruct() /** * Disconnect * - * @param String $msg + * @param string $msg * @access private */ function _disconnect($msg = 'Client Quit') @@ -1063,8 +1063,8 @@ function _disconnect($msg = 'Client Quit') * Also, this function could be improved upon by adding detection for the following exploit: * http://www.securiteam.com/securitynews/5LP042K3FY.html * - * @see \phpseclib\Net\SSH1::_send_binary_packet() - * @return Array + * @see self::_send_binary_packet() + * @return array * @access private */ function _get_binary_packet() @@ -1139,9 +1139,9 @@ function _get_binary_packet() * * Returns true on success, false on failure. * - * @see \phpseclib\Net\SSH1::_get_binary_packet() - * @param String $data - * @return Boolean + * @see self::_get_binary_packet() + * @param string $data + * @return bool * @access private */ function _send_binary_packet($data) @@ -1186,10 +1186,10 @@ function _send_binary_packet($data) * we've reimplemented it. A more detailed discussion of the differences can be found after * $crc_lookup_table's initialization. * - * @see \phpseclib\Net\SSH1::_get_binary_packet() - * @see \phpseclib\Net\SSH1::_send_binary_packet() - * @param String $data - * @return Integer + * @see self::_get_binary_packet() + * @see self::_send_binary_packet() + * @param string $data + * @return int * @access private */ function _crc($data) @@ -1284,9 +1284,9 @@ function _crc($data) * * Inspired by array_shift * - * @param String $string - * @param optional Integer $index - * @return String + * @param string $string + * @param int $index + * @return string * @access private */ function _string_shift(&$string, $index = 1) @@ -1303,9 +1303,9 @@ function _string_shift(&$string, $index = 1) * should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that * calls this call modexp, instead, but I think this makes things clearer, maybe... * - * @see \phpseclib\Net\SSH1::__construct() + * @see self::__construct() * @param BigInteger $m - * @param Array $key + * @param array $key * @return BigInteger * @access private */ @@ -1354,7 +1354,7 @@ function _rsa_crypt($m, $key) * named constants from it, using the value as the name of the constant and the index as the value of the constant. * If any of the constants that would be defined already exists, none of the constants will be defined. * - * @param Array $array + * @param array $array * @access private */ function _define_array() @@ -1377,7 +1377,7 @@ function _define_array() * Returns a string if NET_SSH1_LOGGING == self::LOG_COMPLEX, an array if NET_SSH1_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH1_LOGGING') * * @access public - * @return String or Array + * @return array|false|string */ function getLog() { @@ -1400,10 +1400,10 @@ function getLog() /** * Formats a log for printing * - * @param Array $message_log - * @param Array $message_number_log + * @param array $message_log + * @param array $message_number_log * @access private - * @return String + * @return string */ function _format_log($message_log, $message_number_log) { @@ -1436,9 +1436,9 @@ function _format_log($message_log, $message_number_log) * * For use with preg_replace_callback() * - * @param Array $matches + * @param array $matches * @access private - * @return String + * @return string */ function _format_log_helper($matches) { @@ -1451,8 +1451,8 @@ function _format_log_helper($matches) * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * - * @param optional Boolean $raw_output - * @return String + * @param bool $raw_output + * @return string * @access public */ function getServerKeyPublicExponent($raw_output = false) @@ -1466,8 +1466,8 @@ function getServerKeyPublicExponent($raw_output = false) * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * - * @param optional Boolean $raw_output - * @return String + * @param bool $raw_output + * @return string * @access public */ function getServerKeyPublicModulus($raw_output = false) @@ -1481,8 +1481,8 @@ function getServerKeyPublicModulus($raw_output = false) * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * - * @param optional Boolean $raw_output - * @return String + * @param bool $raw_output + * @return string * @access public */ function getHostKeyPublicExponent($raw_output = false) @@ -1496,8 +1496,8 @@ function getHostKeyPublicExponent($raw_output = false) * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * - * @param optional Boolean $raw_output - * @return String + * @param bool $raw_output + * @return string * @access public */ function getHostKeyPublicModulus($raw_output = false) @@ -1512,8 +1512,8 @@ function getHostKeyPublicModulus($raw_output = false) * is set to true, returns, instead, an array of constants. ie. instead of array('Triple-DES in CBC mode'), you'll * get array(self::CIPHER_3DES). * - * @param optional Boolean $raw_output - * @return Array + * @param bool $raw_output + * @return array * @access public */ function getSupportedCiphers($raw_output = false) @@ -1528,8 +1528,8 @@ function getSupportedCiphers($raw_output = false) * is set to true, returns, instead, an array of constants. ie. instead of array('password authentication'), you'll * get array(self::AUTH_PASSWORD). * - * @param optional Boolean $raw_output - * @return Array + * @param bool $raw_output + * @return array * @access public */ function getSupportedAuthentications($raw_output = false) @@ -1540,7 +1540,7 @@ function getSupportedAuthentications($raw_output = false) /** * Return the server identification. * - * @return String + * @return string * @access public */ function getServerIdentification() @@ -1553,7 +1553,7 @@ function getServerIdentification() * * Makes sure that only the last 1MB worth of packets will be logged * - * @param String $data + * @param string $data * @access private */ function _append_log($protocol_flags, $message) diff --git a/phpseclib/phpseclib/phpseclib/Net/SSH2.php b/phpseclib/phpseclib/phpseclib/Net/SSH2.php index c25fb1ee2..115807550 100644 --- a/phpseclib/phpseclib/phpseclib/Net/SSH2.php +++ b/phpseclib/phpseclib/phpseclib/Net/SSH2.php @@ -112,19 +112,19 @@ class SSH2 */ /** * Returns the message numbers - */ + */ const LOG_SIMPLE = 1; /** * Returns the message content - */ + */ const LOG_COMPLEX = 2; /** * Outputs the content real-time - */ + */ const LOG_REALTIME = 3; /** * Dumps the content real-time to a file - */ + */ const LOG_REALTIME_FILE = 4; /**#@-*/ @@ -134,22 +134,22 @@ class SSH2 */ /** * Returns when a string matching $expect exactly is found - */ + */ const READ_SIMPLE = 1; /** * Returns when a string matching the regular expression $expect is found - */ + */ const READ_REGEX = 2; /** * Make sure that the log never gets larger than this - */ + */ const LOG_MAX_SIZE = 1048576; // 1024 * 1024 /**#@-*/ /** * The SSH identifier * - * @var String + * @var string * @access private */ var $identifier; @@ -157,7 +157,7 @@ class SSH2 /** * The Socket Object * - * @var Object + * @var object * @access private */ var $fsock; @@ -168,7 +168,7 @@ class SSH2 * The bits that are set represent functions that have been called already. This is used to determine * if a requisite function has been successfully executed. If not, an error should be thrown. * - * @var Integer + * @var int * @access private */ var $bitmap = 0; @@ -176,9 +176,9 @@ class SSH2 /** * Error information * - * @see \phpseclib\Net\SSH2::getErrors() - * @see \phpseclib\Net\SSH2::getLastError() - * @var String + * @see self::getErrors() + * @see self::getLastError() + * @var string * @access private */ var $errors = array(); @@ -186,8 +186,8 @@ class SSH2 /** * Server Identifier * - * @see \phpseclib\Net\SSH2::getServerIdentification() - * @var mixed false or Array + * @see self::getServerIdentification() + * @var array|false * @access private */ var $server_identifier = false; @@ -195,8 +195,8 @@ class SSH2 /** * Key Exchange Algorithms * - * @see \phpseclib\Net\SSH2::getKexAlgorithims() - * @var mixed false or Array + * @see self::getKexAlgorithims() + * @var array|false * @access private */ var $kex_algorithms = false; @@ -204,8 +204,8 @@ class SSH2 /** * Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods * - * @see Net_SSH2::_key_exchange() - * @var Integer + * @see self::_key_exchange() + * @var int * @access private */ var $kex_dh_group_size_min = 1536; @@ -213,8 +213,8 @@ class SSH2 /** * Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods * - * @see Net_SSH2::_key_exchange() - * @var Integer + * @see self::_key_exchange() + * @var int * @access private */ var $kex_dh_group_size_preferred = 2048; @@ -222,8 +222,8 @@ class SSH2 /** * Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods * - * @see Net_SSH2::_key_exchange() - * @var Integer + * @see self::_key_exchange() + * @var int * @access private */ var $kex_dh_group_size_max = 4096; @@ -231,8 +231,8 @@ class SSH2 /** * Server Host Key Algorithms * - * @see \phpseclib\Net\SSH2::getServerHostKeyAlgorithms() - * @var mixed false or Array + * @see self::getServerHostKeyAlgorithms() + * @var array|false * @access private */ var $server_host_key_algorithms = false; @@ -240,8 +240,8 @@ class SSH2 /** * Encryption Algorithms: Client to Server * - * @see \phpseclib\Net\SSH2::getEncryptionAlgorithmsClient2Server() - * @var mixed false or Array + * @see self::getEncryptionAlgorithmsClient2Server() + * @var array|false * @access private */ var $encryption_algorithms_client_to_server = false; @@ -249,8 +249,8 @@ class SSH2 /** * Encryption Algorithms: Server to Client * - * @see \phpseclib\Net\SSH2::getEncryptionAlgorithmsServer2Client() - * @var mixed false or Array + * @see self::getEncryptionAlgorithmsServer2Client() + * @var array|false * @access private */ var $encryption_algorithms_server_to_client = false; @@ -258,8 +258,8 @@ class SSH2 /** * MAC Algorithms: Client to Server * - * @see \phpseclib\Net\SSH2::getMACAlgorithmsClient2Server() - * @var mixed false or Array + * @see self::getMACAlgorithmsClient2Server() + * @var array|false * @access private */ var $mac_algorithms_client_to_server = false; @@ -267,8 +267,8 @@ class SSH2 /** * MAC Algorithms: Server to Client * - * @see \phpseclib\Net\SSH2::getMACAlgorithmsServer2Client() - * @var mixed false or Array + * @see self::getMACAlgorithmsServer2Client() + * @var array|false * @access private */ var $mac_algorithms_server_to_client = false; @@ -276,8 +276,8 @@ class SSH2 /** * Compression Algorithms: Client to Server * - * @see \phpseclib\Net\SSH2::getCompressionAlgorithmsClient2Server() - * @var mixed false or Array + * @see self::getCompressionAlgorithmsClient2Server() + * @var array|false * @access private */ var $compression_algorithms_client_to_server = false; @@ -285,8 +285,8 @@ class SSH2 /** * Compression Algorithms: Server to Client * - * @see \phpseclib\Net\SSH2::getCompressionAlgorithmsServer2Client() - * @var mixed false or Array + * @see self::getCompressionAlgorithmsServer2Client() + * @var array|false * @access private */ var $compression_algorithms_server_to_client = false; @@ -294,8 +294,8 @@ class SSH2 /** * Languages: Server to Client * - * @see \phpseclib\Net\SSH2::getLanguagesServer2Client() - * @var mixed false or Array + * @see self::getLanguagesServer2Client() + * @var array|false * @access private */ var $languages_server_to_client = false; @@ -303,8 +303,8 @@ class SSH2 /** * Languages: Client to Server * - * @see \phpseclib\Net\SSH2::getLanguagesClient2Server() - * @var mixed false or Array + * @see self::getLanguagesClient2Server() + * @var array|false * @access private */ var $languages_client_to_server = false; @@ -319,9 +319,9 @@ class SSH2 * * -- http://tools.ietf.org/html/rfc4253#section-6 * - * @see \phpseclib\Net\SSH2::__construct() - * @see \phpseclib\Net\SSH2::_send_binary_packet() - * @var Integer + * @see self::__construct() + * @see self::_send_binary_packet() + * @var int * @access private */ var $encrypt_block_size = 8; @@ -329,9 +329,9 @@ class SSH2 /** * Block Size for Client to Server Encryption * - * @see \phpseclib\Net\SSH2::__construct() - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @var Integer + * @see self::__construct() + * @see self::_get_binary_packet() + * @var int * @access private */ var $decrypt_block_size = 8; @@ -339,8 +339,8 @@ class SSH2 /** * Server to Client Encryption Object * - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @var Object + * @see self::_get_binary_packet() + * @var object * @access private */ var $decrypt = false; @@ -348,8 +348,8 @@ class SSH2 /** * Client to Server Encryption Object * - * @see \phpseclib\Net\SSH2::_send_binary_packet() - * @var Object + * @see self::_send_binary_packet() + * @var object * @access private */ var $encrypt = false; @@ -357,8 +357,8 @@ class SSH2 /** * Client to Server HMAC Object * - * @see \phpseclib\Net\SSH2::_send_binary_packet() - * @var Object + * @see self::_send_binary_packet() + * @var object * @access private */ var $hmac_create = false; @@ -366,8 +366,8 @@ class SSH2 /** * Server to Client HMAC Object * - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @var Object + * @see self::_get_binary_packet() + * @var object * @access private */ var $hmac_check = false; @@ -379,8 +379,8 @@ class SSH2 * For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is * append it. * - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @var Integer + * @see self::_get_binary_packet() + * @var int * @access private */ var $hmac_size = false; @@ -388,14 +388,14 @@ class SSH2 /** * Server Public Host Key * - * @see \phpseclib\Net\SSH2::getServerPublicHostKey() - * @var String + * @see self::getServerPublicHostKey() + * @var string * @access private */ var $server_public_host_key; /** - * Session identifer + * Session identifier * * "The exchange hash H from the first key exchange is additionally * used as the session identifier, which is a unique identifier for @@ -403,8 +403,8 @@ class SSH2 * * -- http://tools.ietf.org/html/rfc4253#section-7.2 * - * @see \phpseclib\Net\SSH2::_key_exchange() - * @var String + * @see self::_key_exchange() + * @var string * @access private */ var $session_id = false; @@ -414,8 +414,8 @@ class SSH2 * * The current exchange hash * - * @see \phpseclib\Net\SSH2::_key_exchange() - * @var String + * @see self::_key_exchange() + * @var string * @access private */ var $exchange_hash = false; @@ -423,8 +423,8 @@ class SSH2 /** * Message Numbers * - * @see \phpseclib\Net\SSH2::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $message_numbers = array(); @@ -432,8 +432,8 @@ class SSH2 /** * Disconnection Message 'reason codes' defined in RFC4253 * - * @see \phpseclib\Net\SSH2::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $disconnect_reasons = array(); @@ -441,8 +441,8 @@ class SSH2 /** * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254 * - * @see \phpseclib\Net\SSH2::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $channel_open_failure_reasons = array(); @@ -451,8 +451,8 @@ class SSH2 * Terminal Modes * * @link http://tools.ietf.org/html/rfc4254#section-8 - * @see \phpseclib\Net\SSH2::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $terminal_modes = array(); @@ -461,8 +461,8 @@ class SSH2 * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes * * @link http://tools.ietf.org/html/rfc4254#section-5.2 - * @see \phpseclib\Net\SSH2::__construct() - * @var Array + * @see self::__construct() + * @var array * @access private */ var $channel_extended_data_type_codes = array(); @@ -472,8 +472,8 @@ class SSH2 * * See 'Section 6.4. Data Integrity' of rfc4253 for more info. * - * @see \phpseclib\Net\SSH2::_send_binary_packet() - * @var Integer + * @see self::_send_binary_packet() + * @var int * @access private */ var $send_seq_no = 0; @@ -483,8 +483,8 @@ class SSH2 * * See 'Section 6.4. Data Integrity' of rfc4253 for more info. * - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @var Integer + * @see self::_get_binary_packet() + * @var int * @access private */ var $get_seq_no = 0; @@ -494,9 +494,9 @@ class SSH2 * * Maps client channels to server channels * - * @see \phpseclib\Net\SSH2::_get_channel_packet() - * @see \phpseclib\Net\SSH2::exec() - * @var Array + * @see self::_get_channel_packet() + * @see self::exec() + * @var array * @access private */ var $server_channels = array(); @@ -507,9 +507,9 @@ class SSH2 * If a client requests a packet from one channel but receives two packets from another those packets should * be placed in a buffer * - * @see \phpseclib\Net\SSH2::_get_channel_packet() - * @see \phpseclib\Net\SSH2::exec() - * @var Array + * @see self::_get_channel_packet() + * @see self::exec() + * @var array * @access private */ var $channel_buffers = array(); @@ -519,8 +519,8 @@ class SSH2 * * Contains the type of the last sent message * - * @see \phpseclib\Net\SSH2::_get_channel_packet() - * @var Array + * @see self::_get_channel_packet() + * @var array * @access private */ var $channel_status = array(); @@ -530,8 +530,8 @@ class SSH2 * * Maximum packet size indexed by channel * - * @see \phpseclib\Net\SSH2::_send_channel_packet() - * @var Array + * @see self::_send_channel_packet() + * @var array * @access private */ var $packet_size_client_to_server = array(); @@ -539,8 +539,8 @@ class SSH2 /** * Message Number Log * - * @see \phpseclib\Net\SSH2::getLog() - * @var Array + * @see self::getLog() + * @var array * @access private */ var $message_number_log = array(); @@ -548,8 +548,8 @@ class SSH2 /** * Message Log * - * @see \phpseclib\Net\SSH2::getLog() - * @var Array + * @see self::getLog() + * @var array * @access private */ var $message_log = array(); @@ -559,9 +559,9 @@ class SSH2 * * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB) * - * @var Integer - * @see \phpseclib\Net\SSH2::_send_channel_packet() - * @see \phpseclib\Net\SSH2::exec() + * @var int + * @see self::_send_channel_packet() + * @see self::exec() * @access private */ var $window_size = 0x7FFFFFFF; @@ -571,8 +571,8 @@ class SSH2 * * Window size indexed by channel * - * @see \phpseclib\Net\SSH2::_send_channel_packet() - * @var Array + * @see self::_send_channel_packet() + * @var array * @access private */ var $window_size_server_to_client = array(); @@ -582,8 +582,8 @@ class SSH2 * * Window size indexed by channel * - * @see \phpseclib\Net\SSH2::_get_channel_packet() - * @var Array + * @see self::_get_channel_packet() + * @var array * @access private */ var $window_size_client_to_server = array(); @@ -593,8 +593,8 @@ class SSH2 * * Verified against $this->session_id * - * @see \phpseclib\Net\SSH2::getServerPublicHostKey() - * @var String + * @see self::getServerPublicHostKey() + * @var string * @access private */ var $signature = ''; @@ -604,8 +604,8 @@ class SSH2 * * ssh-rsa or ssh-dss. * - * @see \phpseclib\Net\SSH2::getServerPublicHostKey() - * @var String + * @see self::getServerPublicHostKey() + * @var string * @access private */ var $signature_format = ''; @@ -613,8 +613,8 @@ class SSH2 /** * Interactive Buffer * - * @see \phpseclib\Net\SSH2::read() - * @var Array + * @see self::read() + * @var array * @access private */ var $interactiveBuffer = ''; @@ -624,9 +624,9 @@ class SSH2 * * Should never exceed self::LOG_MAX_SIZE * - * @see \phpseclib\Net\SSH2::_send_binary_packet() - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @var Integer + * @see self::_send_binary_packet() + * @see self::_get_binary_packet() + * @var int * @access private */ var $log_size; @@ -634,7 +634,7 @@ class SSH2 /** * Timeout * - * @see \phpseclib\Net\SSH2::setTimeout() + * @see self::setTimeout() * @access private */ var $timeout; @@ -642,7 +642,7 @@ class SSH2 /** * Current Timeout * - * @see \phpseclib\Net\SSH2::_get_channel_packet() + * @see self::_get_channel_packet() * @access private */ var $curTimeout; @@ -650,8 +650,8 @@ class SSH2 /** * Real-time log file pointer * - * @see \phpseclib\Net\SSH2::_append_log() - * @var Resource + * @see self::_append_log() + * @var resource * @access private */ var $realtime_log_file; @@ -659,8 +659,8 @@ class SSH2 /** * Real-time log file size * - * @see \phpseclib\Net\SSH2::_append_log() - * @var Integer + * @see self::_append_log() + * @var int * @access private */ var $realtime_log_size; @@ -668,8 +668,8 @@ class SSH2 /** * Has the signature been validated? * - * @see \phpseclib\Net\SSH2::getServerPublicHostKey() - * @var Boolean + * @see self::getServerPublicHostKey() + * @var bool * @access private */ var $signature_validated = false; @@ -677,7 +677,7 @@ class SSH2 /** * Real-time log file wrap boolean * - * @see \phpseclib\Net\SSH2::_append_log() + * @see self::_append_log() * @access private */ var $realtime_log_wrap; @@ -685,7 +685,7 @@ class SSH2 /** * Flag to suppress stderr from output * - * @see \phpseclib\Net\SSH2::enableQuietMode() + * @see self::enableQuietMode() * @access private */ var $quiet_mode = false; @@ -693,7 +693,7 @@ class SSH2 /** * Time of first network activity * - * @var Integer + * @var int * @access private */ var $last_packet; @@ -701,7 +701,7 @@ class SSH2 /** * Exit status returned from ssh if any * - * @var Integer + * @var int * @access private */ var $exit_status; @@ -709,8 +709,8 @@ class SSH2 /** * Flag to request a PTY when using exec() * - * @var Boolean - * @see \phpseclib\Net\SSH2::enablePTY() + * @var bool + * @see self::enablePTY() * @access private */ var $request_pty = false; @@ -718,7 +718,7 @@ class SSH2 /** * Flag set while exec() is running when using enablePTY() * - * @var Boolean + * @var bool * @access private */ var $in_request_pty_exec = false; @@ -726,7 +726,7 @@ class SSH2 /** * Flag set after startSubsystem() is called * - * @var Boolean + * @var bool * @access private */ var $in_subsystem; @@ -734,7 +734,7 @@ class SSH2 /** * Contents of stdError * - * @var String + * @var string * @access private */ var $stdErrorLog; @@ -742,8 +742,8 @@ class SSH2 /** * The Last Interactive Response * - * @see \phpseclib\Net\SSH2::_keyboard_interactive_process() - * @var String + * @see self::_keyboard_interactive_process() + * @var string * @access private */ var $last_interactive_response = ''; @@ -751,8 +751,8 @@ class SSH2 /** * Keyboard Interactive Request / Responses * - * @see \phpseclib\Net\SSH2::_keyboard_interactive_process() - * @var Array + * @see self::_keyboard_interactive_process() + * @var array * @access private */ var $keyboard_requests_responses = array(); @@ -763,9 +763,9 @@ class SSH2 * Quoting from the RFC, "in some jurisdictions, sending a warning message before * authentication may be relevant for getting legal protection." * - * @see \phpseclib\Net\SSH2::_filter() - * @see \phpseclib\Net\SSH2::getBannerMessage() - * @var String + * @see self::_filter() + * @see self::getBannerMessage() + * @var string * @access private */ var $banner_message = ''; @@ -773,8 +773,8 @@ class SSH2 /** * Did read() timeout or return normally? * - * @see \phpseclib\Net\SSH2::isTimeout() - * @var Boolean + * @see self::isTimeout() + * @var bool * @access private */ var $is_timeout = false; @@ -782,8 +782,8 @@ class SSH2 /** * Log Boundary * - * @see \phpseclib\Net\SSH2::_format_log() - * @var String + * @see self::_format_log() + * @var string * @access private */ var $log_boundary = ':'; @@ -791,8 +791,8 @@ class SSH2 /** * Log Long Width * - * @see \phpseclib\Net\SSH2::_format_log() - * @var Integer + * @see self::_format_log() + * @var int * @access private */ var $log_long_width = 65; @@ -800,8 +800,8 @@ class SSH2 /** * Log Short Width * - * @see \phpseclib\Net\SSH2::_format_log() - * @var Integer + * @see self::_format_log() + * @var int * @access private */ var $log_short_width = 16; @@ -809,9 +809,9 @@ class SSH2 /** * Hostname * - * @see \phpseclib\Net\SSH2::__construct() - * @see \phpseclib\Net\SSH2::_connect() - * @var String + * @see self::__construct() + * @see self::_connect() + * @var string * @access private */ var $host; @@ -819,9 +819,9 @@ class SSH2 /** * Port Number * - * @see \phpseclib\Net\SSH2::__construct() - * @see \phpseclib\Net\SSH2::_connect() - * @var Integer + * @see self::__construct() + * @see self::_connect() + * @var int * @access private */ var $port; @@ -829,10 +829,10 @@ class SSH2 /** * Number of columns for terminal window size * - * @see \phpseclib\Net\SSH2::getWindowColumns() - * @see \phpseclib\Net\SSH2::setWindowColumns() - * @see \phpseclib\Net\SSH2::setWindowSize() - * @var Integer + * @see self::getWindowColumns() + * @see self::setWindowColumns() + * @see self::setWindowSize() + * @var int * @access private */ var $windowColumns = 80; @@ -840,10 +840,10 @@ class SSH2 /** * Number of columns for terminal window size * - * @see \phpseclib\Net\SSH2::getWindowRows() - * @see \phpseclib\Net\SSH2::setWindowRows() - * @see \phpseclib\Net\SSH2::setWindowSize() - * @var Integer + * @see self::getWindowRows() + * @see self::setWindowRows() + * @see self::setWindowSize() + * @var int * @access private */ var $windowRows = 24; @@ -851,9 +851,9 @@ class SSH2 /** * Crypto Engine * - * @see Net_SSH2::setCryptoEngine() - * @see Net_SSH2::_key_exchange() - * @var Integer + * @see self::setCryptoEngine() + * @see self::_key_exchange() + * @var int * @access private */ var $crypto_engine = false; @@ -871,10 +871,10 @@ class SSH2 * * $host can either be a string, representing the host, or a stream resource. * - * @param Mixed $host - * @param optional Integer $port - * @param optional Integer $timeout - * @see \phpseclib\Net\SSH2::login() + * @param mixed $host + * @param int $port + * @param int $timeout + * @see self::login() * @return \phpseclib\Net\SSH2 * @access public */ @@ -977,7 +977,7 @@ function __construct($host, $port = 22, $timeout = 10) * Possible $engine values: * CRYPT_MODE_INTERNAL, CRYPT_MODE_MCRYPT * - * @param Integer $engine + * @param int $engine * @access private */ function setCryptoEngine($engine) @@ -988,7 +988,7 @@ function setCryptoEngine($engine) /** * Connect to an SSHv2 server * - * @return Boolean + * @return bool * @access private */ function _connect() @@ -1028,35 +1028,51 @@ function _connect() Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients MUST be able to process such lines." */ - $temp = ''; - $extra = ''; - while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) { - if (substr($temp, -2) == "\r\n") { - $extra.= $temp; - $temp = ''; - } - - if ($this->curTimeout) { - if ($this->curTimeout < 0) { - $this->is_timeout = true; - return false; + $data = ''; + while (!feof($this->fsock) && !preg_match('#(.*)^(SSH-(\d\.\d+).*)#ms', $data, $matches)) { + $line = ''; + while (true) { + if ($this->curTimeout) { + if ($this->curTimeout < 0) { + $this->is_timeout = true; + return false; + } + $read = array($this->fsock); + $write = $except = null; + $start = microtime(true); + $sec = floor($this->curTimeout); + $usec = 1000000 * ($this->curTimeout - $sec); + // on windows this returns a "Warning: Invalid CRT parameters detected" error + // the !count() is done as a workaround for + if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { + $this->is_timeout = true; + return false; + } + $elapsed = microtime(true) - $start; + $this->curTimeout-= $elapsed; } - $read = array($this->fsock); - $write = $except = null; - $start = microtime(true); - $sec = floor($this->curTimeout); - $usec = 1000000 * ($this->curTimeout - $sec); - // on windows this returns a "Warning: Invalid CRT parameters detected" error - // the !count() is done as a workaround for - if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { - $this->is_timeout = true; - return false; + + $temp = stream_get_line($this->fsock, 255, "\n"); + if (strlen($temp) == 255) { + continue; } - $elapsed = microtime(true) - $start; - $this->curTimeout-= $elapsed; + + $line.= "$temp\n"; + + // quoting RFC4253, "Implementers who wish to maintain + // compatibility with older, undocumented versions of this protocol may + // want to process the identification string without expecting the + // presence of the carriage return character for reasons described in + // Section 5 of this document." + + //if (substr($line, -2) == "\r\n") { + // break; + //} + + break; } - $temp.= fgets($this->fsock, 255); + $data.= $line; } if (feof($this->fsock)) { @@ -1064,20 +1080,22 @@ function _connect() return false; } + $extra = $matches[1]; + $this->identifier = $this->_generate_identifier(); if (defined('NET_SSH2_LOGGING')) { - $this->_append_log('<-', $extra . $temp); + $this->_append_log('<-', $matches[0]); $this->_append_log('->', $this->identifier . "\r\n"); } $this->server_identifier = trim($temp, "\r\n"); if (strlen($extra)) { - $this->errors[] = utf8_decode($extra); + $this->errors[] = utf8_decode($data); } - if ($matches[1] != '1.99' && $matches[1] != '2.0') { - user_error("Cannot connect to SSH $matches[1] servers"); + if ($matches[3] != '1.99' && $matches[3] != '2.0') { + user_error("Cannot connect to SSH $matches[3] servers"); return false; } @@ -1109,7 +1127,7 @@ function _connect() * You should overwrite this method in your own class if you want to use another identifier * * @access protected - * @return String + * @return string */ function _generate_identifier() { @@ -1142,12 +1160,12 @@ function _generate_identifier() /** * Key Exchange * - * @param String $kexinit_payload_server + * @param string $kexinit_payload_server * @access private */ function _key_exchange($kexinit_payload_server) { - static $kex_algorithms = array( + $kex_algorithms = array( // Elliptic Curve Diffie-Hellman Key Agreement (ECDH) using // Curve25519. See doc/curve25519-sha256@libssh.org.txt in the // libssh repository for more information. @@ -1160,97 +1178,94 @@ function _key_exchange($kexinit_payload_server) 'diffie-hellman-group-exchange-sha1', // RFC 4419 'diffie-hellman-group-exchange-sha256', // RFC 4419 ); - if (!class_exists('\Sodium')) { + if (!function_exists('\\Sodium\\library_version_major')) { $kex_algorithms = array_diff( $kex_algorithms, array('curve25519-sha256@libssh.org') ); } - static $server_host_key_algorithms = array( + $server_host_key_algorithms = array( 'ssh-rsa', // RECOMMENDED sign Raw RSA Key 'ssh-dss' // REQUIRED sign Raw DSS Key ); - static $encryption_algorithms = false; - if ($encryption_algorithms === false) { - $encryption_algorithms = array( - // from : - 'arcfour256', - 'arcfour128', + $encryption_algorithms = array( + // from : + 'arcfour256', + 'arcfour128', - //'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key + //'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key - // CTR modes from : - 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key - 'aes192-ctr', // RECOMMENDED AES with 192-bit key - 'aes256-ctr', // RECOMMENDED AES with 256-bit key + // CTR modes from : + 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key + 'aes192-ctr', // RECOMMENDED AES with 192-bit key + 'aes256-ctr', // RECOMMENDED AES with 256-bit key - 'twofish128-ctr', // OPTIONAL Twofish in SDCTR mode, with 128-bit key - 'twofish192-ctr', // OPTIONAL Twofish with 192-bit key - 'twofish256-ctr', // OPTIONAL Twofish with 256-bit key + 'twofish128-ctr', // OPTIONAL Twofish in SDCTR mode, with 128-bit key + 'twofish192-ctr', // OPTIONAL Twofish with 192-bit key + 'twofish256-ctr', // OPTIONAL Twofish with 256-bit key - 'aes128-cbc', // RECOMMENDED AES with a 128-bit key - 'aes192-cbc', // OPTIONAL AES with a 192-bit key - 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key + 'aes128-cbc', // RECOMMENDED AES with a 128-bit key + 'aes192-cbc', // OPTIONAL AES with a 192-bit key + 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key - 'twofish128-cbc', // OPTIONAL Twofish with a 128-bit key - 'twofish192-cbc', // OPTIONAL Twofish with a 192-bit key - 'twofish256-cbc', - 'twofish-cbc', // OPTIONAL alias for "twofish256-cbc" - // (this is being retained for historical reasons) + 'twofish128-cbc', // OPTIONAL Twofish with a 128-bit key + 'twofish192-cbc', // OPTIONAL Twofish with a 192-bit key + 'twofish256-cbc', + 'twofish-cbc', // OPTIONAL alias for "twofish256-cbc" + // (this is being retained for historical reasons) - 'blowfish-ctr', // OPTIONAL Blowfish in SDCTR mode + 'blowfish-ctr', // OPTIONAL Blowfish in SDCTR mode - 'blowfish-cbc', // OPTIONAL Blowfish in CBC mode + 'blowfish-cbc', // OPTIONAL Blowfish in CBC mode - '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode + '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode - '3des-cbc', // REQUIRED three-key 3DES in CBC mode - //'none' // OPTIONAL no encryption; NOT RECOMMENDED - ); + '3des-cbc', // REQUIRED three-key 3DES in CBC mode + //'none' // OPTIONAL no encryption; NOT RECOMMENDED + ); - if (extension_loaded('openssl') && !extension_loaded('mcrypt')) { - // OpenSSL does not support arcfour256 in any capacity and arcfour128 / arcfour support is limited to - // instances that do not use continuous buffers - $encryption_algorithms = array_diff( - $encryption_algorithms, - array('arcfour256', 'arcfour128', 'arcfour') - ); - } + if (extension_loaded('openssl') && !extension_loaded('mcrypt')) { + // OpenSSL does not support arcfour256 in any capacity and arcfour128 / arcfour support is limited to + // instances that do not use continuous buffers + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('arcfour256', 'arcfour128', 'arcfour') + ); + } - if (class_exists('\phpseclib\Crypt\RC4') === false) { - $encryption_algorithms = array_diff( - $encryption_algorithms, - array('arcfour256', 'arcfour128', 'arcfour') - ); - } - if (class_exists('\phpseclib\Crypt\Rijndael') === false) { - $encryption_algorithms = array_diff( - $encryption_algorithms, - array('aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc') - ); - } - if (class_exists('\phpseclib\Crypt\Twofish') === false) { - $encryption_algorithms = array_diff( - $encryption_algorithms, - array('twofish128-ctr', 'twofish192-ctr', 'twofish256-ctr', 'twofish128-cbc', 'twofish192-cbc', 'twofish256-cbc', 'twofish-cbc') - ); - } - if (class_exists('\phpseclib\Crypt\Blowfish') === false) { - $encryption_algorithms = array_diff( - $encryption_algorithms, - array('blowfish-ctr', 'blowfish-cbc') - ); - } - if (class_exists('\phpseclib\Crypt\TripleDES') === false) { - $encryption_algorithms = array_diff( - $encryption_algorithms, - array('3des-ctr', '3des-cbc') - ); - } - $encryption_algorithms = array_values($encryption_algorithms); + if (class_exists('\phpseclib\Crypt\RC4') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('arcfour256', 'arcfour128', 'arcfour') + ); + } + if (class_exists('\phpseclib\Crypt\Rijndael') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc') + ); + } + if (class_exists('\phpseclib\Crypt\Twofish') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('twofish128-ctr', 'twofish192-ctr', 'twofish256-ctr', 'twofish128-cbc', 'twofish192-cbc', 'twofish256-cbc', 'twofish-cbc') + ); } + if (class_exists('\phpseclib\Crypt\Blowfish') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('blowfish-ctr', 'blowfish-cbc') + ); + } + if (class_exists('\phpseclib\Crypt\TripleDES') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('3des-ctr', '3des-cbc') + ); + } + $encryption_algorithms = array_values($encryption_algorithms); $mac_algorithms = array( // from : @@ -1263,7 +1278,7 @@ function _key_exchange($kexinit_payload_server) //'none' // OPTIONAL no MAC; NOT RECOMMENDED ); - static $compression_algorithms = array( + $compression_algorithms = array( 'none' // REQUIRED no compression //'zlib' // OPTIONAL ZLIB (LZ77) compression ); @@ -1277,17 +1292,11 @@ function _key_exchange($kexinit_payload_server) )); } - static $str_kex_algorithms, $str_server_host_key_algorithms, - $encryption_algorithms_server_to_client, $mac_algorithms_server_to_client, $compression_algorithms_server_to_client, - $encryption_algorithms_client_to_server, $mac_algorithms_client_to_server, $compression_algorithms_client_to_server; - - if (empty($str_kex_algorithms)) { - $str_kex_algorithms = implode(',', $kex_algorithms); - $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms); - $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms); - $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms); - $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms); - } + $str_kex_algorithms = implode(',', $kex_algorithms); + $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms); + $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms); + $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms); + $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms); $client_cookie = Random::string(16); @@ -1391,7 +1400,7 @@ function _key_exchange($kexinit_payload_server) if ($kex_algorithm === 'curve25519-sha256@libssh.org') { $x = Random::string(32); - $eBytes = \Sodium::crypto_box_publickey_from_secretkey($x); + $eBytes = \Sodium\crypto_box_publickey_from_secretkey($x); $clientKexInitMessage = NET_SSH2_MSG_KEX_ECDH_INIT; $serverKexReplyMessage = NET_SSH2_MSG_KEX_ECDH_REPLY; $kexHash = new Hash('sha256'); @@ -1536,8 +1545,8 @@ function _key_exchange($kexinit_payload_server) user_error('Received curve25519 public key of invalid length.'); return false; } - $key = new BigInteger(\Sodium::crypto_scalarmult($x, $fBytes), 256); - \Sodium::sodium_memzero($x); + $key = new BigInteger(\Sodium\crypto_scalarmult($x, $fBytes), 256); + \Sodium\memzero($x); } else { $f = new BigInteger($fBytes, -256); $key = $f->modPow($x, $prime); @@ -1765,8 +1774,8 @@ function _key_exchange($kexinit_payload_server) /** * Maps an encryption algorithm name to the number of key bytes. * - * @param String $algorithm Name of the encryption algorithm - * @return Mixed Number of bytes as an integer or null for unknown + * @param string $algorithm Name of the encryption algorithm + * @return int|null Number of bytes as an integer or null for unknown * @access private */ function _encryption_algorithm_to_key_size($algorithm) @@ -1805,8 +1814,8 @@ function _encryption_algorithm_to_key_size($algorithm) * Maps an encryption algorithm name to an instance of a subclass of * \phpseclib\Crypt\Base. * - * @param String $algorithm Name of the encryption algorithm - * @return Mixed Instance of \phpseclib\Crypt\Base or null for unknown + * @param string $algorithm Name of the encryption algorithm + * @return mixed Instance of \phpseclib\Crypt\Base or null for unknown * @access private */ function _encryption_algorithm_to_crypt_instance($algorithm) @@ -1850,11 +1859,11 @@ function _encryption_algorithm_to_crypt_instance($algorithm) * * The $password parameter can be a plaintext password, a \phpseclib\Crypt\RSA object or an array * - * @param String $username - * @param Mixed $password - * @param Mixed $... - * @return Boolean - * @see _login + * @param string $username + * @param mixed $password + * @param mixed $... + * @return bool + * @see self::_login() * @access public */ function login($username) @@ -1866,11 +1875,11 @@ function login($username) /** * Login Helper * - * @param String $username - * @param Mixed $password - * @param Mixed $... - * @return Boolean - * @see _login_helper + * @param string $username + * @param mixed $password + * @param mixed $... + * @return bool + * @see self::_login_helper() * @access private */ function _login($username) @@ -1897,9 +1906,9 @@ function _login($username) /** * Login Helper * - * @param String $username - * @param optional String $password - * @return Boolean + * @param string $username + * @param string $password + * @return bool * @access private * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis} * by sending dummy SSH_MSG_IGNORE messages. @@ -2071,9 +2080,9 @@ function _login_helper($username, $password = null) * * See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details. This is not a full-featured keyboard-interactive authenticator. * - * @param String $username - * @param String $password - * @return Boolean + * @param string $username + * @param string $password + * @return bool * @access private */ function _keyboard_interactive_login($username, $password) @@ -2103,8 +2112,8 @@ function _keyboard_interactive_login($username, $password) /** * Handle the keyboard-interactive requests / responses. * - * @param String $responses... - * @return Boolean + * @param string $responses... + * @return bool * @access private */ function _keyboard_interactive_process() @@ -2217,9 +2226,9 @@ function _keyboard_interactive_process() /** * Login with an ssh-agent provided key * - * @param String $username + * @param string $username * @param \phpseclib\System\SSH\Agent $agent - * @return Boolean + * @return bool * @access private */ function _ssh_agent_login($username, $agent) @@ -2238,9 +2247,9 @@ function _ssh_agent_login($username, $agent) /** * Login with an RSA private key * - * @param String $username + * @param string $username * @param \phpseclib\Crypt\RSA $password - * @return Boolean + * @return bool * @access private * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis} * by sending dummy SSH_MSG_IGNORE messages. @@ -2345,7 +2354,7 @@ function _privatekey_login($username, $privatekey) * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. * Setting $timeout to false or 0 will mean there is no timeout. * - * @param Mixed $timeout + * @param mixed $timeout * @access public */ function setTimeout($timeout) @@ -2369,9 +2378,9 @@ function getStdError() * If $callback is set to false then \phpseclib\Net\SSH2::_get_channel_packet(self::CHANNEL_EXEC) will need to be called manually. * In all likelihood, this is not a feature you want to be taking advantage of. * - * @param String $command - * @param optional Callback $callback - * @return String + * @param string $command + * @param Callback $callback + * @return string * @access public */ function exec($command, $callback = null) @@ -2386,7 +2395,7 @@ function exec($command, $callback = null) // RFC4254 defines the (client) window size as "bytes the other party can send before it must wait for the window to // be adjusted". 0x7FFFFFFF is, at 2GB, the max size. technically, it should probably be decremented, but, - // honestly, if you're transfering more than 2GB, you probably shouldn't be using phpseclib, anyway. + // honestly, if you're transferring more than 2GB, you probably shouldn't be using phpseclib, anyway. // see http://tools.ietf.org/html/rfc4254#section-5.2 for more info $this->window_size_server_to_client[self::CHANNEL_EXEC] = $this->window_size; // 0x8000 is the maximum max packet size, per http://tools.ietf.org/html/rfc4253#section-6.1, although since PuTTy @@ -2516,9 +2525,9 @@ function exec($command, $callback = null) /** * Creates an interactive shell * - * @see \phpseclib\Net\SSH2::read() - * @see \phpseclib\Net\SSH2::write() - * @return Boolean + * @see self::read() + * @see self::write() + * @return bool * @access private */ function _initShell() @@ -2620,9 +2629,9 @@ function _initShell() /** * Return the channel to be used with read() / write() * - * @see \phpseclib\Net\SSH2::read() - * @see \phpseclib\Net\SSH2::write() - * @return Integer + * @see self::read() + * @see self::write() + * @return int * @access public */ function _get_interactive_channel() @@ -2640,7 +2649,7 @@ function _get_interactive_channel() /** * Return an available open channel * - * @return Integer + * @return int * @access public */ function _get_open_channel() @@ -2661,10 +2670,10 @@ function _get_open_channel() * Returns when there's a match for $expect, which can take the form of a string literal or, * if $mode == self::READ_REGEX, a regular expression. * - * @see \phpseclib\Net\SSH2::write() - * @param String $expect - * @param Integer $mode - * @return String + * @see self::write() + * @param string $expect + * @param int $mode + * @return string * @access public */ function read($expect = '', $mode = self::READ_SIMPLE) @@ -2707,9 +2716,9 @@ function read($expect = '', $mode = self::READ_SIMPLE) /** * Inputs a command into an interactive shell. * - * @see \phpseclib\Net\SSH2::read() - * @param String $cmd - * @return Boolean + * @see self::read() + * @param string $cmd + * @return bool * @access public */ function write($cmd) @@ -2736,9 +2745,9 @@ function write($cmd) * returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented * if there's sufficient demand for such a feature. * - * @see \phpseclib\Net\SSH2::stopSubsystem() - * @param String $subsystem - * @return Boolean + * @see self::stopSubsystem() + * @param string $subsystem + * @return bool * @access public */ function startSubsystem($subsystem) @@ -2799,8 +2808,8 @@ function startSubsystem($subsystem) /** * Stops a subsystem. * - * @see \phpseclib\Net\SSH2::startSubsystem() - * @return Boolean + * @see self::startSubsystem() + * @return bool * @access public */ function stopSubsystem() @@ -2863,7 +2872,7 @@ function __destruct() /** * Is the connection still active? * - * @return boolean + * @return bool * @access public */ function isConnected() @@ -2871,13 +2880,24 @@ function isConnected() return (bool) ($this->bitmap & self::MASK_CONNECTED); } + /** + * Have you successfully been logged in? + * + * @return bool + * @access public + */ + function isAuthenticated() + { + return (bool) ($this->bitmap & self::MASK_LOGIN); + } + /** * Gets Binary Packets * * See '6. Binary Packet Protocol' of rfc4253 for more info. * - * @see \phpseclib\Net\SSH2::_send_binary_packet() - * @return String + * @see self::_send_binary_packet() + * @return string * @access private */ function _get_binary_packet() @@ -2889,7 +2909,7 @@ function _get_binary_packet() } $start = microtime(true); - $raw = fread($this->fsock, $this->decrypt_block_size); + $raw = stream_get_contents($this->fsock, $this->decrypt_block_size); if (!strlen($raw)) { return ''; @@ -2917,7 +2937,7 @@ function _get_binary_packet() $buffer = ''; while ($remaining_length > 0) { - $temp = fread($this->fsock, $remaining_length); + $temp = stream_get_contents($this->fsock, $remaining_length); if ($temp === false || feof($this->fsock)) { user_error('Error reading from socket'); $this->bitmap = 0; @@ -2935,7 +2955,7 @@ function _get_binary_packet() $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty if ($this->hmac_check !== false) { - $hmac = fread($this->fsock, $this->hmac_size); + $hmac = stream_get_contents($this->fsock, $this->hmac_size); if ($hmac === false || strlen($hmac) != $this->hmac_size) { user_error('Error reading socket'); $this->bitmap = 0; @@ -2969,8 +2989,8 @@ function _get_binary_packet() * * Because some binary packets need to be ignored... * - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @return String + * @see self::_get_binary_packet() + * @return string * @access private */ function _filter($payload) @@ -3118,11 +3138,10 @@ function disableQuietMode() /** * Returns whether Quiet Mode is enabled or not * - * @see \phpseclib\Net\SSH2::enableQuietMode() - * @see \phpseclib\Net\SSH2::disableQuietMode() - * + * @see self::enableQuietMode() + * @see self::disableQuietMode() * @access public - * @return boolean + * @return bool */ function isQuietModeEnabled() { @@ -3152,11 +3171,10 @@ function disablePTY() /** * Returns whether request-pty is enabled or not * - * @see \phpseclib\Net\SSH2::enablePTY() - * @see \phpseclib\Net\SSH2::disablePTY() - * + * @see self::enablePTY() + * @see self::disablePTY() * @access public - * @return boolean + * @return bool */ function isPTYEnabled() { @@ -3169,7 +3187,7 @@ function isPTYEnabled() * Returns the data as a string if it's available and false if not. * * @param $client_channel - * @return Mixed + * @return mixed * @access private */ function _get_channel_packet($client_channel, $skip_extended = false) @@ -3369,7 +3387,9 @@ function _get_channel_packet($client_channel, $skip_extended = false) } $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_CLOSE; - return true; + if ($client_channel == $channel) { + return true; + } case NET_SSH2_MSG_CHANNEL_EOF: break; default: @@ -3384,10 +3404,10 @@ function _get_channel_packet($client_channel, $skip_extended = false) * * See '6. Binary Packet Protocol' of rfc4253 for more info. * - * @param String $data - * @param optional String $logged - * @see \phpseclib\Net\SSH2::_get_binary_packet() - * @return Boolean + * @param string $data + * @param string $logged + * @see self::_get_binary_packet() + * @return bool * @access private */ function _send_binary_packet($data, $logged = null) @@ -3445,7 +3465,7 @@ function _send_binary_packet($data, $logged = null) * * Makes sure that only the last 1MB worth of packets will be logged * - * @param String $data + * @param string $data * @access private */ function _append_log($message_number, $message) @@ -3521,9 +3541,9 @@ function _append_log($message_number, $message) * * Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate * - * @param Integer $client_channel - * @param String $data - * @return Boolean + * @param int $client_channel + * @param string $data + * @return bool * @access private */ function _send_channel_packet($client_channel, $data) @@ -3569,9 +3589,9 @@ function _send_channel_packet($client_channel, $data) * and for SFTP channels are presumably closed when the client disconnects. This functions is intended * for SCP more than anything. * - * @param Integer $client_channel - * @param Boolean $want_reply - * @return Boolean + * @param int $client_channel + * @param bool $want_reply + * @return bool * @access private */ function _close_channel($client_channel, $want_reply = false) @@ -3603,8 +3623,8 @@ function _close_channel($client_channel, $want_reply = false) /** * Disconnect * - * @param Integer $reason - * @return Boolean + * @param int $reason + * @return bool * @access private */ function _disconnect($reason) @@ -3623,9 +3643,9 @@ function _disconnect($reason) * * Inspired by array_shift * - * @param String $string - * @param optional Integer $index - * @return String + * @param string $string + * @param int $index + * @return string * @access private */ function _string_shift(&$string, $index = 1) @@ -3642,7 +3662,7 @@ function _string_shift(&$string, $index = 1) * named constants from it, using the value as the name of the constant and the index as the value of the constant. * If any of the constants that would be defined already exists, none of the constants will be defined. * - * @param Array $array + * @param array $array * @access private */ function _define_array() @@ -3665,7 +3685,7 @@ function _define_array() * Returns a string if NET_SSH2_LOGGING == self::LOG_COMPLEX, an array if NET_SSH2_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING') * * @access public - * @return String or Array + * @return array|false|string */ function getLog() { @@ -3688,10 +3708,10 @@ function getLog() /** * Formats a log for printing * - * @param Array $message_log - * @param Array $message_number_log + * @param array $message_log + * @param array $message_number_log * @access private - * @return String + * @return string */ function _format_log($message_log, $message_number_log) { @@ -3724,9 +3744,9 @@ function _format_log($message_log, $message_number_log) * * For use with preg_replace_callback() * - * @param Array $matches + * @param array $matches * @access private - * @return String + * @return string */ function _format_log_helper($matches) { @@ -3753,9 +3773,9 @@ function _on_channel_open() * Returns the first value of the intersection of two arrays or false if * the intersection is empty. The order is defined by the first parameter. * - * @param Array $array1 - * @param Array $array2 - * @return Mixed False if intersection is empty, else intersected value. + * @param array $array1 + * @param array $array2 + * @return mixed False if intersection is empty, else intersected value. * @access private */ function _array_intersect_first($array1, $array2) @@ -3771,7 +3791,7 @@ function _array_intersect_first($array1, $array2) /** * Returns all errors * - * @return String + * @return string[] * @access public */ function getErrors() @@ -3782,18 +3802,22 @@ function getErrors() /** * Returns the last error * - * @return String + * @return string * @access public */ function getLastError() { - return $this->errors[count($this->errors) - 1]; + $count = count($this->errors); + + if ($count > 0) { + return $this->errors[$count - 1]; + } } /** * Return the server identification. * - * @return String + * @return string * @access public */ function getServerIdentification() @@ -3806,7 +3830,7 @@ function getServerIdentification() /** * Return a list of the key exchange algorithms the server supports. * - * @return Array + * @return array * @access public */ function getKexAlgorithms() @@ -3819,7 +3843,7 @@ function getKexAlgorithms() /** * Return a list of the host key (public key) algorithms the server supports. * - * @return Array + * @return array * @access public */ function getServerHostKeyAlgorithms() @@ -3832,7 +3856,7 @@ function getServerHostKeyAlgorithms() /** * Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client. * - * @return Array + * @return array * @access public */ function getEncryptionAlgorithmsClient2Server() @@ -3845,7 +3869,7 @@ function getEncryptionAlgorithmsClient2Server() /** * Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client. * - * @return Array + * @return array * @access public */ function getEncryptionAlgorithmsServer2Client() @@ -3858,7 +3882,7 @@ function getEncryptionAlgorithmsServer2Client() /** * Return a list of the MAC algorithms the server supports, when receiving stuff from the client. * - * @return Array + * @return array * @access public */ function getMACAlgorithmsClient2Server() @@ -3871,7 +3895,7 @@ function getMACAlgorithmsClient2Server() /** * Return a list of the MAC algorithms the server supports, when sending stuff to the client. * - * @return Array + * @return array * @access public */ function getMACAlgorithmsServer2Client() @@ -3884,7 +3908,7 @@ function getMACAlgorithmsServer2Client() /** * Return a list of the compression algorithms the server supports, when receiving stuff from the client. * - * @return Array + * @return array * @access public */ function getCompressionAlgorithmsClient2Server() @@ -3897,7 +3921,7 @@ function getCompressionAlgorithmsClient2Server() /** * Return a list of the compression algorithms the server supports, when sending stuff to the client. * - * @return Array + * @return array * @access public */ function getCompressionAlgorithmsServer2Client() @@ -3910,7 +3934,7 @@ function getCompressionAlgorithmsServer2Client() /** * Return a list of the languages the server supports, when sending stuff to the client. * - * @return Array + * @return array * @access public */ function getLanguagesServer2Client() @@ -3923,7 +3947,7 @@ function getLanguagesServer2Client() /** * Return a list of the languages the server supports, when receiving stuff from the client. * - * @return Array + * @return array * @access public */ function getLanguagesClient2Server() @@ -3939,7 +3963,7 @@ function getLanguagesClient2Server() * Quoting from the RFC, "in some jurisdictions, sending a warning message before * authentication may be relevant for getting legal protection." * - * @return String + * @return string * @access public */ function getBannerMessage() @@ -3953,7 +3977,7 @@ function getBannerMessage() * Caching this the first time you connect to a server and checking the result on subsequent connections * is recommended. Returns false if the server signature is not signed correctly with the public host key. * - * @return Mixed + * @return mixed * @access public */ function getServerPublicHostKey() @@ -4094,7 +4118,7 @@ function getServerPublicHostKey() /** * Returns the exit status of an SSH command or false. * - * @return Integer or false + * @return false|int * @access public */ function getExitStatus() @@ -4108,7 +4132,7 @@ function getExitStatus() /** * Returns the number of columns for the terminal window size. * - * @return Integer + * @return int * @access public */ function getWindowColumns() @@ -4119,7 +4143,7 @@ function getWindowColumns() /** * Returns the number of rows for the terminal window size. * - * @return Integer + * @return int * @access public */ function getWindowRows() @@ -4130,7 +4154,7 @@ function getWindowRows() /** * Sets the number of columns for the terminal window size. * - * @param Integer $value + * @param int $value * @access public */ function setWindowColumns($value) @@ -4141,7 +4165,7 @@ function setWindowColumns($value) /** * Sets the number of rows for the terminal window size. * - * @param Integer $value + * @param int $value * @access public */ function setWindowRows($value) @@ -4152,8 +4176,8 @@ function setWindowRows($value) /** * Sets the number of columns and rows for the terminal window size. * - * @param Integer $columns - * @param Integer $rows + * @param int $columns + * @param int $rows * @access public */ function setWindowSize($columns = 80, $rows = 24) diff --git a/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php b/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php index 4cb9dec07..a4ff0549d 100644 --- a/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php +++ b/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php @@ -83,7 +83,7 @@ class Agent /** * Socket Resource * - * @var Resource + * @var resource * @access private */ var $fsock; @@ -143,7 +143,7 @@ function __construct() * See "2.5.2 Requesting a list of protocol 2 keys" * Returns an array containing zero or more \phpseclib\System\SSH\Agent\Identity objects * - * @return Array + * @return array * @access public */ function requestIdentities() @@ -168,14 +168,17 @@ function requestIdentities() for ($i = 0; $i < $keyCount; $i++) { $length = current(unpack('N', fread($this->fsock, 4))); $key_blob = fread($this->fsock, $length); + $key_str = 'ssh-rsa ' . base64_encode($key_blob); $length = current(unpack('N', fread($this->fsock, 4))); - $key_comment = fread($this->fsock, $length); + if ($length) { + $key_str.= ' ' . fread($this->fsock, $length); + } $length = current(unpack('N', substr($key_blob, 0, 4))); $key_type = substr($key_blob, 4, $length); switch ($key_type) { case 'ssh-rsa': $key = new RSA(); - $key->loadKey('ssh-rsa ' . base64_encode($key_blob) . ' ' . $key_comment); + $key->loadKey($key_str); break; case 'ssh-dss': // not currently supported @@ -199,7 +202,7 @@ function requestIdentities() * be requested when a channel is opened * * @param Net_SSH2 $ssh - * @return Boolean + * @return bool * @access public */ function startSSHForwarding($ssh) @@ -213,7 +216,7 @@ function startSSHForwarding($ssh) * Request agent forwarding of remote server * * @param Net_SSH2 $ssh - * @return Boolean + * @return bool * @access private */ function _request_forwarding($ssh) @@ -269,7 +272,7 @@ function _on_channel_open($ssh) /** * Forward data to SSH Agent and return data reply * - * @param String $data + * @param string $data * @return data from SSH Agent * @access private */ diff --git a/phpseclib/phpseclib/phpseclib/System/SSH/Agent/Identity.php b/phpseclib/phpseclib/phpseclib/System/SSH/Agent/Identity.php index 490edf6e6..b8cc6cded 100644 --- a/phpseclib/phpseclib/phpseclib/System/SSH/Agent/Identity.php +++ b/phpseclib/phpseclib/phpseclib/System/SSH/Agent/Identity.php @@ -23,9 +23,8 @@ * Instantiation should only be performed by \phpseclib\System\SSH\Agent class. * This could be thought of as implementing an interface that phpseclib\Crypt\RSA * implements. ie. maybe a Net_SSH_Auth_PublicKey interface or something. - * The methods in this interface would be getPublicKey, setSignatureMode - * and sign since those are the methods phpseclib looks for to perform - * public key authentication. + * The methods in this interface would be getPublicKey and sign since those are the + * methods phpseclib looks for to perform public key authentication. * * @package SSH\Agent * @author Jim Wigginton @@ -38,32 +37,32 @@ class Identity * * @var \phpseclib\Crypt\RSA * @access private - * @see \phpseclib\System\SSH\Agent\Identity::getPublicKey() + * @see self::getPublicKey() */ var $key; /** * Key Blob * - * @var String + * @var string * @access private - * @see \phpseclib\System\SSH\Agent\Identity::sign() + * @see self::sign() */ var $key_blob; /** * Socket Resource * - * @var Resource + * @var resource * @access private - * @see \phpseclib\System\SSH\Agent\Identity::sign() + * @see self::sign() */ var $fsock; /** * Default Constructor. * - * @param Resource $fsock + * @param resource $fsock * @return \phpseclib\System\SSH\Agent\Identity * @access private */ @@ -92,7 +91,7 @@ function setPublicKey($key) * Called by \phpseclib\System\SSH\Agent::requestIdentities(). The key blob could be extracted from $this->key * but this saves a small amount of computation. * - * @param String $key_blob + * @param string $key_blob * @access private */ function setPublicKeyBlob($key_blob) @@ -105,8 +104,8 @@ function setPublicKeyBlob($key_blob) * * Wrapper for $this->key->getPublicKey() * - * @param Integer $format optional - * @return Mixed + * @param int $format optional + * @return mixed * @access public */ function getPublicKey($format = null) @@ -120,7 +119,7 @@ function getPublicKey($format = null) * Doesn't do anything as ssh-agent doesn't let you pick and choose the signature mode. ie. * ssh-agent's only supported mode is \phpseclib\Crypt\RSA::SIGNATURE_PKCS1 * - * @param Integer $mode + * @param int $mode * @access public */ function setSignatureMode($mode) @@ -132,8 +131,8 @@ function setSignatureMode($mode) * * See "2.6.2 Protocol 2 private key signature request" * - * @param String $message - * @return String + * @param string $message + * @return string * @access public */ function sign($message) @@ -148,7 +147,7 @@ function sign($message) $length = current(unpack('N', fread($this->fsock, 4))); $type = ord(fread($this->fsock, 1)); if ($type != Agent::SSH_AGENT_SIGN_RESPONSE) { - user_error('Unable to retreive signature'); + user_error('Unable to retrieve signature'); } $signature_blob = fread($this->fsock, $length - 1); diff --git a/phpseclib/phpseclib/phpseclib/bootstrap.php b/phpseclib/phpseclib/phpseclib/bootstrap.php new file mode 100644 index 000000000..0da0999fd --- /dev/null +++ b/phpseclib/phpseclib/phpseclib/bootstrap.php @@ -0,0 +1,16 @@ +