/**
  * @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);
     }
 }
 /**
  * @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;
 }
Exemple #3
0
 /**
  * {@inheritdoc}
  */
 public function connect()
 {
     $this->sftp = new SFTP($this->configuration->getHost(), $this->configuration->getPort());
     switch ($this->configuration->getAuthenticationMethod()) {
         case ServerConfiguration::AUTH_BY_IDENTITY_FILE:
             $key = new RSA();
             $key->loadKey(file_get_contents($this->configuration->getPrivateKey()));
             $result = $this->sftp->login($this->configuration->getUser(), $key);
             break;
         case ServerConfiguration::AUTH_BY_PEM_FILE:
             $key = new RSA();
             $key->loadKey(file_get_contents($this->configuration->getPemFile()));
             $result = $this->sftp->login($this->configuration->getUser(), $key);
             break;
         case ServerConfiguration::AUTH_BY_AGENT:
             $key = new Agent();
             $result = $this->sftp->login($this->configuration->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.');
     }
 }
 /**
  *
  */
 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;
 }
 /**
  * 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));
         }
     }
 }
Exemple #6
0
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testCrypt()
    {
        $rsa = new RSA();
        $rsa->loadKey('-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN
FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76
xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4
gwQco1KRMDSmXSMkDwIDAQAB
-----END PUBLIC KEY-----');
        // public key
        $plaintext = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida felis sit amet nulla accumsan, sed mollis elit tristique. Vivamus fermentum mauris et tellus feugiat luctus. Suspendisse faucibus, orci sed feugiat lobortis, nulla nunc vestibulum nibh, sed vulputate ipsum felis ac nisl. Sed sit amet est a felis posuere mollis eu placerat risus. Mauris eget nisl condimentum, varius sapien vitae, mattis nisl. Nulla porta eu nulla at imperdiet. Integer sollicitudin, ipsum nec tempus rhoncus, ipsum massa elementum sapien, ac malesuada orci augue eu nibh. Quisque posuere porttitor magna id finibus. Nunc porttitor eros et erat semper sagittis. Pellentesque sed luctus sem. Sed vulputate massa mollis lacus tincidunt auctor. Praesent aliquet quis diam sit amet rutrum. Sed mauris sem, placerat sed ex ac, hendrerit lobortis enim. Etiam egestas ex orci. Integer in varius ex, nec scelerisque tortor.';
        //$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
        $ciphertext = $rsa->encrypt($plaintext);
        $rsa->loadKey('-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ
WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR
aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB
AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv
xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH
m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd
8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF
z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5
rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM
V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe
aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil
psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz
uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876
-----END RSA PRIVATE KEY-----');
        // private key
        $decryptedText = $rsa->decrypt($ciphertext);
        $this->assertEquals($decryptedText, $plaintext);
    }
Exemple #7
0
 /**
  * {@inheritdoc }
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $privateKeyPath = $input->getOption('privateKey');
     $keyBundlePath = $input->getOption('certificate');
     $path = $input->getOption('path');
     if (is_null($privateKeyPath) || is_null($keyBundlePath) || is_null($path)) {
         $output->writeln('--privateKey, --certificate and --path are required.');
         return null;
     }
     $privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath);
     $keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath);
     if ($privateKey === false) {
         $output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath));
         return null;
     }
     if ($keyBundle === false) {
         $output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath));
         return null;
     }
     $rsa = new RSA();
     $rsa->loadKey($privateKey);
     $x509 = new X509();
     $x509->loadX509($keyBundle);
     $x509->setPrivateKey($rsa);
     $this->checker->writeCoreSignature($x509, $rsa, $path);
     $output->writeln('Successfully signed "core"');
 }
Exemple #8
0
 /**
  * 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);
 }
Exemple #9
0
 /**
  * Verifies an id token and returns the authenticated apiLoginTicket.
  * Throws an exception if the id token is not valid.
  * The audience parameter can be used to control which id tokens are
  * accepted.  By default, the id token must have been issued to this OAuth2 client.
  *
  * @param $audience
  * @return array the token payload, if successful
  */
 public function verifyIdToken($idToken, $audience = null)
 {
     if (empty($idToken)) {
         throw new LogicException('id_token cannot be null');
     }
     // Check signature
     $certs = $this->getFederatedSignOnCerts();
     foreach ($certs as $cert) {
         $modulus = new BigInteger($this->jwt->urlsafeB64Decode($cert['n']), 256);
         $exponent = new BigInteger($this->jwt->urlsafeB64Decode($cert['e']), 256);
         $rsa = new RSA();
         $rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
         try {
             $payload = $this->jwt->decode($idToken, $rsa->getPublicKey(), array('RS256'));
             if (property_exists($payload, 'aud')) {
                 if ($audience && $payload->aud != $audience) {
                     return false;
                 }
             }
             // support HTTP and HTTPS issuers
             // @see https://developers.google.com/identity/sign-in/web/backend-auth
             $issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS);
             if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) {
                 return false;
             }
             return (array) $payload;
         } catch (ExpiredException $e) {
             return false;
         } catch (DomainException $e) {
             // continue
         }
     }
     return false;
 }
