An experimental object oriented SSH api in PHP

Related tags

Security php-ssh
Overview

PHP SSH

Build Status (master)

Provides an object-oriented wrapper for the php ssh2 extension.

Requirements

You need PHP version 5.3+ with the SSH2 extension.

Installation

The best way to add the library to your project is using composer.

$ composer require herzult/php-ssh:~1.0

Usage

Configuration of the connection

To establish an SSH connection, you must first define its configuration. For that, create a Configuration instance with all the needed parameters.

<?php

// simple configuration to connect "my-host"
$configuration = new Ssh\Configuration('my-host');

The available configuration classes are:

  • Configuration
  • SshConfigFileConfiguration

Both connection configuration and public/private key authentication can be obtained from a ssh config file such as ~/.ssh/config

<?php

// simple configuration to connect "my-host"
$configuration = new Ssh\SshConfigFileConfiguration('/Users/username/.ssh/config', 'my-host');
$authentication = $configuration->getAuthentication('optional_passphrase', 'optional_username');

Create a session

The session is the central access point to the SSH functionality provided by the library.

<?php

// ... the configuration creation

$session = new Ssh\Session($configuration);

Authentication

The authentication classes allow you to authenticate over a SSH session. When you define an authentication for a session, it will authenticate on connection.

<?php

$configuration = new Ssh\Configuration('myhost');
$authentication = new Ssh\Authentication\Password('John', 's3cr3t');

$session = new Session($configuration, $authentication);

The available authentication are:

  • None for username based authentication
  • Password for password authentication
  • PublicKeyFile to authenticate using a public key
  • HostBasedFile to authenticate using a public hostkey
  • Agent to authenticate using an ssh-agent

Authentication from SshConfigFileConfiguration

If you use an ssh config file you can load your authentication and configuration from it as follows:

<?php

$configuration = new Ssh\SshConfigFileConfiguration('~/.ssh/config', 'my-host');

$session = new Session($configuration, $configuration->getAuthentication());

This will pick up your public and private keys from your config file Host and Identity declarations.

Subsystems

Once you are authenticated over a SSH session, you can use the subsystems.

Sftp

You can easily access the sftp subsystem of a session using the getSftp() method:

<?php

// the session creation

$sftp = $session->getSftp();

See the Ssh\Sftp class for more details on the available methods.

Publickey

The session also provides the getPublickey() method to access the publickey subsystem:

<?php

// ... the session creation

$publickey = $session->getPublickey();

See the Ssh\Publickey class for more details on the available methods.

Exec

The session provides the getExec() method to access the exec subsystem

<?php

// ... the session creation

$exec = $session->getExec();

echo $exec->run('ls -lah');

See the Ssh\Exec class for more details.

