public function Authenticate($uid, $pass)
 {
     $this->AuthResult = false;
     // Connect
     $con = ssh2_connect($this->RemoteHost, $this->RemotePort);
     if ($con === false) {
         return ulLoginBackend::ERROR;
     }
     // Check fingerprint
     if ($this->RemoteFingerprint != '') {
         if (ssh2_fingerprint($con, SSH2_FINGERPRINT_SHA1 | SSH2_FINGERPRINT_HEX) != $this->RemoteFingerprint) {
             return ulLoginBackend::ERROR;
         }
     }
     // Test if server supports password-based authentication
     $auth_methods = ssh2_auth_none($con, 'user');
     if (!in_array('password', $auth_methods)) {
         return ulLoginBackend::ERROR;
     }
     // Connect again, because we can only try to authenticate once on a connection
     $con = ssh2_connect($this->RemoteHost, $this->RemotePort);
     if ($con === false) {
         return ulLoginBackend::ERROR;
     }
     // Try to authenticate
     if (ssh2_auth_password($con, $uid, $pass)) {
         $this->AuthResult = $uid;
         return true;
     } else {
         return ulLoginBackend::BAD_CREDENTIALS;
     }
 }
Example #2
0
 function _connectandexecute($hostname, $port, $fingerprint, $user, $pass, $command)
 {
     // connect via ssh2
     $ssh = ssh2_connect($hostname, $port);
     if (!$ssh) {
         die("connection failed!");
     }
     $theirfingerprint = ssh2_fingerprint($ssh, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
     if (strtoupper($theirfingerprint) != strtoupper($fingerprint)) {
         die("fingerprint mismatch!");
     }
     if (!ssh2_auth_password($ssh, $user, $pass)) {
         die("authentication failed!");
     }
     // shell, as Brocade really doesn't seem to like exec
     if (!($sock = ssh2_shell($ssh, 'vt102', null, 80, 40, SSH2_TERM_UNIT_CHARS))) {
         die("failed to establish shell!\n");
     }
     fwrite($sock, "terminal length 0" . PHP_EOL);
     fwrite($sock, $command . PHP_EOL);
     sleep(1);
     // seems to be a magic trick...
     stream_set_blocking($sock, true);
     $data = "";
     while ($buf = fread($sock, 4096)) {
         flush();
         if (preg_match('/SSH@.+#$/', $buf)) {
             break;
         }
         $data .= $buf;
     }
     fclose($sock);
     return $data;
 }
Example #3
0
 /**
  * Connect operation
  */
 public function connect()
 {
     if ($this->_ssh2 != null) {
         // Already connected
         return;
     }
     // Connect to server
     $host = isset($this->_config['hostname']) ? $this->_config['hostname'] : 'localhost';
     $port = isset($this->_config['port']) ? $this->_config['port'] : 22;
     $username = isset($this->_config['username']) ? $this->_config['username'] : '';
     $password = isset($this->_config['password']) ? $this->_config['password'] : null;
     $this->_ssh2 = ssh2_connect($host, $port);
     if ($this->_ssh2 === FALSE) {
         throw new Kohana_Transfer_Exception(Kohana::message('transfer', 'fail_open_connection'), array(':host' => $host, 'port' => $port));
     }
     // Check fingerprint if it is specified
     if (isset($this->_config['fingerprint'])) {
         if (strtolower(ssh2_fingerprint($this->_ssh2)) != strtolower($this->_config['fingerprint'])) {
             throw new Kohana_Transfer_Exception(Kohana::message('transfer', 'fail_fingerprint_validation'), array(':key' => ssh2_fingerprint($this->_ssh2)));
         }
     }
     // Connect with certificate if it is specified
     if (isset($this->_config['pubkeyfile']) and isset($this->_config['privkeyfile'])) {
         if (!@ssh2_auth_pubkey_file($this->_ssh2, $username, $this->_config['pubkeyfile'], $this->_config['privkeyfile'], $password)) {
             throw new Kohana_Transfer_Exception(Kohana::message('transfer', 'fail_authentication'));
         }
     } else {
         if (!@ssh2_auth_password($this->_ssh2, $username, $password)) {
             throw new Kohana_Transfer_Exception(Kohana::message('transfer', 'fail_authentication'));
         }
     }
     // Enable SFTP mode
     $this->_sftp = ssh2_sftp($this->_ssh2);
 }
Example #4
0
 /**
  * {@inheritDoc}
  */
 public function check($fingerprint, $flags = null)
 {
     $flags = null === $flags ? self::FINGERPRINT_MD5 | self::FINGERPRINT_HEX : $flags;
     if (strtoupper(ssh2_fingerprint($this->resource, $flags)) !== str_replace(':', '', strtoupper($fingerprint))) {
         throw new BadFingerprint();
     }
     return $this;
 }
Example #5
0
 public function connect()
 {
     $this->connection = @ssh2_connect($this->hostname, $this->port, array('hostkey' => 'ssh-rsa'));
     $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_SHA1 | SSH2_FINGERPRINT_HEX);
     if (!@ssh2_auth_pubkey_file($this->connection, $this->username, $this->pubKeyFile, $this->privKeyFile)) {
         throw new Exception("Authentification Failed");
     }
     $this->sftpSession = @ssh2_sftp($this->connection);
     if (!$this->sftpSession) {
         throw new Exception("Could not initialize SFTP subsystem.");
     }
 }