Exemple #10
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.');
     }
 }
 public function handle($data)
 {
     $rsa = new RSA();
     $rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_XML);
     $rsa->setPublicKeyFormat(RSA::PRIVATE_FORMAT_XML);
     return ["assignment" => Token::generateNewToken(TOKEN_ASSIGNMENT)->toExternalForm(false)];
 }
Exemple #12
0
 private function rsa($public_or_private_key, $padding_mode)
 {
     $rsa = new RSA();
     $rsa->loadKey($public_or_private_key);
     $rsa->setEncryptionMode($padding_mode);
     return $rsa;
 }
 /**
  * Static method for quick calls to calculate a signature.
  * @link https://developer.walmartapis.com/#authentication
  * @param string $consumerId
  * @param string $privateKey
  * @param string $requestUrl
  * @param string $requestMethod
  * @param string|null $timestamp
  * @return string
  * @throws \Exception
  */
 public static function calculateSignature($consumerId, $privateKey, $requestUrl, $requestMethod, $timestamp = null)
 {
     if (is_null($timestamp) || !is_numeric($timestamp)) {
         $timestamp = self::getMilliseconds();
     }
     /**
      * Append values into string for signing
      */
     $message = $consumerId . "\n" . $requestUrl . "\n" . strtoupper($requestMethod) . "\n" . $timestamp . "\n";
     /**
      * Get RSA object for signing
      */
     $rsa = new RSA();
     $decodedPrivateKey = base64_decode($privateKey);
     $rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
     $rsa->setPublicKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
     /**
      * Load private key
      */
     if ($rsa->loadKey($decodedPrivateKey, RSA::PRIVATE_FORMAT_PKCS8)) {
         /**
          * Make sure we use SHA256 for signing
          */
         $rsa->setHash('sha256');
         $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
         $signed = $rsa->sign($message);
         /**
          * Return Base64 Encode generated signature
          */
         return base64_encode($signed);
     } else {
         throw new \Exception("Unable to load private key", 1446780146);
     }
 }