Comments
  • 29 scan directory recursive fix

    29 scan directory recursive fix

    We have to check the case when the function returns false if directory is empty. Otherwise error will be thrown: "array_merge(): Argument #2 is not an array"

    opened by Valdocco 8
  • RuntimeException during installation of composer

    RuntimeException during installation of composer

    We use deployphp to deploy projects to our servers but sinds a little while composer changed there output from writing lines to writing error's in some cases but the installation is still succesvol. So there is an open issue at deployphp https://github.com/deployphp/deployer/issues/201 library that try's to fix this and they solved it for PhpSecLib server implementation but they also use this library to connect to servers.

    In conclusion is it possible to check the output result on exit code like deployphp does for PhpSecLib instead of checking the error output?

    • https://github.com/Herzult/php-ssh/blob/master/src/Ssh/Exec.php#L26

    More details

    • https://github.com/deployphp/deployer/issues/201
    • https://github.com/deployphp/deployer/pull/199
    • https://github.com/composer/composer/issues/1905#issuecomment-41631659
    opened by cmodijk 7
  • Composer install issue when ssh2 not available

    Composer install issue when ssh2 not available

    The php-ssh dependency has a hard dependency on the ssh extension.

     "ext-ssh2": "*"
    

    Possible solution is to make ext-ssh2 a suggest instead of a require.

    It will help to install libs which uses php-ssh as require.

    opened by antonmedv 6
  • php7 + ext-ssh2 on debian 8 ?

    php7 + ext-ssh2 on debian 8 ?

    hot to install the dependency extension ext-ssh2 on debian 8 ?

    - herzult/php-ssh v1.1.1 requires ext-ssh2 * -> the requested PHP extension ssh2 is missing from your system
    
    opened by ibasaw 5
  • Fix recursion when listing directories

    Fix recursion when listing directories

    Sftp::scanDirectory() always recursively scans a whole directory tree even if no recursion is wanted. This patch uses scandir instead of the recursive method-call to avoid this.

    Because this patch uses scandir() there might be the same problems described in an issue and pull request.

    This is my first pull request ever, so feel free to point out things I made wrong.

    opened by woiwa 5
  • Provide ability to configure connection and authentication from a ssh config file such as ~/.ssh/config

    Provide ability to configure connection and authentication from a ssh config file such as ~/.ssh/config

    This PR provides the ability to get connection and authentication from a config file based on host matching. It uses the PublicKeyFile authentication if an IdentityFile is specified in the matching hosts configuration. The configuration options it pick up from the config file are HostName and Port. User and Identity file are used in the auth if available.

    If your Identity file doesn't have a User declaration then you can pass one into getAuthentication. If your key is encrypted with a passphrase you can pass this in to getAuthentication.

    This enables the follow types of usage:

    ~/.ssh/config

    Host test testing.com
        User test
        HostName 111.111.111.111
            Port 1234
        IdentityFile ~/.ssh/id_dsa_testing
    
    <?php
    $configuration = new Ssh\SshConfigFileConfiguration('~/.ssh/config', 'test');
    $session = new Session($configuration, $configuration->getAuthentication());
    
    <?php
    $configuration = new Ssh\SshConfigFileConfiguration('~/.ssh/config', 'testing.com');
    $session = new Session($configuration, $configuration->getAuthentication());
    
    opened by camspiers 5
  • Add exec support, fix for unlink

    Add exec support, fix for unlink

    ssh2_exec() support for remote execution of SSH commands. Usage:

    
    $exec = $session->getExec();
    $exec->run('touch hello');
    
    

    This would execute the touch hello command on the remote server.

    In addition I found an error in the Ssh\Sftp::unlink() method, it was using the incorrect function, and would never work properly.

    opened by awildeep 4
  • Run intval on SFTP resource.

    Run intval on SFTP resource.

    As of 5.6.28, it is necessary to execute intval on the SFTP Resource when parsing the URL. See: http://paul-m-jones.com/archives/6439

    Note: I have not tested this on PHP < 5.6.28, but I have tested and confirmed fixed for PHP 7.1.3.

    opened by michaeljoelphillips 3
  • Ssh\Exec : Wrong error code test

    Ssh\Exec : Wrong error code test

    Hi,

    If i am correct, the test in Exec is

            if ((int) $match[1] !== 0) {
                throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]);
            }
    

    but on Unix 0 means SUCCESS and 1 means ERROR

    opened by Niiko 2
  • Rely on last command exit status to raise error

    Rely on last command exit status to raise error

    Some tools like composer write human-related non-error messages to stderr, thus it's not safe to rely on stderr to decide if the command failed.

    More info:

    • https://github.com/composer/composer/issues/3795#issuecomment-76401013
    • https://github.com/composer/composer/issues/1905#issuecomment-41631659
    • https://github.com/composer/composer/pull/3715#issuecomment-73271923

    Inspiration:

    • http://stackoverflow.com/questions/10478491/php-ssh2-exec-channel-exit-status
    • http://stackoverflow.com/questions/18278023/php-net-ssh2-exec-how-to-get-the-command-return-code
    opened by gquemener 2
  • Added dircheck parameter to scanDirectory method in Sftp

    Added dircheck parameter to scanDirectory method in Sftp

    This will stop the method from going into the rabbit hole when there is no need. I am not sure this would be the way to do it I think it is at least an improvement.

    opened by Fgruntjes 2
  • Project status

    Project status

    As title, it seems that this project has been inactive for about over three years.

    Many issues are wait for reply/feedback and PRs need to be reviewed/merged.

    @Herzult and @h4cc, do you have any idea about this?

    opened by peter279k 2
  • cast ssh resource into int to be compliant with php >=7.0

    cast ssh resource into int to be compliant with php >=7.0

    With php >=7.0, I have the following error when I try to create a directory to a sftp server:

    The directory 'my_dir' does not exist and could not be created. at /my_project/vendor/knplabs/gaufrette/src/Gaufrette/Adapter/Sftp.php:209)"}
    

    The gaufrette adapter fails because of the Ssh\Sftp:getUrl() method returning an url like ssh2.sftp://Resource id #324/my_dir, which is incompatible in php >=7.0.

    The following bug describe my issue: https://bugs.php.net/bug.php?id=73561

    It is solvable by casting the resource into int before inject it in the url.

    opened by paulandrieux 1
  • getenv('HOME') sometimes returns false

    getenv('HOME') sometimes returns false

    This causes SshConfigFileConfiguration::processPath to turn ~/folder into /folder and cause an error.

    There are others you can fallback onto ($_SERVER['HOME'] for one) and as a final fallback it should assume the dirname(dirname($file)) of the config file is home (A setter for manually setting it would also be nice)

    opened by jnvsor 0
  • SshConfigFileConfiguration::getAuthentication() automatic identityflie

    SshConfigFileConfiguration::getAuthentication() automatic identityflie

    Most SSH clients will automatically look for keys in the folder with the config. It would be nice if getAuthentication would return a class that could try them one at a time (Like an SSH client) if the config section was missing an identityfile

    opened by jnvsor 0
  • New SCP Subsystem

    New SCP Subsystem

    Hi,

    As I suggested in issue #65, I implemented SCP subsystem, I would be glad to have your feedback about this feature. Hoping It will be useful.

    (Edit) Also, I didn't commit PhpUnitTest as I was unable to run existing ones, if someone can confirm that they are broken ?

    Cheers,

    Flavien

    opened by flavienaudin 0
