/**
  * @param $config
  * @return NoPasswordAuthentication|PasswordAuthentication|RSAKeyAuthentication|null
  * @throws SSH2Exception
  */
 protected function factoryAuthentication($config)
 {
     $type = $config['type'];
     $username = $config['username'];
     $authentication = null;
     switch ($type) {
         case 'password':
             $password = $config['password'];
             $authentication = new PasswordAuthentication($username, $password);
             break;
         case 'no_password':
             $authentication = new NoPasswordAuthentication($username);
             break;
         case 'rsa':
             $file = $config['file'];
             $keyRSA = new RSA();
             $keyRSA->loadKey(file_get_contents($file));
             $authentication = new RSAKeyAuthentication($username, $keyRSA);
             break;
         case 'rsa_password':
             $file = $config['file'];
             $keyRSA = new RSA();
             $keyRSA->loadKey(file_get_contents($file));
             $password = $config['password'];
             $keyRSA->setPassword($password);
             $authentication = new RSAKeyAuthentication($username, $keyRSA);
             break;
     }
     if (is_null($authentication)) {
         throw new SSH2Exception(sprintf("No authentication for given type '%s'", $type));
     }
     return $authentication;
 }
示例#2
1
 /**
  * @param string $commandName
  * @param string $target
  * @param array  $targetConfig
  * @param array  $inputCommand
  * @param array  $userHomeDir
  * @return string
  */
 public function executeCommand($commandName, $target, $targetConfig, $inputCommand, $userHomeDir)
 {
     $remoteCommand = str_replace([sprintf('\'%s\'', $commandName), sprintf('target=\'%s\'', $target)], [$commandName, sprintf('root=%s', $targetConfig['root'])], $inputCommand);
     $remoteCommand = sprintf('%s %s', $targetConfig['console'], $remoteCommand);
     $key = null;
     if (array_key_exists('password', $targetConfig)) {
         $key = $targetConfig['password'];
     }
     if (!$key) {
         $key = new RSA();
         if (array_key_exists('passphrase', $targetConfig['keys'])) {
             $passphrase = $targetConfig['keys']['passphrase'];
             $passphrase = realpath(preg_replace('/~/', $userHomeDir, $passphrase, 1));
             $key->setPassword(trim(file_get_contents($passphrase)));
         }
         $private = $targetConfig['keys']['private'];
         $private = realpath(preg_replace('/~/', $userHomeDir, $private, 1));
         if (!$key->loadKey(trim(file_get_contents($private)))) {
             return $this->getTranslator()->trans('commands.site.debug.messages.private-key');
         }
     }
     $ssh = new SSH2($targetConfig['host'], $targetConfig['port']);
     if (!$ssh->login($targetConfig['user'], $key)) {
         return sprintf('%s - %s', $ssh->getExitStatus(), $ssh->getErrors());
     } else {
         return $ssh->exec($remoteCommand);
     }
 }
 /**
  * Connects to remote server.
  *
  * @throws \InvalidArgumentException|\RuntimeException
  */
 protected function connect()
 {
     $host = $this->gitEnvironment->getHost();
     $username = $this->gitEnvironment->getUsername();
     $port = $this->gitEnvironment->getPort();
     $password = $this->gitEnvironment->getPassword();
     $privateKey = $this->gitEnvironment->getPrivateKey();
     $privateKeyPassword = $this->gitEnvironment->getPrivateKeyPassword();
     $this->sftp = new SFTP($host, 22);
     if (!$this->sftp) {
         throw new SshLoginException(sprintf('SSH connection failed on "%s:%s"', $host, $port));
     }
     if (isset($username) && $privateKey != null) {
         $key = new RSA();
         //Set Private Key Password
         if ($privateKeyPassword) {
             $key->setPassword($privateKeyPassword);
         }
         $key->loadKey($privateKey);
         //Login using private key
         if (!$this->sftp->login($username, $key)) {
             throw new SshLoginException(sprintf('SFTP authentication failed for user "%s" using private key', $username));
         }
     } else {
         if (!$this->sftp->login($username, $password)) {
             throw new SshLoginException(sprintf('SFTP authentication failed for user "%s" using password', $username));
         }
     }
 }