Exemple #14
0
 public static function generateKeyPair($comment = 'dogpro')
 {
     $rsa = new RSA();
     $rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
     $rsa->setComment($comment);
     return $rsa->createKey();
 }
 /**
  * Login with the set username and password.
  * @return LoginResult
  * @throws SteamException Thrown when Steam gives an unexpected response (e.g. Steam is down/having issues)
  * @throws \Exception Thrown when cookiefile is unable to be created.
  */
 public function doLogin()
 {
     if (!file_exists($this->_getCookiesFilePath())) {
         if (file_put_contents($this->_getCookiesFilePath(), '') === false) {
             throw new \Exception("Could not create cookiefile for {$this->username}.");
         }
     }
     if ($this->_isLoggedIn()) {
         $this->loggedIn = true;
         return LoginResult::LoginOkay;
     }
     $rsaResponse = $this->cURL('https://steamcommunity.com/login/getrsakey', null, ['username' => $this->username]);
     $rsaJson = json_decode($rsaResponse, true);
     if ($rsaJson == null) {
         return LoginResult::GeneralFailure;
     }
     if (!$rsaJson['success']) {
         return LoginResult::BadRSA;
     }
     $rsa = new RSA();
     $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
     $key = ['modulus' => new BigInteger($rsaJson['publickey_mod'], 16), 'publicExponent' => new BigInteger($rsaJson['publickey_exp'], 16)];
     $rsa->loadKey($key, RSA::PUBLIC_FORMAT_RAW);
     $encryptedPassword = base64_encode($rsa->encrypt($this->password));
     $params = ['username' => $this->username, 'password' => urlencode($encryptedPassword), 'twofactorcode' => is_null($this->twoFactorCode) ? '' : $this->twoFactorCode, 'captchagid' => $this->requiresCaptcha ? $this->captchaGID : '-1', 'captcha_text' => $this->requiresCaptcha ? $this->captchaText : '', 'emailsteamid' => $this->requires2FA || $this->requiresEmail ? (string) $this->steamId : '', 'emailauth' => $this->requiresEmail ? $this->emailCode : '', 'rsatimestamp' => $rsaJson['timestamp'], 'remember_login' => 'false'];
     $loginResponse = $this->cURL('https://steamcommunity.com/login/dologin/', null, $params);
     $loginJson = json_decode($loginResponse, true);
     if ($loginJson == null) {
         return LoginResult::GeneralFailure;
     } else {
         if (isset($loginJson['captcha_needed']) && $loginJson['captcha_needed']) {
             $this->requiresCaptcha = true;
             $this->captchaGID = $loginJson['captcha_gid'];
             return LoginResult::NeedCaptcha;
         } else {
             if (isset($loginJson['emailauth_needed']) && $loginJson['emailauth_needed']) {
                 $this->requiresEmail = true;
                 $this->steamId = $loginJson['emailsteamid'];
                 return LoginResult::NeedEmail;
             } else {
                 if (isset($loginJson['requires_twofactor']) && $loginJson['requires_twofactor'] && !$loginJson['success']) {
                     $this->requires2FA = true;
                     return LoginResult::Need2FA;
                 } else {
                     if (isset($loginJson['login_complete']) && !$loginJson['login_complete']) {
                         return LoginResult::BadCredentials;
                     } else {
                         if ($loginJson['success']) {
                             $this->_setSession();
                             $this->loggedIn = true;
                             return LoginResult::LoginOkay;
                         }
                     }
                 }
             }
         }
     }
     return LoginResult::GeneralFailure;
 }
Exemple #16
0
 function testEncodeWithExtraComponents()
 {
     $rsa = new RSA();
     $rsa->loadKey($this->rsa_keys['private']);
     $jwk = JOSE_JWK::encode($rsa, array('kid' => '12345', 'use' => 'sig'));
     $this->assertEquals('12345', $jwk->components['kid']);
     $this->assertEquals('sig', $jwk->components['use']);
 }