Example #6
0
 public function __construct($hostname, $port = 22, $throw_error = false)
 {
     $this->ssh_connection = @ssh2_connect($hostname, $port);
     if (!$this->ssh_connection) {
         unset($this->ssh_connection);
         if ($throw_error) {
             //Throw error details (string)
             throw new Exception(Error::out(504, 'gateway timeout', 'Failed to make a SSH connection to host \'' . $hostname . '\' on port \'' . $port . '\'.'));
         } else {
             //Output error details
             Error::halt(504, 'gateway timeout', 'Failed to make a SSH connection to host \'' . $hostname . '\' on port \'' . $port . '\'.');
         }
     }
     $this->hostname = $hostname;
     $this->port = $port;
     $this->fingerprint = ssh2_fingerprint($this->ssh_connection, SSH2_FINGERPRINT_SHA1 | SSH2_FINGERPRINT_HEX);
 }
Example #7
0
 function _connectandexecute($hostname, $port, $fingerprint, $user, $pass, $command)
 {
     // connect via ssh2
     $ssh = ssh2_connect($hostname, $port);
     if (!$ssh) {
         die("connection failed!");
     }
     $theirfingerprint = ssh2_fingerprint($ssh, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
     if (strtoupper($theirfingerprint) != strtoupper($fingerprint)) {
         die("fingerprint mismatch: their: {$theirfingerprint} us: {$fingerprint}");
     }
     if (!ssh2_auth_password($ssh, $user, $pass)) {
         die("authentication failed!");
     }
     $sock = ssh2_exec($ssh, $command);
     stream_set_blocking($sock, true);
     return stream_get_contents($sock);
 }
Example #8
0
 /**
  * Makes connection via SFTP
  * @return bool.
  * @throws \Bitrix\Main\SystemException
  */
 public function connect()
 {
     $this->connection = @ssh2_connect($this->host, $this->port);
     if (!$this->connection) {
         throw new SystemException("Can't connect via ssh to: " . $this->host . ":" . $this->port);
     }
     if ($this->fingerprint != "") {
         $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
         if ($fingerprint != $this->fingerprint) {
             throw new SystemException("HOSTKEY MISMATCH! Possible Man-In-The-Middle Attack? Actual fingerint:" . $fingerprint . " expected: " . $this->fingerprint);
         }
     }
     if (!@ssh2_auth_password($this->connection, $this->login, $this->pass)) {
         throw new SystemException("Incorrect sftp login or password ");
     }
     $this->sftp = ssh2_sftp($this->connection);
     if (!$this->sftp) {
         throw new SystemException("Could not initialize SFTP subsystem.");
     }
     return true;
 }
Example #9
0
 /**
  * LhpSftp - Returns ssh2_sftp object
  *
  * @param string $user
  * @param string $pass
  * @param string $host
  * @param string $pubkey
  * @param int $port
  *
  * @throws exception
  */
 public function __construct($user, $pass, $host, $pubkey = null, $port = 22)
 {
     /**
      * Try to connect to $host
      */
     if (!($this->connection = ssh2_connect($host, $port))) {
         throw new Exception("Could not connect to {$host} on port {$port}.");
     }
     /**
      * Check fingerprint from server against our stored pubkey
      */
     if ($pubkey !== null) {
         $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
         if ($fingerprint != $pubkey) {
             throw new Exception("Fingerprint [ {$fingerprint} ] does not match your pubkey [ {$pubkey} ] ");
         }
     }
     /**
      * Send username and password
      */
     if (!ssh2_auth_password($this->connection, $user, $pass)) {
         throw new Exception("Username and/or password was not accepted.");
     }
 }
Example #10
0
 /**
  * Get the server SSH fingerprint
  *
  * @see ssh2_fingerprint()
  * @param int $flags Equiv ssh2_fingerprint() flags
  * @throws Exceptions\NotConnectedException
  * @return string
  */
 public function getFingerprint($flags = null)
 {
     if ($flags === null) {
         // Default flags of the ssh2_fingerprint function, matches format of the known_hosts file
         $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX;
     }
     $this->requireConnection(false);
     return ssh2_fingerprint($this->resource, $flags);
 }
Example #11
0
         }
         if ($ftp) {
             ftp_close($ftp);
         }
     }
 } elseif ($test['type'] == 'sftp') {
     // Check if we can connect to the SFTP server
     if (!function_exists('ssh2_connect')) {
         $result = 'failure';
         $msg = $cms->trans("SFTP support not available in this installation of PHP") . "<br/>\n" . $cms->trans("See %s for more information", "<a href='http://php.net/manual/en/ref.ssh2.php'>http://php.net/manual/en/ref.ssh2.php</a>");
     } else {
         if (empty($test['password'])) {
             $test['password'] = $log['password'];
         }
         $ssh = @ssh2_connect($test['host'], $test['port'] ? $test['port'] : 22);
         $finger = @ssh2_fingerprint($ssh);
         // in order for this to work PasswordAuthentication must be set to 'yes' in
         // the remote server's sshd_config file. I think a lot of distros might disable it.
         $res = @ssh2_auth_password($ssh, $test['username'], $test['password']);
         $result = 'failure';
         if (!$res) {
             $msg = $cms->trans("Unable to connect to ssh://%s@%s" . "<br/>\n", $test['username'], $test['host']);
             $msg .= !$ssh ? $cms->trans("Verify the host and port are correct") : $cms->trans("Authentication Failed! Note: the remote server must have PasswordAuthentication set to 'yes' in the sshd_config file.");
             $msg .= "<br/>" . $cms->trans("Note: This test mechanism does not support public key authentication.");
         } else {
             $sftp = ssh2_sftp($ssh);
             $stat = @ssh2_sftp_stat($sftp, $test['path']);
             if (!$stat) {
                 $msg = $cms->trans("Connected to SFTP server, however the path entered does not exist");
             } else {
                 $result = 'success';
Example #12
0
 /**
  * @param string $hashingMethod "sha1" or "md5"
  * @return mixed
  */
 public function getForeignKeyFingerprint($hashingMethod)
 {
     switch ($hashingMethod) {
         case self::HASHING_SHA1:
             $hashingMethod = SSH2_FINGERPRINT_SHA1;
             break;
         case self::HASHING_MD5:
         default:
             $hashingMethod = SSH2_FINGERPRINT_MD5;
     }
     return ssh2_fingerprint($this->ssh, $hashingMethod);
 }
Example #13
0
 /**
  * Attempt connection
  *
  * @return boolean
  * @throws Ssh2ConnectionException  if cannot connect
  */
 protected function connect()
 {
     $this->connected = false;
     $this->connection = ssh2_connect($this->hostname, $this->port);
     if (!$this->connection) {
         throw new Ssh2ConnectionException("Could not connect to {$this->hostname}:{$this->port}.");
     }
     // always ask for fingerprint for passing to event
     $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
     if (!empty($this->fingerprint) && $this->fingerprint !== $fingerprint) {
         throw new Ssh2ConnectionException("Fingerprint mismatch for {$this->hostname}:{$this->port} (server: '{$fingerprint}')");
     }
     try {
         if (!ssh2_auth_password($this->connection, $this->user, $this->password)) {
             throw new Ssh2ConnectionException("Could not authorize as {$this->user} on {$this->hostname}:{$this->port}.");
         }
     } catch (\Exception $e) {
         throw new Ssh2ConnectionException("Could not authorize as {$this->user} on {$this->hostname}:{$this->port}.");
     }
     $this->connected = true;
     event(new SshConnectionWasMade($this->user . '@' . $this->hostname . ':' . $this->port, $fingerprint));
     return $this->connected;
 }
Example #14
0
 private function setupSSH($host, $port, $known_host, $pub_key_location, $priv_key_location, $key_user, $cache_dir)
 {
     $this->Timers['SSH'] = MicroTime(true);
     if (!is_dir($cache_dir)) {
         mkdir($cache_dir);
     } else {
         $files = array_diff(scandir($cache_dir), array('.', '..'));
         foreach ($files as $file) {
             is_dir("{$cache_dir}\\{$file}") ? delTree("{$cache_dir}\\{$file}") : unlink("{$cache_dir}\\{$file}");
         }
     }
     if ($port == 0 || empty($port)) {
         $port = 22;
     }
     if (!isset($host) || !isset($known_host) || !isset($pub_key_location) || !isset($priv_key_location) || !isset($key_user)) {
         throw new Exception('Please make sure to you set all variables for setting up SSH!');
     } else {
         $connection = ssh2_connect($host, $port);
         if (!$connection) {
             throw new Exception('Failed to connect to the server!');
         }
         $fingerprint = ssh2_fingerprint($connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
         if (empty($known_host) || !isset($known_host)) {
             die("You haven't set your SSH known host! If this is a new installation, here is your host's MD5: {$fingerprint} <br>Please use this key in your SSH options.");
         }
         if ($fingerprint != $known_host) {
             throw new Exception('Possible Man-In-The-Middle Attack! Check your known_host setting to make sure the key is correct!');
             return false;
         }
         ssh2_auth_pubkey_file($connection, $key_user, $pub_key_location, $priv_key_location);
         $stream = ssh2_exec($connection, "/usr/bin/rm -rf {$this->installLocation}/arkdata.zip && /usr/bin/zip -j {$this->installLocation}/arkdata.zip {$this->installLocation}/*.arkprofile {$this->installLocation}/*.arktribe");
         //forces PHP to wait for the zip file to finish before continuing.
         stream_set_blocking($stream, true);
         while ($line = fgets($stream)) {
             flush();
         }
         $sftp = ssh2_sftp($connection);
         $remotezipfile = @file_get_contents("ssh2.sftp://{$sftp}{$this->installLocation}/arkdata.zip");
         if (!$remotezipfile) {
             throw new Exception('We failed to get the zip file from the server, please check your installLocation path and try again!');
             return false;
         }
         $localzipfile = @file_put_contents("{$cache_dir}\\arkdata.zip", $remotezipfile);
         if (!$localzipfile) {
             throw new Exception('We failed to write the zip file out and cannot proceed! Please check your cache_dir path and try again.');
             return false;
         }
         $zip = new ZipArchive();
         $res = $zip->open($cache_dir . '\\arkdata.zip');
         if ($res === true) {
             $zip->extractTo($cache_dir);
             $zip->close();
         } else {
             throw new Exception('We failed to extract the zip file, this could be due to a space issue or the file failed to download!');
             return false;
         }
         $this->Timers['SSH'] = Number_Format(MicroTime(true) - $this->Timers['SSH'], 4, '.', '');
         return true;
     }
 }
Example #15
0
 public function getSSH2Connection()
 {
     //try to get any passive connection ...if any...
     if (count($this->connections_cache_passive)) {
         if (count($this->connections_cache_passive) == 1) {
             //just return one...(array is never zero based ....)
             $connection_data = array_shift($this->connections_cache_passive);
             //get one and remove it from passive...
         } else {
             //we got more to choose from ....
             if (PHP_SSH2MST_REUSE_RANDOM_CONNECTION) {
                 //get randomly one out all available passive connections...
                 //the more we shuffle our data among all those connections - the more difficult it will be for those suckers that installed DPI in they centers...
                 $i = array_rand($this->connections_cache_passive, 1);
             } else {
                 //return last used stream..this will effectively break the file integrity if assembled as-is...by DPI...
                 //unless of coz ... last used connection was the last stream.... in this case we'll randomize...
                 usort($this->connections_cache_passive, 'DSResortLastUsed');
                 $i = 0;
                 if ($this->connections_cache_passive[$i]->connection_index == $this->max_streams) {
                     //crap ... it is the last one. :)
                     //keep randomizing till we'll get something else...
                     $radom_enough = 0;
                     while (!$radom_enough) {
                         $i = array_rand($this->connections_cache_passive, 1);
                         if ($this->connections_cache_passive[$i]->connection_index != $this->max_streams) {
                             $radom_enough = 1;
                         }
                     }
                 }
             }
             $connection_data = $this->connections_cache_passive[$i];
             //and remove from passive...
             unset($this->connections_cache_passive[$i]);
         }
         //---------------------------------------------------------------------------------------------------------------
         if (PHP_SSH2MST_DEBUG) {
             echo "|||||||||| REUSING EXISTING CONNECTION .....{$connection_data->connection_index}..\n";
         }
         //---------------------------------------------------------------------------------------------------------------
         //save in active list...
         $this->connections_cache_active[] = $connection_data;
         return $connection_data;
     }
     //nothing cached - create new connection...
     $connection_data = new stdClass();
     $connection_data->connection_index = count($this->connections_cache_active) + 1;
     $connection_data->connected = 0;
     $connection_data->connection_handle = NULL;
     $connection_data->ssh_base_dir = '';
     $connection_data->sftp_handle = NULL;
     $connection_data->last_used = $this->getMicroTime();
     //---------------------------------------------------------------------------------------------------------------
     if (PHP_SSH2MST_DEBUG) {
         echo "Creating SSH Connection {$connection_data->connection_index}\n";
     }
     //---------------------------------------------------------------------------------------------------------------
     if ($connection_data->connection_handle = ssh2_connect($this->host, $this->port, $this->ssh_methods, $this->ssh_callbacks)) {
         if (ssh2_auth_password($connection_data->connection_handle, $this->user, $this->pass)) {
             if ($connection_data->sftp_handle = ssh2_sftp($connection_data->connection_handle)) {
                 if ($this->host_fingerprint) {
                     if ($this->host_fingerprint != ssh2_fingerprint($connection_data->connection_handle, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX)) {
                         $this->error = 'Wrong Server Fingerprint.';
                         $this->disconnect();
                     }
                 }
                 $connection_data->ssh_base_dir = 'ssh2.sftp://' . $connection_data->sftp_handle;
                 $connection_data->connected = 1;
             } else {
                 $this->error = 'Unable to get SFTP subsystem handle.';
             }
         } else {
             //---------------------------------------------------------------------------------------------------------------
             if (PHP_SSH2MST_DEBUG) {
                 echo "SSH authentication failed....\n";
             }
             //---------------------------------------------------------------------------------------------------------------
             $this->error = 'Authentication failed.';
         }
     } else {
         //---------------------------------------------------------------------------------------------------------------
         if (PHP_SSH2MST_DEBUG) {
             echo "SSH connection failed\n";
         }
         //---------------------------------------------------------------------------------------------------------------
         $this->error = 'Unable to connect to remote server.';
     }
     //save in active list...
     $this->connections_cache_active[] = $connection_data;
     return $connection_data;
 }
Example #16
0
 function CreateConn($SSH_Host, $SSH_Username, $SSH_Password, $SSH_Port, $Known_Fingerprint)
 {
     if ($this->Conn = ssh2_connect($SSH_Host, $SSH_Port) or die('Unable To Reach SSH Server for connection')) {
         if (ssh2_fingerprint($this->Conn) != $Known_Fingerprint) {
             die("HOSTKEY MISMATCH!\n" . "Possible Man-In-The-Middle Attack?");
         }
         if (!ssh2_auth_password($this->Conn, $SSH_Username, $SSH_Password)) {
             die("Password Authentication Failed.");
         } else {
             return true;
         }
     } else {
         return false;
     }
 }
Example #17
0
//print report
echo PHP_EOL . PHP_EOL . PHP_EOL;
echo 'Package Script Report:' . PHP_EOL;
echo '----------------------' . PHP_EOL;
foreach ($final_status as $module => $status) {
    echo $status . PHP_EOL;
}
echo '----------------------' . PHP_EOL . PHP_EOL;
if ($vars['interactive'] && !empty($supported['version']) && !empty($final_status)) {
    $publish = freepbx::getInput('Publish?', 'n');
    if ($publish == 'y' || $publish == 'yes') {
        if (function_exists('ssh2_connect')) {
            foreach ($final_status as $module => $status) {
                $supported = freepbx::getInput('Supported Version to Publish for?', $supported['version']);
                $connection = ssh2_connect('mirror1.freepbx.org');
                $fingerprint = ssh2_fingerprint($connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
                if (strcmp("B5CA3DA1C15FA48CC70746EE7BCEACA5", $fingerprint) !== 0) {
                    freepbx::out("Unable to verify server identity!");
                    exit(1);
                }
                $user = posix_getpwuid(posix_geteuid());
                $username = freepbx::getInput('Username?', $user['name']);
                $ssh_auth_pub = $username == 'root' ? '/root/.ssh/id_rsa.pub' : '/home/' . $username . '/.ssh/id_rsa.pub';
                $ssh_auth_priv = $username == 'root' ? '/root/.ssh/id_rsa' : '/home/' . $username . '/.ssh/id_rsa';
                $ssh_auth_pass = !file_exists($ssh_auth_pub) || !file_exists($ssh_auth_priv) ? freepbx::getPassword("Password?") : null;
                if (!ssh2_auth_pubkey_file($connection, $username, $ssh_auth_pub, $ssh_auth_priv, $ssh_auth_pass)) {
                    freepbx::out('Autentication rejected by server');
                    exit(1);
                }
                $packager = "/usr/src/freepbx-server-dev-tools/server_packaging.php";
                if (!($stream = ssh2_exec($connection, "ls " . $packager))) {
 /**
  * Check if the SSH server public key fingerprint is valid
  *
  * @param resource $connection
  *
  * @return string Server public key fingerprint
  */
 protected function __checkFingerprint($connection)
 {
     $knownHost = false;
     try {
         $fingerprint = ssh2_fingerprint($connection, SSH2_FINGERPRINT_MD5);
         if (file_exists(static::$knownHostsFile)) {
             $file = new SplFileObject(static::$knownHostsFile);
             $file->setFlags(SplFileObject::READ_CSV);
             $file->setCsvControl(' ');
             foreach ($file as $entry) {
                 list(, , $fp) = $entry;
                 $fp = md5(base64_decode($fp));
                 $knownHost = strcasecmp($fp, $fingerprint) === 0;
                 if ($knownHost) {
                     break;
                 }
             }
         }
         $knownHost = $knownHost || !static::$strictHostKeyChecking;
         if ($knownHost === false) {
             throw new ModuleException(__CLASS__, 'Unable to verify server identity!');
         }
     } catch (RuntimeException $e) {
         if (static::$strictHostKeyChecking) {
             throw new ModuleException(__CLASS__, 'Unable to verify server identity!');
         }
     }
     return $fingerprint;
 }
Example #19
0
 /**
  * Get server fingerprint
  * @note A ssh2/scp/sftp only feature
  */
 public function getFingerprint()
 {
     return ssh2_fingerprint($this->ssh);
 }
Example #20
0
 /**
  * Starts a new connection
  * 
  * @param string $host     Give the remote hostname or IP address
  * @param string $username Give the authentication username
  * @param string $password Give the authentication password
  * @param string $port     Give the network port
  * 
  * @return void
  */
 public function connect($host, $username, $password = '', $port = 22)
 {
     // Start connection
     if (!($this->connection = @ssh2_connect($host, $port))) {
         throw new DualityException('Cannot connect to server', DualityException::E_REMOTE_NOTCONNECTED);
     }
     // Verify fingerprint
     $fingerprint = @ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
     if (!empty($this->ssh_fingerprint) && strcmp($this->ssh_fingerprint, $fingerprint) !== 0) {
         throw new DualityException('Unable to verify server identity!', DualityException::E_REMOTE_FINGERPRINTNOTFOUND);
     }
     // Try auth methods
     if (!empty($password)) {
         if (!@ssh2_auth_password($this->connection, $username, $password)) {
             throw new DualityException('Autentication rejected by server', DualityException::E_REMOTE_AUTHFAILED);
         }
     } else {
         $public_key_path = sprintf($this->ssh_auth_pub, $username);
         $private_key_path = sprintf($this->ssh_auth_priv, $username);
         if (!ssh2_auth_pubkey_file($this->connection, $username, $public_key_path, $private_key_path, $this->ssh_auth_pass)) {
             throw new DualityException('Autentication rejected by server', DualityException::E_REMOTE_AUTHFAILED);
         }
     }
 }
Example #21
0
 /**
  * Verify host fingerprint
  * 
  * Verifies the host fingerprint.
  * 
  * @return TRUE on success, FALSE on failure
  */
 protected function verify_host_fingerprint()
 {
     //Get the hosts fingerprint
     $fingerprint = ssh2_fingerprint($this->_conn_link);
     //Check the returned fingerprint, to the one expected
     if ($this->_config['host_fingerprint'] === $fingerprint) {
         return TRUE;
     } else {
         return FALSE;
     }
 }
Example #22
0
 /**
  * Verifies remote server fingerprint.
  * @param resource $session SSH session.
  * @param string $expectedFingerprint expected remote server fingerprint
  * @throws Exception if fingerprint missmatches.
  */
 protected function verifyFingerprint($session, $expectedFingerprint)
 {
     $fingerprint = ssh2_fingerprint($session, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
     if (strcmp($expectedFingerprint, $fingerprint) !== 0) {
         throw new Exception("Invalid remote server fingerprint: '{$fingerprint}' does not match expected '{$expectedFingerprint}'");
     }
 }
Example #23
0
 /**
  * Get the servers hostkey/fingerprint.
  *
  * @param string $algorithm sha1|md5
  * @param string $encoding  hex|raw
  *
  * @return string
  *
  * @throws UnexpectedValueException if $algorithm or $encoding is incorrect
  */
 public function fingerprint($algorithm = 'sha1', $encoding = 'hex')
 {
     return ssh2_fingerprint($this->getFingerprintAlgorithmId($algorithm) | $this->getFingerprintEncodingId($encoding));
 }
Example #24
0
 /**
  * @{inheritDoc}
  */
 public function __construct(SessionInterface $session, AuthInterface $auth, OutputInterface $output)
 {
     self::registerErrorHandler();
     // Set the base object properties
     parent::__construct($session, $output);
     $this->printOut('<info>Connecting...</info>');
     $this->printDebug('$session => ' . var_export($session, true));
     $this->printVerbose('Connecting to ' . $session->getHost() . ' at port ' . $session->getPort());
     // Validate ssh2 session
     if (!$session->valid()) {
         throw new RuntimeException('SSH connection failed.');
     }
     $this->printVerbose('Connected.');
     $this->printDebug('$auth => ' . var_export($auth, true));
     $this->printVerbose('Authorize...');
     // Authorize
     try {
         $authorized = $auth->authorize($session);
     } catch (ErrorException $e) {
         throw new RuntimeException('SSH authorization failed. REASON : ' . $e->getMessage());
     }
     $this->printVerbose('Authorized');
     $this->session = $session;
     $this->auth = $auth;
     $this->printDebug('HOST FINGERPRINT: ' . ssh2_fingerprint($this->session->getConnection()));
 }
Example #25
0
 public function getFingerprint(SSHConnection $context)
 {
     return ssh2_fingerprint($this->resource, SSH2_FINGERPRINT_MD5 | \SSH2_FINGERPRINT_HEX);
 }