示例#4
0
文件: rsa.php 项目: farukuzun/core-1
 /**
  * Generate a keypair
  *
  * @return array ['privatekey' => $privateKey, 'publickey' => $publicKey]
  */
 public function createKey()
 {
     $rsa = new RSACrypt();
     $rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH);
     $rsa->setPassword($this->config->getSystemValue('secret', ''));
     return $rsa->createKey(self::CREATE_KEY_BITS);
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function connect()
 {
     $serverConfig = $this->getConfiguration();
     $this->sftp = new SFTP($serverConfig->getHost(), $serverConfig->getPort(), 3600);
     switch ($serverConfig->getAuthenticationMethod()) {
         case Configuration::AUTH_BY_PASSWORD:
             $result = $this->sftp->login($serverConfig->getUser(), $serverConfig->getPassword());
             break;
         case Configuration::AUTH_BY_IDENTITY_FILE:
             $key = new RSA();
             $key->setPassword($serverConfig->getPassPhrase());
             $key->loadKey(file_get_contents($serverConfig->getPrivateKey()));
             $result = $this->sftp->login($serverConfig->getUser(), $key);
             break;
         case Configuration::AUTH_BY_PEM_FILE:
             $key = new RSA();
             $key->loadKey(file_get_contents($serverConfig->getPemFile()));
             $result = $this->sftp->login($serverConfig->getUser(), $key);
             break;
         case Configuration::AUTH_BY_AGENT:
             $key = new Agent();
             $key->startSSHForwarding(null);
             $result = $this->sftp->login($serverConfig->getUser(), $key);
             break;
         default:
             throw new RuntimeException('You need to specify authentication method.');
     }
     if (!$result) {
         throw new RuntimeException('Unable to login with the provided credentials.');
     }
 }
示例#6
0
 /**
  *
  */
 public function connect()
 {
     $this->ssh = new SSH2($this->configuration['hostname'], $this->configuration['port']);
     $authenticationMethod = $this->configuration[SftpDriver::CONFIG_AUTHENTICATION_METHOD];
     if (static::AUTHENTICATION_PASSWORD === (int) $authenticationMethod) {
         $authentication = $this->configuration['password'];
     } elseif (static::AUTHENTICATION_PUBKEY === (int) $authenticationMethod) {
         $authentication = new RSA();
         if (!empty($this->configuration['privateKeyPassword'])) {
             $authentication->setPassword($this->configuration['privateKeyPassword']);
         }
         $authentication->loadKey(file_get_contents($this->configuration['privateKey']));
     } else {
         throw new \LogicException('Wrong authentication type for phpseclibAdapter', 1476626149);
     }
     $sshConnected = $this->ssh->login($this->configuration['username'], $authentication);
     if ($sshConnected) {
         $this->sftp = new SFTP($this->configuration['hostname'], $this->configuration['port']);
         $sftpConnected = $this->sftp->login($this->configuration['username'], $authentication);
         if ($sftpConnected) {
             $this->info['userId'] = (int) $this->ssh->exec('echo $EUID');
             $this->info['groupIds'] = GeneralUtility::intExplode(' ', $this->ssh->exec('echo ${GROUPS[*]}'), true);
             return true;
         }
     }
     return false;
 }