Exemple #17
0
 /**
  * @param array $data
  *
  * @throws \Exception
  *
  * @return \phpseclib\Crypt\RSA
  */
 public static function fromArrayToRSACrypt(array $data)
 {
     self::checkRequirements();
     $xml = self::fromArrayToXML($data);
     $rsa = new RSA();
     $rsa->loadKey($xml);
     return $rsa;
 }
 public function decrypt($encryptedToken)
 {
     defined('CRYPT_RSA_PKCS15_COMPAT') || define('CRYPT_RSA_PKCS15_COMPAT', true);
     $rsa = new Crypt_RSA();
     $rsa->loadKey($this->privateKey);
     $rsa->setEncryptionMode(Crypt_RSA::ENCRYPTION_PKCS1);
     return $rsa->decrypt($encryptedToken);
 }
 protected static function doGenerateKeys($keySize = 2048)
 {
     $rsa = new Crypt_RSA();
     $rsa->setPrivateKeyFormat(Crypt_RSA::PRIVATE_FORMAT_PKCS1);
     $rsa->setPublicKeyFormat(Crypt_RSA::PUBLIC_FORMAT_PKCS1);
     defined('CRYPT_RSA_EXPONENT') || define('CRYPT_RSA_EXPONENT', 65537);
     defined('CRYPT_RSA_SMALLEST_PRIME') || define('CRYPT_RSA_SMALLEST_PRIME', 64);
     return $rsa->createKey($keySize);
 }
Exemple #20
0
 /**
  * Generate a private/public RSA key pair
  *
  * @param int $size Key size
  * @param string $passphrase Optional - password-protected private key
  *
  * @return self
  * @throws InvalidKeyException
  */
 public static function generateKeyPair($size = 2048)
 {
     if ($size < 2048) {
         throw new InvalidKeyException('Key size must be at least 2048 bits.');
     }
     $rsa = new RSA();
     $keypair = $rsa->createKey($size);
     return new KeyPair(new PrivateKey($keypair['privatekey']), new PublicKey($keypair['publickey']));
 }
Exemple #21
0
 /**
  * @expectedException \LengthException
  */
 public function testSmallModulo()
 {
     $plaintext = 'x';
     $n = new BigInteger(base64_decode('272435F22706FA96DE26E980D22DFF67'), 256);
     $e = new BigInteger(base64_decode('158753FF2AF4D1E5BBAB574D5AE6B54D'), 256);
     $rsa = new RSA();
     $rsa->load(array('n' => $n, 'e' => $e));
     $rsa->encrypt($plaintext);
 }
Exemple #22
0
 public function encrypt(DatabaseRow $row, User $receiver)
 {
     $rsa = new RSA();
     $rsa->loadKey($receiver->getPublicKey());
     $rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP);
     $sharedRow = clone $row;
     $sharedRow->setAttributes(array());
     return $rsa->encrypt(json_encode($sharedRow));
 }
 /**
  * @REST\Get("/jwks", name="oidc_jwks", defaults={"_format"="json"})
  * @REST\View(templateVar="jwks")
  */
 public function getAction()
 {
     $keyStorage = $this->get('oauth2.storage.public_key');
     $pubKey = new RSA();
     $pubKey->loadKey($keyStorage->getPublicKey());
     $publicKey = \JOSE_JWK::encode($pubKey);
     $publicKey->components['kid'] = 'pub';
     $jwks = new \JOSE_JWKSet(array($publicKey));
     return new JsonResponse(json_decode($jwks->toString()));
 }
Exemple #24
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;
 }
Exemple #25
0
 function testThumbprint()
 {
     $rsa = new RSA();
     $rsa->loadKey($this->rsa_keys['public']);
     $jwk = JOSE_JWK::encode($rsa);
     $this->assertInstanceOf('JOSE_JWK', $jwk);
     $this->assertEquals('nuBTimkcSt_AuEsD8Yv3l8CoGV31bu_3gsRDGN1iVKA', $jwk->thumbprint());
     $this->assertEquals('nuBTimkcSt_AuEsD8Yv3l8CoGV31bu_3gsRDGN1iVKA', $jwk->thumbprint('sha256'));
     $this->assertEquals('6v7pXTnQLMiQgvJlPJUdhAUSuGLzgF8C1r3ABAMFet6bc53ea-Pq4ZGbGu3RoAFsNRT1-RhTzDqtqXuLU6NOtw', $jwk->thumbprint('sha512'));
 }