Releases(v1.1.1)
Owner
Antoine Hérault
Antoine Hérault
Antware NinjaCrypter is an experimental username and password cookie string class for PHP

Antware NinjaCrypter is an experimental username and password cookie string class for PHP. For study case this crypter is based on password crypting ideology but can also encrypt username and password for storing cookie string that way your login details will not be exposed by hackers that search through cookie string.

Chukwu Remijius 1 Nov 25, 2021
A cryptography API wrapping the Sodium library, providing a simple object interface for symmetrical and asymmetrical encryption, decryption, digital signing and message authentication.

PHP Encryption A cryptography API wrapping the Sodium library, providing a simple object interface for symmetrical and asymmetrical encryption, decryp

null 19 Dec 31, 2022
JSON Object Signing and Encryption library for PHP.

NAMSHI | JOSE Deprecation notice Hi there, as much as we'd like to be able to work on all of the OSS in the world, we don't actively use this library

Namshi 1.7k Dec 22, 2022
HTML/PHP/CSS website that tracks two API data

Detailed instructions on how to build and run Step 1: download XAMPP for a live web server XAMPP download 1 XAMP download 2 Step 2: Download all files

Winsor Tse 0 Jun 2, 2022
Api random address

RandomAddress what actually it does? Its scrap Address from Fakeaddress and gives output in json format for api use. This address are working many pla

Nitin1818 6 Dec 28, 2022
Run locally to export crypto tx data from crypto exchanges using their api connections, and process into a normalised format.

CryptoCredible The missing crypto-exchange data exporter tldr: run locally to export your crypto tx data from popular exchanges via api connections. E

Lee Overy 6 Apr 6, 2022
SЁCU is a public API to store self-destructing data payloads with url shortener and handle anonymous chat-rooms.

SЁCU Introduction SЁCU is a public API to store self-destructing data payloads. This repository includes only backend part using Laravel framework. Fr

SЁCU 27 Nov 21, 2022
Secure API Toolkit

Sapient: Secure API toolkit Sapient secures your PHP applications' server-to-server HTTP(S) traffic even in the wake of a TLS security breakdown (comp

Paragon Initiative Enterprises 315 Jan 3, 2023
PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application

PHPIDS PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web ap

null 752 Jan 3, 2023
php-chmod is a PHP library for easily changing permissions recursively.

PHP chmod php-chmod is a PHP library for easily changing the permissions recursively. Versions & Dependencies Version PHP Documentation ^1.1 ^7.4 curr

Mathias Reker ⚡️ 5 Oct 7, 2022
PHP 5.x support for random_bytes() and random_int()

random_compat PHP 5.x polyfill for random_bytes() and random_int() created and maintained by Paragon Initiative Enterprises. Although this library sho

Paragon Initiative Enterprises 8k Jan 5, 2023
PHP Secure Communications Library

phpseclib - PHP Secure Communications Library Supporting phpseclib Become a backer or sponsor on Patreon One-time donation via PayPal or crypto-curren

null 4.9k Jan 7, 2023
Simple Encryption in PHP.

php-encryption composer require defuse/php-encryption This is a library for encrypting data with a key or password in PHP. It requires PHP 5.6 or new

Taylor Hornby 3.6k Jan 3, 2023
Standards compliant HTML filter written in PHP

HTML Purifier HTML Purifier is an HTML filtering solution that uses a unique combination of robust whitelists and aggressive parsing to ensure that no

Edward Z. Yang 2.7k Jan 5, 2023
A database of PHP security advisories

PHP Security Advisories Database The PHP Security Advisories Database references known security vulnerabilities in various PHP projects and libraries.

null 1.9k Dec 18, 2022
A php.ini scanner for best security practices

Scanner for PHP.ini The Iniscan is a tool designed to scan the given php.ini file for common security practices and report back results. Currently it

psec.io 1.5k Dec 5, 2022
🤖 Id obfuscation based on Knuth's multiplicative hashing method for PHP.

Optimus id transformation With this library, you can transform your internal id's to obfuscated integers based on Knuth's integer hash. It is similar

Jens Segers 1.2k Jan 2, 2023
㊙️ AntiXSS | Protection against Cross-site scripting (XSS) via PHP

㊙️ AntiXSS "Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inje

Lars Moelleken 570 Dec 16, 2022
TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library

About TCrypto is a simple and flexible PHP 5.3+ in-memory key-value storage library. By default, a cookie will be used as a storage backend. TCrypto h

timoh 57 Dec 2, 2022