* createKey());
+ * extract(\phpseclib\Crypt\RSA::createKey());
*
- * $plaintext = 'terrafrost';
+ * $plaintext = 'terrafrost';
*
- * $rsa->loadKey($privatekey);
- * $ciphertext = $rsa->encrypt($plaintext);
+ * $ciphertext = $publickey->encrypt($plaintext);
*
- * $rsa->loadKey($publickey);
- * echo $rsa->decrypt($ciphertext);
+ * echo $privatekey->decrypt($ciphertext);
* ?>
*
*
* Here's an example of how to create signatures and verify signatures with this library:
*
* createKey());
+ * extract(\phpseclib\Crypt\RSA::createKey());
*
- * $plaintext = 'terrafrost';
+ * $plaintext = 'terrafrost';
*
- * $rsa->loadKey($privatekey);
- * $signature = $rsa->sign($plaintext);
+ * $signature = $privatekey->sign($plaintext);
*
- * $rsa->loadKey($publickey);
- * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
+ * echo $publickey->verify($plaintext, $signature) ? 'verified' : 'unverified';
* ?>
*
*
@@ -51,6 +45,8 @@
namespace phpseclib\Crypt;
+use ParagonIE\ConstantTime\Base64;
+use phpseclib\File\ASN1;
use phpseclib\Math\BigInteger;
/**
@@ -71,26 +67,32 @@ class RSA
* Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
* (OAEP) for encryption / decryption.
*
- * Uses sha1 by default.
+ * Uses sha256 by default
*
* @see self::setHash()
* @see self::setMGFHash()
*/
- const ENCRYPTION_OAEP = 1;
+ const PADDING_OAEP = 1;
/**
* Use PKCS#1 padding.
*
- * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
+ * Although self::PADDING_OAEP / self::PADDING_PSS 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;
+ const PADDING_PKCS1 = 2;
/**
* Do not use any padding
*
* Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy
* stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.
*/
- const ENCRYPTION_NONE = 3;
+ const PADDING_NONE = 3;
+ /**
+ * Use PKCS#1 padding with PKCS1 v1.5 compatability
+ *
+ * A PKCS1 v2.1 encrypted message may not successfully decrypt with a PKCS1 v1.5 implementation (such as OpenSSL).
+ */
+ const PADDING_PKCS15_COMPAT = 6;
/**#@-*/
/**#@+
@@ -98,29 +100,27 @@ class RSA
* @see self::sign()
* @see self::verify()
* @see self::setHash()
- */
+ */
/**
* Use the Probabilistic Signature Scheme for signing
*
- * Uses sha1 by default.
+ * Uses sha256 and 0 as the salt length
*
* @see self::setSaltLength()
* @see self::setMGFHash()
+ * @see self::setHash()
*/
- const SIGNATURE_PSS = 1;
+ const PADDING_PSS = 4;
/**
- * 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.
+ * Use a relaxed version of PKCS#1 padding for signature verification
*/
- const SIGNATURE_PKCS1 = 2;
+ const PADDING_RELAXED_PKCS1 = 5;
/**#@-*/
/**#@+
* @access private
- * @see \phpseclib\Crypt\RSA::createKey()
- */
+ * @see self::createKey()
+ */
/**
* ASN1 Integer
*/
@@ -145,8 +145,8 @@ class RSA
/**#@+
* @access private
- * @see \phpseclib\Crypt\RSA::__construct()
- */
+ * @see self::__construct()
+ */
/**
* To use the pure-PHP implementation
*/
@@ -159,124 +159,37 @@ class RSA
const MODE_OPENSSL = 2;
/**#@-*/
- /**#@+
- * @access public
- * @see \phpseclib\Crypt\RSA::createKey()
- * @see \phpseclib\Crypt\RSA::setPrivateKeyFormat()
- */
- /**
- * 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 = 8;
- /**
- * OpenSSH formatted private key
- */
- const PRIVATE_FORMAT_OPENSSH = 9;
- /**#@-*/
-
- /**#@+
- * @access public
- * @see \phpseclib\Crypt\RSA::createKey()
- * @see \phpseclib\Crypt\RSA::setPublicKeyFormat()
- */
- /**
- * Raw public key
- *
- * An array containing two \phpseclib\Math\BigInteger objects.
- *
- * The exponent can be indexed with any of the following:
- *
- * 0, e, exponent, publicExponent
- *
- * 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)
- *
- * Used by File/X509.php
- *
- * Has the following header:
- *
- * -----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)
- *
- * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
- *
- * Has the following header:
- *
- * -----BEGIN PUBLIC KEY-----
- *
- * 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 \phpseclib\Math\BigInteger
+ * @var array
* @access private
*/
- var $zero;
+ static $zero;
/**
* Precomputed One
*
- * @var \phpseclib\Math\BigInteger
+ * @var array
* @access private
*/
- var $one;
+ static $one;
/**
* Private Key Format
*
- * @var int
+ * @var string
* @access private
*/
- var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
+ var $privateKeyFormat = 'PKCS1';
/**
* Public Key Format
*
- * @var int
- * @access public
+ * @var string
+ * @access private
*/
- var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
+ var $publicKeyFormat = 'PKCS8';
/**
* Modulus (ie. n)
@@ -374,22 +287,6 @@ class RSA
*/
var $mgfHLen;
- /**
- * Encryption mode
- *
- * @var int
- * @access private
- */
- var $encryptionMode = self::ENCRYPTION_OAEP;
-
- /**
- * Signature mode
- *
- * @var int
- * @access private
- */
- var $signatureMode = self::SIGNATURE_PSS;
-
/**
* Public Exponent
*
@@ -407,46 +304,69 @@ class RSA
var $password = false;
/**
- * Components
+ * Loaded File Format
*
- * 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 self::_start_element_handler()
- * @var array
+ * @var string
* @access private
*/
- var $components = array();
-
- /**
- * Current String
- *
- * For use with parsing XML formatted keys.
- *
- * @see self::_character_handler()
- * @see self::_stop_element_handler()
- * @var mixed
- * @access private
- */
- var $current;
+ var $format = false;
/**
* OpenSSL configuration file name.
*
* Set to null to use system configuration file.
+ *
* @see self::createKey()
* @var mixed
- * @Access public
+ * @access public
*/
- var $configFile;
+ static $configFile;
/**
- * Public key comment field.
+ * Supported file formats (lower case)
*
- * @var string
+ * @see self::_initialize_static_variables()
+ * @var array
* @access private
*/
- var $comment = 'phpseclib-generated-key';
+ static $fileFormats = false;
+
+ /**
+ * Supported file formats (original case)
+ *
+ * @see self::_initialize_static_variables()
+ * @var array
+ * @access private
+ */
+ static $origFileFormats = false;
+
+
+ /**
+ * Initialize static variables
+ *
+ * @access private
+ */
+ static function _initialize_static_variables()
+ {
+ if (!isset(self::$zero)) {
+ self::$zero= new BigInteger(0);
+ self::$one = new BigInteger(1);
+ self::$configFile = __DIR__ . '/../openssl.cnf';
+
+ if (self::$fileFormats === false) {
+ self::$fileFormats = array();
+ foreach (glob(__DIR__ . '/RSA/*.php') as $file) {
+ $name = pathinfo($file, PATHINFO_FILENAME);
+ $type = 'phpseclib\Crypt\RSA\\' . $name;
+ $meta = new \ReflectionClass($type);
+ if (!$meta->isAbstract()) {
+ self::$fileFormats[strtolower($name)] = $type;
+ self::$origFileFormats[] = $name;
+ }
+ }
+ }
+ }
+ }
/**
* The constructor
@@ -460,68 +380,12 @@ class RSA
*/
function __construct()
{
- $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
+ self::_initialize_static_variables();
- if (!defined('CRYPT_RSA_MODE')) {
- switch (true) {
- // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
- // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
- // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
- case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- break;
- case extension_loaded('openssl') && file_exists($this->configFile):
- // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
- $versions = array();
-
- // avoid generating errors (even with suppression) when phpinfo() is disabled (common in production systems)
- if (strpos(ini_get('disable_functions'), 'phpinfo') === false) {
- ob_start();
- @phpinfo();
- $content = ob_get_contents();
- ob_end_clean();
-
- preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches);
-
- if (!empty($matches[1])) {
- for ($i = 0; $i < count($matches[1]); $i++) {
- $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i])));
-
- // Remove letter part in OpenSSL version
- if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) {
- $versions[$matches[1][$i]] = $fullVersion;
- } else {
- $versions[$matches[1][$i]] = $m[0];
- }
- }
- }
- }
-
- // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+
- switch (true) {
- 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:
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
- }
- break;
- default:
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- }
- }
-
- $this->zero = new BigInteger();
- $this->one = new BigInteger(1);
-
- $this->hash = new Hash('sha1');
+ $this->hash = new Hash('sha256');
$this->hLen = $this->hash->getLength();
- $this->hashName = 'sha1';
- $this->mgfHash = new Hash('sha1');
+ $this->hashName = 'sha256';
+ $this->mgfHash = new Hash('sha256');
$this->mgfHLen = $this->mgfHash->getLength();
}
@@ -539,8 +403,26 @@ class RSA
* @param int $timeout
* @param array $p
*/
- function createKey($bits = 1024, $timeout = false, $partial = array())
+ static function createKey($bits = 2048, $timeout = false, $partial = array())
{
+ self::_initialize_static_variables();
+
+ if (!defined('CRYPT_RSA_MODE')) {
+ switch (true) {
+ // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
+ // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
+ // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
+ case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
+ define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
+ break;
+ case extension_loaded('openssl') && file_exists(self::$configFile):
+ define('CRYPT_RSA_MODE', self::MODE_OPENSSL);
+ break;
+ default:
+ define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
+ }
+ }
+
if (!defined('CRYPT_RSA_EXPONENT')) {
// http://en.wikipedia.org/wiki/65537_%28number%29
define('CRYPT_RSA_EXPONENT', '65537');
@@ -558,16 +440,17 @@ class RSA
// OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
if (CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
$config = array();
- if (isset($this->configFile)) {
- $config['config'] = $this->configFile;
+ if (isset(self::$configFile)) {
+ $config['config'] = self::$configFile;
}
$rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
- openssl_pkey_export($rsa, $privatekey, null, $config);
- $publickey = openssl_pkey_get_details($rsa);
- $publickey = $publickey['key'];
+ openssl_pkey_export($rsa, $privatekeystr, null, $config);
+ $privatekey = new RSA();
+ $privatekey->load($privatekeystr);
- $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, self::PRIVATE_FORMAT_PKCS1)));
- $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, self::PUBLIC_FORMAT_PKCS1)));
+ $publickeyarr = openssl_pkey_get_details($rsa);
+ $publickey = new RSA();
+ $publickey->load($publickeyarr['key']);
// clear the buffer of error strings stemming from a minimalistic openssl.cnf
while (openssl_error_string() !== false) {
@@ -585,7 +468,7 @@ class RSA
$e = new BigInteger(CRYPT_RSA_EXPONENT);
}
- extract($this->_generateMinMax($bits));
+ extract(self::_generateMinMax($bits));
$absoluteMin = $min;
$temp = $bits >> 1; // divide by two to see how many bits P and Q would be
if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
@@ -594,19 +477,17 @@ class RSA
} else {
$num_primes = 2;
}
- extract($this->_generateMinMax($temp + $bits % $temp));
+ extract(self::_generateMinMax($temp + $bits % $temp));
$finalMax = $max;
- extract($this->_generateMinMax($temp));
+ extract(self::_generateMinMax($temp));
- $generator = new BigInteger();
-
- $n = $this->one->copy();
+ $n = clone self::$one;
if (!empty($partial)) {
extract(unserialize($partial));
} else {
$exponents = $coefficients = $primes = array();
$lcm = array(
- 'top' => $this->one->copy(),
+ 'top' => clone self::$one,
'bottom' => false
);
}
@@ -635,12 +516,12 @@ class RSA
if ($i == $num_primes) {
list($min, $temp) = $absoluteMin->divide($n);
- if (!$temp->equals($this->zero)) {
- $min = $min->add($this->one); // ie. ceil()
+ if (!$temp->equals(self::$zero)) {
+ $min = $min->add(self::$one); // ie. ceil()
}
- $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
+ $primes[$i] = BigInteger::randomPrime($min, $finalMax, $timeout);
} else {
- $primes[$i] = $generator->randomPrime($min, $max, $timeout);
+ $primes[$i] = BigInteger::randomPrime($min, $max, $timeout);
}
if ($primes[$i] === false) { // if we've reached the timeout
@@ -657,8 +538,8 @@ class RSA
}
return array(
- 'privatekey' => '',
- 'publickey' => '',
+ 'privatekey' => false,
+ 'publickey' => false,
'partialkey' => $partialkey
);
}
@@ -671,7 +552,7 @@ class RSA
$n = $n->multiply($primes[$i]);
- $temp = $primes[$i]->subtract($this->one);
+ $temp = $primes[$i]->subtract(self::$one);
// textbook RSA implementations use Euler's totient function instead of the least common multiple.
// see http://en.wikipedia.org/wiki/Euler%27s_totient_function
@@ -684,7 +565,7 @@ class RSA
list($temp) = $lcm['top']->divide($lcm['bottom']);
$gcd = $temp->gcd($e);
$i0 = 1;
- } while (!$gcd->equals($this->one));
+ } while (!$gcd->equals(self::$one));
$d = $e->modInverse($temp);
@@ -703,842 +584,221 @@ class RSA
// coefficient INTEGER, -- (inverse of q) mod p
// otherPrimeInfos OtherPrimeInfos OPTIONAL
// }
+ $privatekey = new RSA();
+ $privatekey->modulus = $n;
+ $privatekey->k = $bits >> 3;
+ $privatekey->publicExponent = $e;
+ $privatekey->exponent = $d;
+ $privatekey->privateExponent = $e;
+ $privatekey->primes = $primes;
+ $privatekey->exponents = $exponents;
+ $privatekey->coefficients = $coefficients;
+
+ $publickey = new RSA();
+ $publickey->modulus = $n;
+ $publickey->k = $bits >> 3;
+ $publickey->exponent = $e;
return array(
- 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
- 'publickey' => $this->_convertPublicKey($n, $e),
+ 'privatekey' => $privatekey,
+ 'publickey' => $publickey,
'partialkey' => false
);
}
/**
- * Convert a private key to the appropriate format.
+ * Add a fileformat plugin
*
- * @access private
- * @see self::setPrivateKeyFormat()
- * @param string $RSAPrivateKey
- * @return string
+ * The plugin needs to either already be loaded or be auto-loadable.
+ * Loading a plugin whose shortname overwrite an existing shortname will overwrite the old plugin.
+ *
+ * @see self::load()
+ * @param string $fullname
+ * @access public
+ * @return bool
*/
- function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
+ static function addFileFormat($fullname)
{
- $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML;
- $num_primes = count($primes);
- $raw = array(
- 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
- 'modulus' => $n->toBytes($signed),
- 'publicExponent' => $e->toBytes($signed),
- 'privateExponent' => $d->toBytes($signed),
- 'prime1' => $primes[1]->toBytes($signed),
- 'prime2' => $primes[2]->toBytes($signed),
- 'exponent1' => $exponents[1]->toBytes($signed),
- 'exponent2' => $exponents[2]->toBytes($signed),
- 'coefficient' => $coefficients[2]->toBytes($signed)
- );
+ self::_initialize_static_variables();
- // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
- // call _convertPublicKey() instead.
- switch ($this->privateKeyFormat) {
- case self::PRIVATE_FORMAT_XML:
- if ($num_primes != 2) {
- return false;
- }
- return "' . base64_encode($raw['prime1']) . "
\r\n" . - '' . base64_encode($raw['prime2']) . "\r\n" . - '
' . $log . ''; + return $this->_format_log($this->message_log, $this->message_number_log); + break; default: return false; } @@ -4516,6 +3969,8 @@ class SSH2 * is recommended. Returns false if the server signature is not signed correctly with the public host key. * * @return mixed + * @throws \RuntimeException on badly formatted keys + * @throws \phpseclib\Exception\NoSupportedAlgorithmsException when the key isn't in a supported format * @access public */ function getServerPublicHostKey() @@ -4529,15 +3984,12 @@ class SSH2 $signature = $this->signature; $server_public_host_key = $this->server_public_host_key; - if (strlen($server_public_host_key) < 4) { - return false; - } extract(unpack('Nlength', $this->_string_shift($server_public_host_key, 4))); $this->_string_shift($server_public_host_key, $length); if ($this->signature_validated) { return $this->bitmap ? - $this->signature_format . ' ' . base64_encode($this->server_public_host_key) : + $this->signature_format . ' ' . Base64::encode($this->server_public_host_key) : false; } @@ -4547,27 +3999,15 @@ class SSH2 case 'ssh-dss': $zero = new BigInteger(); - if (strlen($server_public_host_key) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $p = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); - if (strlen($server_public_host_key) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $q = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); - if (strlen($server_public_host_key) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $g = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); - if (strlen($server_public_host_key) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $y = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); @@ -4576,8 +4016,8 @@ class SSH2 padding, unsigned, and in network byte order). */ $temp = unpack('Nlength', $this->_string_shift($signature, 4)); if ($temp['length'] != 40) { - user_error('Invalid signature'); - return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + throw new \RuntimeException('Invalid signature'); } $r = new BigInteger($this->_string_shift($signature, 20), 256); @@ -4588,8 +4028,8 @@ class SSH2 case $r->compare($q) >= 0: case $s->equals($zero): case $s->compare($q) >= 0: - user_error('Invalid signature'); - return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + throw new \RuntimeException('Invalid signature'); } $w = $s->modInverse($q); @@ -4608,60 +4048,33 @@ class SSH2 list(, $v) = $v->divide($q); if (!$v->equals($r)) { - user_error('Bad server signature'); + //user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } break; case 'ssh-rsa': - case 'rsa-sha2-256': - case 'rsa-sha2-512': - if (strlen($server_public_host_key) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $e = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); - if (strlen($server_public_host_key) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $rawN = $this->_string_shift($server_public_host_key, $temp['length']); $n = new BigInteger($rawN, -256); $nLength = strlen(ltrim($rawN, "\0")); /* - if (strlen($signature) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($signature, 4)); $signature = $this->_string_shift($signature, $temp['length']); $rsa = new RSA(); - switch ($this->signature_format) { - case 'rsa-sha2-512': - $hash = 'sha512'; - break; - case 'rsa-sha2-256': - $hash = 'sha256'; - break; - //case 'ssh-rsa': - default: - $hash = 'sha1'; - } - $rsa->setHash($hash); - $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1); - $rsa->loadKey(array('e' => $e, 'n' => $n), RSA::PUBLIC_FORMAT_RAW); - - if (!$rsa->verify($this->exchange_hash, $signature)) { - user_error('Bad server signature'); + $rsa->load(array('e' => $e, 'n' => $n), 'raw'); + $rsa->setHash('sha1'); + if (!$rsa->verify($this->exchange_hash, $signature, RSA::PADDING_PKCS1)) { + //user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } */ - if (strlen($signature) < 4) { - return false; - } $temp = unpack('Nlength', $this->_string_shift($signature, 4)); $s = new BigInteger($this->_string_shift($signature, $temp['length']), 256); @@ -4672,50 +4085,27 @@ class SSH2 // also, see SSHRSA.c (rsa2_verifysig) in PuTTy's source. if ($s->compare(new BigInteger()) < 0 || $s->compare($n->subtract(new BigInteger(1))) > 0) { - user_error('Invalid signature'); - return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + throw new \RuntimeException('Invalid signature'); } $s = $s->modPow($e, $n); $s = $s->toBytes(); - switch ($this->signature_format) { - case 'rsa-sha2-512': - $hash = 'sha512'; - break; - case 'rsa-sha2-256': - $hash = 'sha256'; - break; - //case 'ssh-rsa': - default: - $hash = 'sha1'; - } - $hashObj = new Hash($hash); - switch ($this->signature_format) { - case 'rsa-sha2-512': - $h = pack('N5a*', 0x00305130, 0x0D060960, 0x86480165, 0x03040203, 0x05000440, $hashObj->hash($this->exchange_hash)); - break; - case 'rsa-sha2-256': - $h = pack('N5a*', 0x00303130, 0x0D060960, 0x86480165, 0x03040201, 0x05000420, $hashObj->hash($this->exchange_hash)); - break; - //case 'ssh-rsa': - default: - $hash = 'sha1'; - $h = pack('N4a*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, $hashObj->hash($this->exchange_hash)); - } + $h = pack('N4H*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, sha1($this->exchange_hash)); $h = chr(0x01) . str_repeat(chr(0xFF), $nLength - 2 - strlen($h)) . $h; if ($s != $h) { - user_error('Bad server signature'); + //user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } break; default: - user_error('Unsupported signature format'); - return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); + $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); + throw new NoSupportedAlgorithmsException('Unsupported signature format'); } - return $this->signature_format . ' ' . base64_encode($this->server_public_host_key); + return $this->signature_format . ' ' . Base64::encode($this->server_public_host_key); } /** @@ -4788,4 +4178,47 @@ class SSH2 $this->windowColumns = $columns; $this->windowRows = $rows; } + + /** + * @return string + */ + function __toString() + { + return $this->getResourceId(); + } + + /** + * We use {} because that symbols should not be in URL according to + * {@link http://tools.ietf.org/html/rfc3986#section-2 RFC}. + * It will safe us from any conflicts, because otherwise regexp will + * match all alphanumeric domains. + * + * @return string + */ + function getResourceId() + { + return '{' . spl_object_hash($this) . '}'; + } + + /** + * Return existing connection + * + * @param string $id + * + * @return bool|SSH2 will return false if no such connection + */ + static function getConnectionByResourceId($id) + { + return isset(self::$connections[$id]) ? self::$connections[$id] : false; + } + + /** + * Return all excising connections + * + * @return SSH2[] + */ + static function getConnections() + { + return self::$connections; + } } diff --git a/vendor/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php b/vendor/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php index 99dcecfe62..23bf027a42 100644 --- a/vendor/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php +++ b/vendor/phpseclib/phpseclib/phpseclib/System/SSH/Agent.php @@ -33,7 +33,9 @@ namespace phpseclib\System\SSH; +use ParagonIE\ConstantTime\Base64; use phpseclib\Crypt\RSA; +use phpseclib\Exception\BadConfigurationException; use phpseclib\System\SSH\Agent\Identity; /** @@ -43,7 +45,7 @@ use phpseclib\System\SSH\Agent\Identity; * * @package SSH\Agent * @author Jim Wigginton