Exemple #26
0
 /**
  * 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;
 }
 /**
  * Executes the PullDbViaSsh Task.
  *
  * @return Robo\Result
  */
 public function run()
 {
     // Login to the remote server
     $this->printTaskInfo('Logging into remote server - <info>ssh://' . $this->sshUser . '@' . $this->sshHost . '/</info>');
     $ssh = new SFTP($this->sshHost);
     // Do we use password or a key
     if (file_exists($this->sshKey) && empty($this->sshPass)) {
         $key = new RSA();
         $key->loadKey(file_get_contents($this->sshKey));
         if (!$ssh->login($this->sshUser, $key)) {
             throw new RuntimeException('Failed to login via SSH using Key Based Auth.');
         }
     } else {
         if (!$ssh->login($this->sshUser, $this->sshPass)) {
             throw new RuntimeException('Failed to login via SSH using Password Based Auth.');
         }
     }
     // Create our dump filename
     $dump_name = $this->remoteDbName . '_' . time();
     // Create our dump on the remote server
     $cmd = 'mysqldump ' . '-h' . $this->remoteDbHost . ' -u' . $this->remoteDbUser . ' ' . (empty($this->remoteDbPass) ? '' : '-p' . $this->remoteDbPass) . ' ' . $this->remoteDbName . ' > /tmp/' . $dump_name . '.sql';
     $this->printTaskInfo('Dumping db on remote server - <info>' . $cmd . '</info>');
     $results = $ssh->exec($cmd);
     if ($ssh->getExitStatus() > 0) {
         throw new RuntimeException('Failed to create dump on remote server. ' . $results);
     }
     // Compressing dump
     $cmd = 'gzip /tmp/' . $dump_name . '.sql';
     $this->printTaskInfo('Compressing dump on remote server - <info>' . $cmd . '</info>');
     $results = $ssh->exec($cmd);
     if ($ssh->getExitStatus() > 0) {
         throw new RuntimeException('Failed to compress dump on remote server. ' . $results);
     }
     // Copy it down locally
     $this->printTaskInfo('Transfering dump to local.');
     $temp_dump_name = tempnam(sys_get_temp_dir(), 'dump');
     $temp_dump = $temp_dump_name . '.sql.gz';
     if (!$ssh->get('/tmp/' . $dump_name . '.sql.gz', $temp_dump)) {
         throw new RuntimeException('Failed to download dump.');
     }
     // Remove the dump from the remote server
     $this->printTaskInfo('Removing dump from remote server - <info>rm /tmp/' . $dump_name . '.sql.gz</info>');
     if (!$ssh->delete('/tmp/' . $dump_name . '.sql.gz')) {
         throw new RuntimeException('Failed to delete dump on remote server.');
     }
     // Import the dump locally
     if (!$this->taskImportSqlDump($temp_dump)->host($this->localDbHost)->user($this->localDbUser)->pass($this->localDbPass)->name($this->localDbName)->run()->wasSuccessful()) {
         throw new RuntimeException('Failed to import dump on local server.');
     }
     $this->printTaskInfo('Deleting dump locally.');
     unlink($temp_dump);
     unlink($temp_dump_name);
     // If we get to here assume everything worked
     return Result::success($this);
 }
 /**
  * Create domain RSA keys
  *
  * @return KeyPair
  * @throws \Exception
  */
 public function createKeys()
 {
     $rsa = new RSA();
     $keys = $rsa->createKey(2048);
     if ($keys['partialkey'] === false) {
         $this->domainKeys = new KeyPair($keys['privatekey'], $keys['publickey']);
     } else {
         throw new \Exception('CPU was to slow, we\'ve not yet coded this part.');
     }
     return $this->domainKeys;
 }
