Exemplo n.º 1
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);
     }
 }
 /**
  * @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;
 }
Exemplo n.º 3
1
 /**
  * @return bool
  */
 public function login()
 {
     $password = $this->password;
     $username = $this->username;
     // try to login using ssh key
     if (null === $password) {
         try {
             // try with agent (suppress stupid phpseclib warnings/errors)
             $agent = @new Agent();
         } catch (\Exception $e) {
             $agent = null;
         }
         if ($success = $this->sftp->login($username, $agent)) {
             return true;
         }
         // try with key manually
         $identityFilePath = $_SERVER['HOME'] . '/.ssh/id_rsa';
         if (!is_file($identityFilePath)) {
             $this->io->write(sprintf('Public key file not found in %s', $identityFilePath));
             return false;
         }
         $identityFile = file_get_contents($identityFilePath);
         $key = new RSA();
         $loaded = $key->loadKey($identityFile);
         // first try without keypass
         if (!$loaded || false === ($success = $this->sftp->login($username, $key))) {
             $attempts = 3;
             // now N attempts to load the identity file
             while ($attempts--) {
                 // retry with password
                 $this->keyPassword = $this->keyPassword ?: $this->io->askAndHideAnswer(sprintf('Enter passphrase for %s: ', $identityFilePath));
                 $key->setPassword($this->keyPassword);
                 $loaded = $key->loadKey($identityFile);
                 if (!$loaded) {
                     if ($attempts > 0) {
                         $this->keyPassword = null;
                         $this->io->write('Permission denied, please try again.');
                     }
                 } else {
                     if (false === ($success = $this->sftp->login($username, $key))) {
                         $this->io->write(sprintf('%s@%s: Permission denied (publickey)', $this->username, $this->host));
                     }
                     return $success;
                 }
             }
         }
         return $success;
     }
     // login with given password
     return $this->sftp->login($username, $password);
 }
Exemplo n.º 4
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);
    }
Exemplo n.º 5
0
    public function testEncryptionModeNone()
    {
        $plaintext = 'a';
        $rsa = new RSA();
        $privatekey = '-----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->loadKey($privatekey);
        $rsa->loadKey($rsa->getPublicKey());
        $rsa->setEncryptionMode(RSA::ENCRYPTION_NONE);
        $expected = '105b92f59a87a8ad4da52c128b8c99491790ef5a54770119e0819060032fb9e772ed6772828329567f3d7e9472154c1530f8156ba7fd732f52ca1c06' . '5a3f5ed8a96c442e4662e0464c97f133aed31262170201993085a589565d67cc9e727e0d087e3b225c8965203b271e38a499c92fc0d6502297eca712' . '4d04bd467f6f1e7c';
        $expected = pack('H*', $expected);
        $result = $rsa->encrypt($plaintext);
        $this->assertEquals($result, $expected);
        $rsa->loadKey($privatekey);
        $this->assertEquals(trim($rsa->decrypt($result), ""), $plaintext);
    }
Exemplo n.º 6
0
 /**
  * Constructor.
  *
  * @param string $username
  * @param Client $client
  *
  * @throws SteamLoginException In case of errors
  */
 public function __construct($username, Client $client)
 {
     $responseBody = Utils::jsonBody($client->post(SteamLogin::STEAMCOMM_WEBSITE . '/login/getrsakey/', array('form_params' => ['donotcache' => Utils::microtime_ms(true), 'username' => $username])));
     $this->publickey_mod = new BigInteger($responseBody->publickey_mod, 16);
     $this->publickey_exp = new BigInteger($responseBody->publickey_exp, 16);
     $this->timestamp = $responseBody->timestamp;
     $this->rsa_key = new RSA();
     $this->rsa_key->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
     $this->rsa_key->loadKey(array('e' => $this->publickey_exp, 'n' => $this->publickey_mod));
 }
Exemplo n.º 7
0
 public function onEnable()
 {
     $this->saveDefaultConfig();
     $this->saveResource("server-icon.png", false);
     $this->saveResource("steve.yml", false);
     $this->saveResource("alex.yml", false);
     $this->reloadConfig();
     $this->onlineMode = (bool) $this->getConfig()->get("online-mode");
     if ($this->onlineMode and !function_exists("mcrypt_generic_init")) {
         $this->onlineMode = false;
         $this->getLogger()->notice("no mcrypt detected, online-mode has been disabled. Try using the latest PHP binaries");
     }
     if (!$this->getConfig()->exists("motd")) {
         $this->getLogger()->warning("No motd has been set. The server description will be empty.");
         return;
     }
     if (Info::CURRENT_PROTOCOL === 84) {
         $this->translator = new Translator_84();
         $this->rsa = new RSA();
         $this->getServer()->getPluginManager()->registerEvents($this, $this);
         Achievement::add("openInventory", "Taking Inventory");
         //this for DesktopPlayer
         if ($this->onlineMode) {
             $this->getLogger()->info("Server is being started in the background");
             $this->getLogger()->info("Generating keypair");
             $this->rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
             $this->rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
             $keys = $this->rsa->createKey(1024);
             $this->privateKey = $keys["privatekey"];
             $this->publicKey = $keys["publickey"];
             $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
             $this->rsa->loadKey($this->privateKey);
         }
         $this->getLogger()->info("Starting Minecraft: PC server on " . ($this->getIp() === "0.0.0.0" ? "*" : $this->getIp()) . ":" . $this->getPort() . " version " . MCInfo::VERSION);
         $disable = true;
         foreach ($this->getServer()->getNetwork()->getInterfaces() as $interface) {
             if ($interface instanceof ProtocolInterface) {
                 $disable = false;
             }
         }
         if ($disable) {
             $this->interface = new ProtocolInterface($this, $this->getServer(), $this->translator);
             $this->getServer()->getNetwork()->registerInterface($this->interface);
         }
     } else {
         $this->getLogger()->critical("Couldn't find a protocol translator for #" . Info::CURRENT_PROTOCOL . ", disabling plugin");
         $this->getPluginLoader()->disablePlugin($this);
     }
 }
