1
0
mirror of https://github.com/danog/phpseclib.git synced 2024-12-14 18:15:39 +01:00

Merge branch '3.0'

This commit is contained in:
terrafrost 2020-04-18 10:45:51 -05:00
commit e20b742eb0
30 changed files with 156 additions and 77 deletions

View File

@ -1,5 +1,15 @@
# Changelog
## 2.0.26 - 2020-03-22
- SFTP: another attempt at speeding up uploads (#1455)
- SSH2: try logging in with none as an auth method first (#1454)
- ASN1: fix for malformed ASN1 strings (#1456)
## 2.0.25 - 2020-02-25
- SFTP: re-add buffering (#1455)
## 2.0.24 - 2020-02-22
- X509: fix PHP 5.3 compatability issue

View File

@ -175,7 +175,7 @@ abstract class Strings
$result.= pack('N', $element);
break;
case 's':
if (!is_string($element)) {
if (!self::is_stringable($element)) {
throw new \InvalidArgumentException('A string was expected.');
}
$result.= pack('Na*', strlen($element), $element);
@ -372,4 +372,16 @@ abstract class Strings
return $var;
}
/**
* Find whether the type of a variable is string (or could be converted to one)
*
* @param string|object $var
* @return boolean
* @access public
*/
public static function is_stringable($var)
{
return is_string($var) || (is_object($var) && method_exists($var, '__toString'));
}
}

View File

@ -24,7 +24,7 @@ use phpseclib3\Crypt\DSA;
use phpseclib3\Crypt\ECDSA;
/**
* Base Class for all stream cipher classes
* Base Class for all asymmetric cipher classes
*
* @package AsymmetricKey
* @author Jim Wigginton <terrafrost@php.net>
@ -173,8 +173,8 @@ abstract class AsymmetricKey
}
$components['format'] = $format;
$new = static::onLoad($components);
$new->format = $format;
return $new instanceof PrivateKey ?
$new->withPassword($password) :
$new;
@ -206,6 +206,7 @@ abstract class AsymmetricKey
$components['format'] = $format;
$new = static::onLoad($components);
$new->format = $format;
return $new instanceof PrivateKey ?
$new->withPassword($password) :
$new;
@ -304,7 +305,7 @@ abstract class AsymmetricKey
* Returns the format of the loaded key.
*
* If the key that was loaded wasn't in a valid or if the key was auto-generated
* with RSA::createKey() then this will return false.
* with RSA::createKey() then this will throw an exception.
*
* @see self::load()
* @access public
@ -312,8 +313,8 @@ abstract class AsymmetricKey
*/
public function getLoadedFormat()
{
if ($this->format === false) {
return false;
if (empty($this->format)) {
throw new NoKeyLoadedException('This key was created with createKey - it was not loaded with load. Therefore there is no "loaded format"');
}
$meta = new \ReflectionClass($this->format);

View File

@ -70,7 +70,7 @@ abstract class OpenSSH
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -22,6 +22,7 @@ use phpseclib3\Crypt\AES;
use phpseclib3\Crypt\DES;
use phpseclib3\Crypt\TripleDES;
use phpseclib3\File\ASN1;
use phpseclib3\Common\Functions\Strings;
use phpseclib3\Exception\UnsupportedAlgorithmException;
/**
@ -127,7 +128,7 @@ abstract class PKCS1 extends PKCS
*/
protected static function load($key, $password)
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -37,6 +37,7 @@ use phpseclib3\Crypt\Random;
use phpseclib3\Math\BigInteger;
use phpseclib3\File\ASN1;
use phpseclib3\File\ASN1\Maps;
use phpseclib3\Common\Functions\Strings;
use phpseclib3\Exception\UnsupportedAlgorithmException;
/**
@ -331,25 +332,7 @@ abstract class PKCS8 extends PKCS
*/
protected static function load($key, $password = '')
{
self::initialize_static_variables();
if (!is_string($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}
if (self::$format != self::MODE_DER) {
$decoded = ASN1::extractBER($key);
if ($decoded !== false) {
$key = $decoded;
} elseif (self::$format == self::MODE_PEM) {
throw new \UnexpectedValueException('Expected base64-encoded PEM format but was unable to decode base64 text');
}
}
$decoded = ASN1::decodeBER($key);
if (empty($decoded)) {
throw new \RuntimeException('Unable to decode BER');
}
$decoded = self::preParse($key);
$meta = [];
@ -442,7 +425,7 @@ abstract class PKCS8 extends PKCS
if (isset($keyLength)) {
$params[] = (int) $keyLength->toString();
}
call_user_func_array([$cipher, 'setPassword'], $params);
$cipher->setPassword(...$params);
$key = $cipher->decrypt($decrypted['encryptedData']);
$decoded = ASN1::decodeBER($key);
if (empty($decoded)) {
@ -654,4 +637,65 @@ abstract class PKCS8 extends PKCS
chunk_split(Base64::encode($key), 64) .
"-----END PUBLIC KEY-----";
}
/**
* Perform some preliminary parsing of the key
*
* @param string $key
* @return array
*/
private static function preParse(&$key)
{
self::initialize_static_variables();
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}
if (self::$format != self::MODE_DER) {
$decoded = ASN1::extractBER($key);
if ($decoded !== false) {
$key = $decoded;
} elseif (self::$format == self::MODE_PEM) {
throw new \UnexpectedValueException('Expected base64-encoded PEM format but was unable to decode base64 text');
}
}
$decoded = ASN1::decodeBER($key);
if (empty($decoded)) {
throw new \RuntimeException('Unable to decode BER');
}
return $decoded;
}
/**
* Returns the encryption parameters used by the key
*
* @param string $key
* @return array
*/
public static function extractEncryptionAlgorithm($key)
{
$decoded = self::preParse($key);
$r = ASN1::asn1map($decoded[0], ASN1\Maps\EncryptedPrivateKeyInfo::MAP);
if (!is_array($r)) {
throw new \RuntimeException('Unable to parse using EncryptedPrivateKeyInfo map');
}
if ($r['encryptionAlgorithm']['algorithm'] == 'id-PBES2') {
$decoded = ASN1::decodeBER($r['encryptionAlgorithm']['parameters']->element);
$r['encryptionAlgorithm']['parameters'] = ASN1::asn1map($decoded[0], ASN1\Maps\PBES2params::MAP);
$kdf = &$r['encryptionAlgorithm']['parameters']['keyDerivationFunc'];
switch ($kdf['algorithm']) {
case 'id-PBKDF2':
$decoded = ASN1::decodeBER($kdf['parameters']->element);
$kdf['parameters'] = ASN1::asn1map($decoded[0], Maps\PBKDF2params::MAP);
}
}
return $r['encryptionAlgorithm'];
}
}

View File

@ -80,7 +80,7 @@ abstract class PuTTY
*/
public static function load($key, $password)
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}
@ -200,14 +200,14 @@ abstract class PuTTY
*/
protected static function wrapPrivateKey($public, $private, $type, $password, array $options = [])
{
$key = "PuTTY-User-Key-File-2: " . $type . "\r\nEncryption: ";
$encryption = (!empty($password) || is_string($password)) ? 'aes256-cbc' : 'none';
$key.= $encryption;
$key.= "\r\nComment: " . self::$comment . "\r\n";
$comment = isset($options['comment']) ? $options['comment'] : self::$comment;
$key = "PuTTY-User-Key-File-2: " . $type . "\r\nEncryption: "; $key.= $encryption;
$key.= "\r\nComment: " . $comment . "\r\n";
$public = Strings::packSSH2('s', $type) . $public;
$comment = isset($options['comment']) ? $options['comment'] : self::$comment;
$source = Strings::packSSH2('ssss', $type, $encryption, $comment, $public);
$public = Base64::encode($public);

View File

@ -25,6 +25,7 @@ use phpseclib3\Math\BigInteger;
use phpseclib3\Crypt\Common\Formats\Keys\PKCS8 as Progenitor;
use phpseclib3\File\ASN1;
use phpseclib3\File\ASN1\Maps;
use phpseclib3\Common\Functions\Strings;
/**
* PKCS#8 Formatted DH Key Handler
@ -69,7 +70,7 @@ abstract class PKCS8 extends Progenitor
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -95,7 +95,7 @@ abstract class DSA extends AsymmetricKey
* @var string
* @access private
*/
protected $format;
protected $sigFormat;
/**
* Signature Format (Short)
@ -263,7 +263,7 @@ abstract class DSA extends AsymmetricKey
*/
protected function __construct()
{
$this->format = self::validatePlugin('Signature', 'ASN1');
$this->sigFormat = self::validatePlugin('Signature', 'ASN1');
$this->shortFormat = 'ASN1';
parent::__construct();
@ -329,7 +329,7 @@ abstract class DSA extends AsymmetricKey
{
$new = clone $this;
$new->shortFormat = $format;
$new->format = self::validatePlugin('Signature', $format);
$new->sigFormat = self::validatePlugin('Signature', $format);
return $new;
}

View File

@ -29,6 +29,7 @@ use phpseclib3\Math\BigInteger;
use phpseclib3\Crypt\Common\Formats\Keys\PKCS8 as Progenitor;
use phpseclib3\File\ASN1;
use phpseclib3\File\ASN1\Maps;
use phpseclib3\Common\Functions\Strings;
/**
* PKCS#8 Formatted DSA Key Handler
@ -73,7 +74,7 @@ abstract class PKCS8 extends Progenitor
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -23,6 +23,7 @@ namespace phpseclib3\Crypt\DSA\Formats\Keys;
use ParagonIE\ConstantTime\Base64;
use phpseclib3\Math\BigInteger;
use phpseclib3\Common\Functions\Strings;
/**
* XML Formatted DSA Key Handler
@ -43,7 +44,7 @@ abstract class XML
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -85,7 +85,7 @@ class PrivateKey extends DSA implements Common\PrivateKey
*/
public function sign($message)
{
$format = $this->format;
$format = $this->sigFormat;
if (self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods())) {
$signature = '';

View File

@ -40,7 +40,7 @@ class PublicKey extends DSA implements Common\PublicKey
*/
public function verify($message, $signature)
{
$format = $this->format;
$format = $this->sigFormat;
$params = $format::load($signature);
if ($params === false || count($params) != 2) {

View File

@ -244,7 +244,7 @@ abstract class EC extends AsymmetricKey
*/
protected function __construct()
{
$this->format = self::validatePlugin('Signature', 'ASN1');
$this->sigFormat = self::validatePlugin('Signature', 'ASN1');
$this->shortFormat = 'ASN1';
parent::__construct();
@ -383,7 +383,7 @@ abstract class EC extends AsymmetricKey
$new = clone $this;
$new->shortFormat = $format;
$new->format = self::validatePlugin('Signature', $format);
$new->sigFormat = self::validatePlugin('Signature', $format);
return $new;
}

View File

@ -36,6 +36,7 @@ use phpseclib3\Math\Common\FiniteField\Integer;
use phpseclib3\Crypt\EC\Curves\Ed25519;
use phpseclib3\Crypt\EC\Curves\Ed448;
use phpseclib3\Exception\UnsupportedCurveException;
use phpseclib3\Common\Functions\Strings;
/**
* PKCS#8 Formatted EC Key Handler
@ -81,7 +82,7 @@ abstract class PKCS8 extends Progenitor
// one that's called
self::initialize_static_variables();
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -26,6 +26,7 @@ use phpseclib3\Crypt\EC\BaseCurves\Base as BaseCurve;
use phpseclib3\Crypt\EC\BaseCurves\Prime as PrimeCurve;
use phpseclib3\Crypt\EC\BaseCurves\TwistedEdwards as TwistedEdwardsCurve;
use phpseclib3\Crypt\EC\BaseCurves\Montgomery as MontgomeryCurve;
use phpseclib3\Common\Functions\Strings;
use phpseclib3\Exception\UnsupportedCurveException;
/**
@ -65,7 +66,7 @@ abstract class XML
{
self::initialize_static_variables();
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -100,7 +100,7 @@ class PrivateKey extends EC implements Common\PrivateKey
$order = $this->curve->getOrder();
$shortFormat = $this->shortFormat;
$format = $this->format;
$format = $this->sigFormat;
if ($format === false) {
return false;
}

View File

@ -52,7 +52,7 @@ class PublicKey extends EC implements Common\PublicKey
}
$shortFormat = $this->shortFormat;
$format = $this->format;
$format = $this->sigFormat;
if ($format === false) {
return false;
}

View File

@ -93,7 +93,7 @@ class Hash
* @var string
* @access private
*/
private $hash;
private $algo;
/**
* Key
@ -268,9 +268,9 @@ class Hash
return;
}
$this->computedKey = is_array($this->hash) ?
call_user_func($this->hash, $this->key) :
hash($this->hash, $this->key, true);
$this->computedKey = is_array($this->algo) ?
call_user_func($this->algo, $this->key) :
hash($this->algo, $this->key, true);
}
/**
@ -302,7 +302,7 @@ class Hash
case 'umac-128':
$this->blockSize = 128;
$this->length = abs(substr($hash, -3)) >> 3;
$this->hash = 'umac';
$this->algo = 'umac';
return;
case 'md2-96':
case 'md5-96':
@ -439,7 +439,7 @@ class Hash
$this->opad = str_repeat(chr(0x5C), $b);
}
$this->hash = $hash;
$this->algo = $hash;
$this->computeKey();
}
@ -785,7 +785,8 @@ class Hash
*/
public function hash($text)
{
if ($this->hash == 'umac') {
$algo = $this->algo;
if ($algo == 'umac') {
if ($this->recomputeAESKey) {
if (!is_string($this->nonce)) {
throw new InsufficientSetupException('No nonce has been set');
@ -837,9 +838,9 @@ class Hash
return $hashedmessage ^ $this->pad;
}
if (is_array($this->hash)) {
if (is_array($algo)) {
if (empty($this->key) || !is_string($this->key)) {
return substr(call_user_func($this->hash, $text, ...array_values($this->parameters)), 0, $this->length);
return substr($algo($text, ...array_values($this->parameters)), 0, $this->length);
}
// SHA3 HMACs are discussed at https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf#page=30
@ -847,17 +848,17 @@ class Hash
$key = str_pad($this->computedKey, $b, chr(0));
$temp = $this->ipad ^ $key;
$temp .= $text;
$temp = substr(call_user_func($this->hash, $temp, ...array_values($this->parameters)), 0, $this->length);
$temp = substr($algo($temp, ...array_values($this->parameters)), 0, $this->length);
$output = $this->opad ^ $key;
$output.= $temp;
$output = call_user_func($this->hash, $output, ...array_values($this->parameters));
$output = $algo($output, ...array_values($this->parameters));
return substr($output, 0, $this->length);
}
$output = !empty($this->key) || is_string($this->key) ?
hash_hmac($this->hash, $text, $this->computedKey, true) :
hash($this->hash, $text, true);
hash_hmac($algo, $text, $this->computedKey, true) :
hash($algo, $text, true);
return strlen($output) > $this->length
? substr($output, 0, $this->length)

View File

@ -393,7 +393,7 @@ class RC2 extends BlockCipher
$l[0] = self::$invpitable[$l[0]];
array_unshift($l, 'C*');
$this->key = call_user_func_array('pack', $l);
$this->key = pack(...$l);
$this->key_length = strlen($this->key);
$this->changed = $this->nonIVChanged = true;
$this->setEngine();

View File

@ -407,7 +407,6 @@ abstract class RSA extends AsymmetricKey
new PublicKey :
new PrivateKey;
$key->format = $components['format'];
$key->modulus = $components['modulus'];
$key->publicExponent = $components['publicExponent'];
$key->k = $key->modulus->getLengthInBytes();

View File

@ -76,7 +76,7 @@ abstract class MSBLOB
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -28,6 +28,7 @@ use phpseclib3\Math\BigInteger;
use phpseclib3\Crypt\Common\Formats\Keys\PKCS1 as Progenitor;
use phpseclib3\File\ASN1;
use phpseclib3\File\ASN1\Maps;
use phpseclib3\Common\Functions\Strings;
/**
* PKCS#1 Formatted RSA Key Handler
@ -48,7 +49,7 @@ abstract class PKCS1 extends Progenitor
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -30,6 +30,7 @@ namespace phpseclib3\Crypt\RSA\Formats\Keys;
use phpseclib3\Math\BigInteger;
use phpseclib3\Crypt\Common\Formats\Keys\PKCS8 as Progenitor;
use phpseclib3\File\ASN1;
use phpseclib3\Common\Functions\Strings;
/**
* PKCS#8 Formatted RSA Key Handler
@ -74,7 +75,7 @@ abstract class PKCS8 extends Progenitor
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -29,6 +29,7 @@ use phpseclib3\Math\BigInteger;
use phpseclib3\Crypt\Common\Formats\Keys\PKCS8 as Progenitor;
use phpseclib3\File\ASN1;
use phpseclib3\File\ASN1\Maps;
use phpseclib3\Common\Functions\Strings;
/**
* PKCS#8 Formatted RSA-PSS Key Handler
@ -107,7 +108,7 @@ abstract class PSS extends Progenitor
{
self::initialize_static_variables();
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -24,6 +24,7 @@ namespace phpseclib3\Crypt\RSA\Formats\Keys;
use ParagonIE\ConstantTime\Base64;
use phpseclib3\Math\BigInteger;
use phpseclib3\Common\Functions\Strings;
use phpseclib3\Exception\UnsupportedFormatException;
/**
@ -45,7 +46,7 @@ abstract class XML
*/
public static function load($key, $password = '')
{
if (!is_string($key)) {
if (!Strings::is_stringable($key)) {
throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}

View File

@ -553,7 +553,7 @@ abstract class ASN1
}
if (isset($value)) {
if (isset($special[$key])) {
$value = call_user_func($special[$key], $value);
$value = $special[$key]($value);
}
return [$key => $value];
}
@ -637,7 +637,7 @@ abstract class ASN1
if ($maymatch) {
// Got the match: use it.
if (isset($special[$key])) {
$candidate = call_user_func($special[$key], $candidate);
$candidate = $special[$key]($candidate);
}
$map[$key] = $candidate;
$i++;
@ -722,7 +722,7 @@ abstract class ASN1
// Got the match: use it.
if (isset($special[$key])) {
$candidate = call_user_func($special[$key], $candidate);
$candidate = $special[$key]($candidate);
}
$map[$key] = $candidate;
break;
@ -881,7 +881,7 @@ abstract class ASN1
if (isset($idx)) {
if (isset($special[$idx])) {
$source = call_user_func($special[$idx], $source);
$source = $special[$idx]($source);
}
self::$location[] = $idx;
}

View File

@ -1941,7 +1941,7 @@ class SFTP extends SSH2
$i = $j = 0;
while ($dataCallback || ($size === 0 || $sent < $size)) {
if ($dataCallback) {
$temp = call_user_func($dataCallback, $sftp_packet_size);
$temp = $dataCallback($sftp_packet_size);
if (is_null($temp)) {
break;
}
@ -1962,7 +1962,7 @@ class SFTP extends SSH2
}
$sent+= strlen($temp);
if (is_callable($progressCallback)) {
call_user_func($progressCallback, $sent);
$progressCallback($sent);
}
$i++;
@ -2137,7 +2137,7 @@ class SFTP extends SSH2
$packet = null;
$read+= $packet_size;
if (is_callable($progressCallback)) {
call_user_func($progressCallback, $read);
$progressCallback($read);
}
$i++;
}

View File

@ -789,6 +789,6 @@ class Stream
if (!method_exists($this, $name)) {
return false;
}
return call_user_func_array([$this, $name], $arguments);
return $this->$name(...$arguments);
}
}

View File

@ -2675,7 +2675,7 @@ class SSH2
return false;
default:
if (is_callable($callback)) {
if (call_user_func($callback, $temp) === true) {
if ($callback($temp) === true) {
$this->close_channel(self::CHANNEL_EXEC);
return true;
}
@ -4190,7 +4190,9 @@ class SSH2
$output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
}
$fragment = Strings::shift($current_log, $this->log_short_width);
$hex = substr(preg_replace_callback('#.#s', [$this, 'format_log_helper'], $fragment), strlen($this->log_boundary));
$hex = substr(preg_replace_callback('#.#s', function ($matches) {
return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT);
}, $fragment), strlen($this->log_boundary));
// replace non ASCII printable characters with dots
// http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
// also replace < with a . since < messes up the output on web browsers