Exemple #29
0
 public function login($user_id, $user_pw, $do_finalize = true)
 {
     $keys = $this->getKeys();
     $rsa = new RSA();
     $rsa->modulus = new BigInteger($keys['nvalue'], 16);
     $rsa->exponent = new BigInteger($keys['evalue'], 16);
     $rsa->publicExponent = new BigInteger($keys['evalue'], 16);
     $rsa->k = strlen($rsa->modulus->toBytes());
     $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $rsa->loadKey($rsa->_convertPublicKey($rsa->modulus, $rsa->exponent), CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
     $raw_data = $this->getLenChar($keys['sessionkey']) . $keys['sessionkey'] . $this->getLenChar($user_id) . $user_id . $this->getLenChar($user_pw) . $user_pw;
     $enc_data = $rsa->encrypt($raw_data);
     $login_url = 'https://nid.naver.com/nidlogin.login';
     $headers = ['User-Agent' => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 TAKOYAKI", 'Accept' => 'text/html,application/xhtml+xml,' . 'application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding' => 'gzip, deflate', 'Referer' => 'http://www.naver.com/', 'Content-Type' => 'application/x-www-form-urlencoded'];
     $params = "enctp" . "=" . "1";
     $params .= "&encpw" . "=" . bin2hex($enc_data);
     $params .= "&encnm" . "=" . $keys['keyname'];
     $params .= "&svctype" . "=" . "0";
     $params .= "&url=http://www.naver.com/&enc_url=http%3A%2F%2Fwww.naver.com%2F&postDataKey=&nvlong=&saveID=&smart_level=undefined";
     $params .= "&id" . "=" . "";
     $params .= "&pw" . "=" . "";
     $resp = $this->postURL($login_url, $params, 10, $headers);
     // echo "\n\nheader\n" . $resp ["header"] . "\n";
     // echo "\n\nbody\n" . $resp ["body"] . "\n";
     $this->logined = true;
     echo "\n로그인에 성공했습니다\n";
     if (strpos($resp["body"], "새로운")) {
         // NEW DEVICE CHECK
         $key = $this->getKey($resp["body"]);
         $result = $this->Accept($key);
         $exp = explode('Set-Cookie: ', $result);
         $NID_SES3 = explode('Set-Cookie: NID_AUT=', $result);
         $work = $NID_SES3[1];
         $NID_SES2 = explode(';', $work);
         $NID_SES = $NID_SES2[0];
         $NID_AUT3 = explode('Set-Cookie: NID_AUT=', $result);
         $work2 = $NID_AUT3[1];
         $NID_AUT2 = explode(';', $work2);
         $NID_AUT = $NID_AUT2[0];
         $this->logined = true;
         echo "\n새장치 등록에 성공했습니다\n";
     } elseif (strpos($resp["body"], "않습니다")) {
         $this->logined = false;
     }
     if ($do_finalize and strpos($resp["body"], "https://nid.naver.com/login/sso/finalize.nhn")) {
         $finalize_url = explode("replace(\"", $resp["body"], 2)[1];
         $finalize_url = explode("\")", $finalize_url, 2)[0];
         // echo "finalize_url: " . $finalize_url . "\n";
         $headers = ['User-Agent' => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 TAKOYAKI", 'Accept' => 'text/html,application/xhtml+xml,' . 'application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding' => 'gzip, deflate', 'Referer' => 'https://nid.naver.com/nidlogin.login'];
         $resp = $this->postURL($finalize_url, $headers);
         echo "파이널라이즈에 성공했습니다\n";
         // var_dump ( $resp );
     }
 }
Exemple #30
0
 /**
  * Generate a 4096 bits RSA private key
  * @return array the PEM-encoded version of the unprotected private and public keys.
  */
 function genRsa()
 {
     $rsa = new RSA();
     $privKey = $rsa->createKey(4096);
     // TODO handle timeout?
     if (isset($privKey["partialkey"])) {
         unset($privKey["partialkey"]);
     }
     return $privKey;
     // hash with privatekey and publickey
 }