示例#7
0
 private function generateSshKeys()
 {
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
     $rsa->setPassword(\OC::$server->getConfig()->getSystemValue('secret', ''));
     $key = $rsa->createKey();
     // Replace the placeholder label with a more meaningful one
     $key['publicKey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
     return $key;
 }
示例#8
0
文件: sftp_key.php 项目: henkRW/core
 /**
  * Returns the private key to be used for authentication to the remote server.
  *
  * @return RSA instance or null in case of a failure to load the key.
  */
 private function getPrivateKey()
 {
     $key = new RSA();
     $key->setPassword(\OC::$server->getConfig()->getSystemValue('secret', ''));
     if (!$key->loadKey($this->privateKey)) {
         // Should this exception rather than return null?
         return null;
     }
     return $key;
 }
示例#9
0
 public static function generate($bits = 2048, $password = '')
 {
     $bits = (int) $bits;
     $rsa = new RSA();
     if (!empty($password)) {
         $rsa->setPassword($password);
     }
     $keys = $rsa->createKey($bits);
     $publicKey = new SshPublicKey($keys['publickey']);
     $privateKey = new SshPrivateKey($keys['privatekey'], $password);
     return new SshKeyPair($publicKey, $privateKey);
 }
示例#10
0
 /**
  * Log into the server.
  *
  * @return void
  */
 public function login()
 {
     // Do nothing if already logged in
     if ($this->in) {
         return;
     }
     if ($this->config('key')) {
         // We prefer logging in via keys
         $key = new RSA();
         if ($phrase = $this->config('keyphrase')) {
             $key->setPassword($phrase);
         }
         $key->loadKey(file_get_contents($this->config('key')));
     } else {
         // Password is less preferred, but anyway...
         $key = $this->config('password');
     }
     if (!($this->in = $this->ssh->login($this->config('username'), $key))) {
         throw new Exception('Failed to log in.');
     }
 }
示例#11
0
文件: JWS.php 项目: igtm/jose
 private function rsa($public_or_private_key, $padding_mode, $password = null)
 {
     if ($public_or_private_key instanceof JOSE_JWK) {
         $rsa = $public_or_private_key->toKey();
     } else {
         if ($public_or_private_key instanceof RSA) {
             $rsa = $public_or_private_key;
         } else {
             $rsa = new RSA();
             if ($password) {
                 $rsa->setPassword($password);
             }
             $rsa->loadKey($public_or_private_key);
         }
     }
     $rsa->setHash($this->digest());
     $rsa->setMGFHash($this->digest());
     $rsa->setSaltLength(false);
     # NOTE: https://github.com/phpseclib/phpseclib/issues/768
     $rsa->setSignatureMode($padding_mode);
     return $rsa;
 }
示例#12
0
 /**
  * @param string      $Username
  * @param string      $File
  * @param null|string $Password
  *
  * @return SFTP
  * @throws ComponentException
  */
 public function loginCredentialKey($Username, $File, $Password = null)
 {
     $this->Username = $Username;
     $this->Key = $File;
     $this->Password = $Password;
     $Key = new RSA();
     if (null !== $Password) {
         $Key->setPassword($Password);
     }
     if (!$Key->loadKey(file_get_contents($File))) {
         throw new ComponentException(__METHOD__ . ': Key failed');
     }
     if (!$this->Connection->login($Username, $Key)) {
         throw new ComponentException(__METHOD__ . ': Login failed');
     }
     return $this;
 }
示例#13
0
 /**
  * Get the private get with the password or private key contents.
  *
  * @return RSA
  */
 public function getPrivateKey()
 {
     if (is_file($this->privatekey)) {
         $this->privatekey = file_get_contents($this->privatekey);
     }
     $key = new RSA();
     if ($this->password) {
         $key->setPassword($this->password);
     }
     $key->loadKey($this->privatekey);
     return $key;
 }
示例#14
0
 /**
  * @param SSH2|SFTP $connector
  * @return SSH2|SFTP
  * @throws \Exception
  */
 protected function auth($connector)
 {
     switch ($this->auth) {
         case self::AUTH_KEYFILE:
             $password = new RSA();
             if (!is_null($this->getPassword())) {
                 $password->setPassword($this->getPassword());
             }
             $password->loadKey($this->getKeyfile());
             break;
         case self::AUTH_PASSWORD:
             // break intentionally omitted
         // break intentionally omitted
         default:
             $password = $this->getPassword();
             break;
     }
     if (!isset($password)) {
         $loggedIn = $connector->login($this->username);
     } else {
         $loggedIn = $connector->login($this->username, $password);
     }
     if (!$loggedIn) {
         throw new \Exception(sprintf('SSH authentication (%s) with %s on %s:%s failed!', $this->auth, $this->username, $this->hostname, $this->port));
     }
     return $connector;
 }
示例#15
0
    public function testSavePKCS8PrivateKey()
    {
        $rsa = new RSA();
        $key = '-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----';
        $rsa->setPassword('password');
        $this->assertTrue($rsa->loadKey($key));
        $key = $rsa->getPrivateKey(RSA::PRIVATE_FORMAT_PKCS8);
        $this->assertInternalType('string', $key);
        $this->assertTrue($rsa->loadKey($key));
    }
示例#16
0
    public function testPKCS1EncryptionChange()
    {
        $rsa = new RSA();
        $key = 'PuTTY-User-Key-File-2: ssh-rsa
Encryption: none
Comment: phpseclib-generated-key
Public-Lines: 4
AAAAB3NzaC1yc2EAAAADAQABAAAAgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4
eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RK
NUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDy
R4e9T04ZZw==
Private-Lines: 8
AAAAgBYo5KOevqhsjfDNEVcmkQF8/vsU6hwS4d7ceFYDLa0PlhIAo4aE8KNtyjAQ
LiRkmJ0ZqAWTN5TH0ynryJAInTxMb2AnZuXWKt106C5JC7+S9qSCFThTAxvihEpw
BVe5dnPnJ80TFtPm+n/JkdQic2bsVSy+kNNn7y4uef5m0mMRAAAAQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJ
rmfPwIGm63ilAAAAQQDEIvkdBvZtCvgHKitwxab+EQ/YxnNE5XvfIXjWE+xEL2br
oquF470c9Mm6jf/2zmn6yobE6UUvQ0O3hKSiyOAbAAAAQBGoiuSoSjafUhV7i1cE
Gpb88h5NBYZzWXGZ37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ
4p0=
Private-MAC: 03e2cb74e1d67652fbad063d2ed0478f31bdf256
';
        $key = preg_replace('#(?<!\\r)\\n#', "\r\n", $key);
        $this->assertTrue($rsa->load($key));
        PKCS1::setEncryptionAlgorithm('AES-256-CBC');
        $rsa->setPassword('demo');
        $encryptedKey = (string) $rsa;
        $this->assertRegExp('#AES-256-CBC#', $encryptedKey);
        $rsa = new RSA();
        $rsa->setPassword('demo');
        $this->assertTrue($rsa->load($encryptedKey));
        $rsa->setPassword();
        $rsa->setPrivateKeyFormat('PuTTY');
        $key2 = (string) $rsa;
        $this->assertSame($key, $key2);
    }
 /**
  * @throws \InvalidArgumentException|\RuntimeException
  *
  * @param array $connection
  */
 protected function connect($host, $username, $port = 22, $password = null, $pubkeyFile = null, $privateKey = null, $privateKeyPassword = null)
 {
     $this->shell = new SSH2($host, $port);
     if (!$this->shell) {
         throw new \InvalidArgumentException(sprintf('SSH connection failed on "%s:%s"', $host, $port));
     }
     if (isset($username) && trim($privateKey)) {
         $key = new RSA();
         if ($privateKeyPassword) {
             $key->setPassword($privateKeyPassword);
         }
         $key->loadKey($privateKey);
         if (!$this->shell->login($username, $key)) {
             throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s" using private key', $username, $pubkeyFile));
         }
     } elseif ($username && $password) {
         if (!$this->shell->login($username, $password)) {
             throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s"', $username));
         }
     }
     $this->shell->getServerPublicHostKey();
     $this->stdout = array();
     $this->stdin = array();
 }
示例#18
0
 public function login()
 {
     $this->connectIfNeeded(false);
     if ($this->user === null) {
         throw new FtpException(Yii::t('gsftp', 'Could not login to SFTP server "{host}" on port "{port}" without username.', ['host' => $this->host, 'port' => $this->port]));
     } else {
         if ($this->privateKeyFile != null) {
             $key = new RSA();
             if ($this->pass != null && !empty($this->pass)) {
                 $key->setPassword($this->pass);
             }
             if ($this->publicKeyFile != null && !empty($this->publicKeyFile)) {
                 $key->setPublicKey(self::_readKeyFile('Public', $this->publicKeyFile));
             }
             $key->setPrivateKey(self::_readKeyFile('Private', $this->privateKeyFile));
             if (!$this->handle->login($this->user, $key)) {
                 throw new FtpException(Yii::t('gsftp', 'Could not login to SFTP server "{host}" on port "{port}" with user "{user}" using RSA key.', ['host' => $this->host, 'port' => $this->port, 'user' => $this->user]));
             }
         } else {
             if ($this->pass != null && !empty($this->pass)) {
                 if (!$this->handle->login($this->user, $this->pass)) {
                     throw new FtpException(Yii::t('gsftp', 'Could not login to SFTP server "{host}" on port "{port}" with user "{user}".', ['host' => $this->host, 'port' => $this->port, 'user' => $this->user]));
                 }
             }
         }
     }
 }