Exemplo n.º 8
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;
 }
 /**
  * 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));
         }
     }
 }
Exemplo n.º 10
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.');
     }
 }
Exemplo n.º 11
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;
 }
Exemplo n.º 12
0
 /**
  * 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);
     }
 }
Exemplo n.º 13
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.');
     }
 }
Exemplo n.º 14
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;
 }
Exemplo n.º 15
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"');
 }
 /**
  * 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;
 }
 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);
 }
Exemplo n.º 18
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']);
 }
Exemplo n.º 19
0
 public function receiveCryptoKeys($privateKey, $publicKey)
 {
     $this->privateKey = $privateKey;
     $this->publicKey = $publicKey;
     $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $this->rsa->loadKey($this->privateKey);
     $this->enableServer();
 }
Exemplo n.º 20
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;
 }
Exemplo n.º 21
0
 public function manipulateStorageConfig(StorageConfig &$storage, IUser $user = null)
 {
     $auth = new RSACrypt();
     $auth->setPassword($this->config->getSystemValue('secret', ''));
     if (!$auth->loadKey($storage->getBackendOption('private_key'))) {
         throw new \RuntimeException('unable to load private key');
     }
     $storage->setBackendOption('public_key_auth', $auth);
 }
Exemplo n.º 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()));
 }
Exemplo n.º 24
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;
 }
Exemplo n.º 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'));
 }
Exemplo n.º 26
0
 /**
  * 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);
 }
Exemplo n.º 27
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 );
     }
 }
Exemplo n.º 28
0
    /**
     * @group github768
     */
    public function testPSSSigs()
    {
        $rsa = new RSA();
        $rsa->loadKey('-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVx
wTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFnc
CzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0T
p0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----');
        $sig = pack('H*', '1bd29a1d704a906cd7f726370ce1c63d8fb7b9a620871a05f3141a311c0d6e75fefb5d36dfb50d3ea2d37cd67992471419bfadd35da6e13b494' . '058ddc9b568d4cfea13ddc3c62b86a6256f5f296980d1131d3eaec6089069a3de79983f73eae20198a18721338b4a66e9cfe80e4f8e4fcef7a5bead5cbb' . 'b8ac4c76adffbc178c');
        $this->assertTrue($rsa->verify('zzzz', $sig));
    }
 public function __construct($host)
 {
     $this->host = $host;
     $this->ssh = new SSH2($this->host);
     $key = new RSA();
     $user = '******';
     // load private from apache home ssh dir
     $key->loadKey(file_get_contents('/var/www/.ssh/file.rsa'));
     if (!$this->ssh->login($user, $key)) {
         exit('Login Failed');
     }
 }
Exemplo n.º 30
0
 /**
  * @Route("/asd", name="homepage")
  */
 public function indexAction(Request $request)
 {
     $request = $this->get('request');
     $defaultData = array('name' => 'Type your file name here');
     $form = $this->createFormBuilder($defaultData)->add('name', 'text')->add('file', 'file', array('mapped' => false))->add('submit', 'submit')->getForm();
     if ($request->getMethod() == 'POST') {
         $form->handleRequest($this->get('request'));
         if ($form->isValid()) {
             // perform some action, such as saving the task to the database
             $data = $form->getData();
             if ($form['file']->getData()) {
                 $filename = $form['file']->getData()->getClientOriginalName();
                 $uploadDir = dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/framework/upload';
                 $form['file']->getData()->move($uploadDir, $filename);
                 $link = '/web/bundles/framework/upload' . '/' . $filename;
             }
         }
         $inputFile = $request->files->get('cache.xml');
         return $this->render('default/index.html.twig', array('cipher' => "", 'plain' => "", 'rsacipher' => "", 'rsaplain' => "", 'rsapk' => "", 'form' => $form->createView(), 'link' => $link));
     } else {
         $des = new DES();
         echo gettype($des);
         $des->setKey('This is my secret key');
         $plaintext = 'asda sda sdas dasd asdasdada sd';
         $cipher = $des->encrypt($plaintext);
         $plain = $des->decrypt($cipher);
         $rsa = new RSA();
         $rsa->createKey(1024);
         $rsaplain = "encrypt using RSA";
         $key = $rsa->createKey(1024);
         $rsa->loadKey($key['publickey']);
         $rsacipher = $rsa->encrypt($rsaplain);
         $rsa->loadKey($key['privatekey']);
         $rsadec = $rsa->decrypt($rsacipher);
         // replace this example code with whatever you need
         return $this->render('default/index.html.twig', array('base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..'), 'cipher' => $cipher, 'plain' => $plain, 'rsacipher' => $key['publickey'], 'rsaplain' => $key['privatekey'], 'rsapk' => $rsa->getPublicKey(), 'form' => $form->createView()));
     }
 }