phpseclib
PHP Secure Communications Library
phpseclib: pure PHP implementations of SSH, SFTP, RSA and X.509 easy to use, easy to install, actively maintained and actively supported, phpseclib is the best way to utilize ssh, sftp, rsa and x.509 in php
I have an issue that's stumped me.
I'm trying to automate a CLI login to a router and run some commands obtained via a webpage. However I don't know if the router has telnet or SSH enabled (might be one,the other, or both) and I have a list of possible username/password combos that I need to try to gain access.
Oh, and I can't change either the protocol type or the credentials on the device, so that's not really an option.
I was able to figure out how to login to a router with a known protocol and login credentials and run the necessary commands(included below), but I don't know if I should use an if/else block to work through the telnet/ssh decisions, or if a switch statement might be better? Would using Expect inside PHP be an easier way to go?
function tunnelRun($commands,$user,$pass, $yubi){
$cpeIP = "1.2.3.4";
$commands_explode = explode("\n", $commands);
$screenOut = "";
$ssh = new Net_SSH2('router_jumphost');
if (!$ssh->login($user, $pass . $yubi)) {
exit('Login Failed');
}
$ssh->setTimeout(2);
$ssh->write("ssh -l username $cpeIP\n");
$ssh->read("assword:");
$ssh->write("password\n");
$ssh->read("#");
$ssh->write("\n");
$cpePrompt = $ssh->read('/.*[#|>]/', NET_SSH2_READ_REGEX);
$cpePrompt = str_replace("\n", '', trim($cpePrompt));
$ssh->write("config t\n");
foreach ($commands_explode as $i) {
$ssh->write("$i\n"); // note the "\n"
$ssh->setTimeout(2);
$screenOut .= $ssh->read();
}
$ssh->write("end\n");
$ssh->read($cpePrompt);
$ssh->write("exit\n");
echo "Router Update completed! Results below:<br><br>";
echo "<div id=\"text_out\"><textarea style=\" border:none; width: 700px;\" rows=\"20\">".$screenOut."</textarea></div>";
Update:
The solution I went with was a while/switch loop. I would of gone the Expect route, but I kept running into issues on getting the Expect module integrated into PHP on my server (Windows box.) If I had been using a Unix/Linux server Expect would of been the simplest way to achieve this.
I just made it into a working demo for now, so there are a lot of variations missing from the case statements still, and error-handling still needs to bef figured out, but the basic idea is there. I still want to move the preg_match statements around a bit more to do the matching at the top of the while loop (so I don't spam the whole case section with different preg_match lines), but that may prove to be more work than I want for now. Hope this might help someone else trying to do the same!
<?php
include('Net/SSH2.php');
define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);
ini_set('display_errors', 1);
$conn = new Net_SSH2('somewhere.outthere.com');
if (!$conn->login($user, $pass . $yubi)) {
exit('Login Failed');
}
$prompt = "Testing#";
$conn->setTimeout(2);
$conn->write("PS1=\"$prompt\"");
$conn->read();
$conn->write("\n");
$screenOut = $conn->read();
//echo "$screenOut is set on the shell<br><br>";
echo $login_db[3][0]. " ". $login_db[3][1];
$logged_in = false;
$status = "SSH";
$status_prev = "";
$login_counter = 0;
while (!$logged_in && $login_counter <=3) {
switch ($status) {
case "Telnet":
break;
case "SSH":
$conn->write("\n");
$conn->write("ssh -l " . $login_db[$login_counter][0] . " $cpeIP\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/Permission denied.*/', $status) ? true : false):
$conn->write(chr(3)); //Sends Ctrl+C
$status = $conn->read();
if (strstr($status, "Testing#")) {
$status = "SSH";
$login_counter++;
break;
} else {
break 2;
}
case (preg_match('/[pP]assword:/', $status) ? true : false):
$conn->write($login_db[$login_counter][1] . "\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/yes\/no/', $status) ? true : false):
$conn->write("yes\n");
$status_prev = $status;
$status = $conn->read('/\n([.*])$/', NET_SSH2_READ_REGEX);
break;
case (preg_match('/(^[a-zA-Z0-9_]+[#]$)|(>)/', $status,$matches) ? true : false):
$conn->write("show version\n");
$status = $conn->read(">");
if(preg_match('/ADTRAN|Adtran|Cisco/', $status)? true:false){
$logged_in = true;
break;
}
default:
echo "<br>Something done messed up! Exiting";
break 2;
}
//echo "<pre>" . $conn->getLog() . "</pre>";
}
if ($logged_in === true) {
echo "<br> Made it out of the While loop cleanly";
} else {
echo "<br> Made it out of the While loop, but not cleanly";
}
echo "<pre>" . $conn->getLog() . "</pre>";
$conn->disconnect();
echo "disconnected cleanly";
}
?>
Source: (StackOverflow)
OK, so accessing other servers from your own via either ftp or sftp... I have written a small class to handle either.. It is obviously new and could easily be improved so thought i would throw it out here and see what other people think (stackoverflow gets a hell of a lot of views so hopefully this could help someone else), and how they can improve on it... so i guess the question is... how can this be improved?
class ftp_sftp{
//determine, if ssh, to use phpseclib or php's inbuilt ssh_sftp 'libssh'
public $ssh_type = 'phpseclib';
//set ths path to the directory containing the entire phpseclib files
public $phpseclib_path = 'scripts/phpseclib0.3.0';
//private vars generated by this class
public $host;
public $username;
public $password;
public $connection_type;
public $port_number;
public $connection = false;
//contruct method which will attempt to set the connection details and automatically attempt to establisha connection to the server
public function __construct( $host, $username, $password, $connection_type, $port_number = false ){
//add the webroot to the beginning of the $this->phpseclib_path (this is bespoke to my own configuration)
$this->phpseclib_path = WEBROOT_PRIVATE.$this->phpseclib_path;
//setting the classes vars
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->connection_type = $connection_type;
//set the port number to defaults based on connection type if none passed
if( $port_number === false ){
if( $connection_type == 'ftp' ){
$port_number = 21;
} else {
$port_number = 22;
}
}
$this->port_number = $port_number;
//now set the server connection into this classes connection var
$this->connection = $this->connect();
}
//tests the details passed and tries to establish a connection, returns false on fail.
function connect(){
br($this->connection_type);
switch( $this->connection_type )
{
case 'ftp':
$connection = ftp_connect($this->host);
$login = ftp_login($connection, $this->username, $this->password);
//if no connection was possible return false and leave $this-connection as false
if(!$connection || !$login){
return false;
} else {
// enabling passive mode
ftp_pasv( $connection, true );
return $connection;
}
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
//inlcude the phpseclib path in the include array and include the ssh2 class
set_include_path($this->phpseclib_path );
if(!include('Net/SSH2.php')){
echo 'Sorry failed to load SSH2 class';
br();
}
if(!include('Net/SFTP.php')){
echo 'Sorry failed to load SFTP class';
br();
}
$connection = new Net_SFTP($this->host, $this->port_number);
$login = $connection->login($this->username, $this->password);
break;
case 'libssh2':
$connection = ssh2_connect($this->host, $this->port_number);
$login = ssh2_auth_password($connection, 'username', 'secret');
break;
default:
echo 'No ssh method defined, please define one in: $ftp_sftp->ssh_type';
exit();
break;
}
//if no connection was possible return false and leave $this-connection as false
if (!$connection || !$login) {
return false;
} else {
return $connection;
}
break;
default: echo 'No connection type set cannot choose a method to connect';
break;
}
}
//acces the phpseclib errors
public function errors(){
if($this->connection_type == 'sftp' && $this->ssh_type == 'phpseclib'){
print_r($this->connection->getErrors());
} else {
echo 'no error logs available';
}
}
//function used by this class to check certain values are set
public function connection_check(){
if( $this->connection === false){
echo 'Sorry there seems to be a connection problem please try again';
br();
}
if( $this->connection_type === false){
echo 'Sorry there seems to be a no connection type set';
}
if( $this->connection === false || $this->connection_type === false ){
exit();
}
}
//transfers a file to the connected server
public function put($targetLocationToSendTo, $existingLocationToSendFrom){
//check the connection
$this->connection_check();
switch( $this->connection_type )
{
case 'ftp':
//ftp_put the file across
$put = ftp_put( $this->connection, $targetLocationToSendTo, $existingLocationToSendFrom, FTP_BINARY);
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$put = $this->connection->put( $targetLocationToSendTo, $existingLocationToSendFrom, NET_SFTP_LOCAL_FILE );
break;
case 'libssh2':
$put = ssh2_scp_send($this->connection, $targetLocationToSendTo, $existingLocationToSendFrom, 0755);
break;
}
break;
}
return $put;
}
//list the contents of a remote directory
public function dir_list( $dirToList ){
//check the connection
$this->connection_check();
//run appropriate list
switch( $this->connection_type )
{
case 'ftp':
$list = $this->connection = ftp_nlist($this->connection, $dirToList);
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$list = $this->connection->nlist( $dirToList );
break;
case 'libssh2':
echo 'Sorry there is no support for nlist with libssh2, however this link has a possible answer: http://randomdrake.com/2012/02/08/listing-and-downloading-files-over-sftp-with-php-and-ssh2/';
break;
}
break;
}
return $list;
}
//get the timestamp of the file on another server
public function remote_filemtime( $pathToFile ){
//check the connection
$this->connection_check();
//run appropriate list
switch( $this->connection_type )
{
case 'ftp':
$timeStamp = ftp_mdtm($this->connection, $pathToFile);
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$statinfo = $this->connection->stat( $pathToFile );
break;
case 'libssh2':
$statinfo = ssh2_sftp_stat($this->connection, $pathToFile);
break;
}
if($statinfo['mtime']){
$timeStamp = $statinfo['mtime'];
} else {
$timeStamp = false;
}
break;
}
return $timeStamp;
}
//make a directory on the remote server
public function make_dir( $dirToMake ){
//check the connection
$this->connection_check();
//run appropriate list
switch( $this->connection_type )
{
case 'ftp':
$dir_made = ftp_mkdir($this->connection, $dirToMake);
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$statinfo = $this->connection->mkdir( $dirToMake );
break;
case 'libssh2':
$statinfo = ssh2_sftp_mkdir($this->connection, $dirToMake, 0755);
break;
}
break;
}
return $dir_made;
}
//change directory
public function change_dir( $dirToMoveTo ){
//check the connection
$this->connection_check();
//run appropriate list
switch( $this->connection_type )
{
case 'ftp': $chdir = ftp_chdir($this->connection, $dirToMoveTo );
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$chdir = $this->connection->chdir( $dirToMoveTo );
break;
case 'libssh2':
echo 'Sorry this feature does exist yet for when using libssh2 with the ftp_sftp class';
exit();
break;
}
break;
}
return $chdir;
}
//curent directory we are looking in
public function pwd(){
//check the connection
$this->connection_check();
//run appropriate list
switch( $this->connection_type )
{
case 'ftp': $pwd = ftp_pwd($this->connection);
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$pwd = $this->connection->pwd();
break;
case 'libssh2':
echo 'Sorry this feature does exist yet for when using libssh2';
exit();
break;
}
break;
}
return $pwd;
}
//delete file
public function delete_file($fileToDelete){
//check the connection
$this->connection_check();
//run appropriate list
switch( $this->connection_type )
{
case 'ftp': $unlink = ftp_delete($this->connection, $fileToDelete);
break;
case 'sftp':
//decide which ssh type to use
switch( $this->ssh_type ){
case 'phpseclib':
$unlink = $this->connection->delete( $fileToDelete );
break;
case 'libssh2':
$unlink = ssh2_sftp_unlink($this->connection, $fileToDelete);
break;
}
break;
}
return $unlink;
} }//end of class
Using the class:
$ftp_sftp = new ftp_sftp( '92.21.627.163', 'ftpuser', 'yourpassword', '', 'ftp', '21' );
echo $ftp_sftp->pwd();
I am having a little trouble getting the phpseclib to connect on my win7 machine using easyPHP and have started a Q.. if anyone has any ideas i would be very grateful...
Cannot get phpseclib to connect - error 10060
Source: (StackOverflow)
I have implemented RSA cryptography using in php, javascript, and android app using library:
1) phpseclib for php side
2) pidcrypt for javascript
3) bouncrycastle version(bcprov-jdk14-151) for anrdroid serviceprovider
I have my cryptography mechanism like:
user->request->publickey
->server->generate(publickey,privatekey) and save private key into Database
->server->sendpublickey->user
->user->encryptdata->send->server->decrypt
however this mechanism works fine between javascript and php encryption and decryption but in android platform when server send public key. It cannot decrypt the public key.
now i have tested different scenario for this
PHP KeyGenerating
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
define('CRYPT_RSA_EXPONENT', 65537);
extract($rsa->createKey(1024));
PHP DecryptingCode
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
$rsa->loadKey($pri);
$binaryCiphertext=base64_decode($encrypted);
$strBase64DecryptedData=$rsa->decrypt($binaryCiphertext);
$plaintText = base64_decode($strBase64DecryptedData);
as my public key is.
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBALrBdN8F83hT2+pBsAwiNx+v3FWp51IdEElE8UvVhfZYmePbitpzLcJi
jZ4/tvRFXJGhqa3PKPUQkH2F4VrHruA2kNceiL/Btywc9oM+tDMeX1jcRKwXwK1k
KdccKwn0qywG6YxQuqWQIotOfV+IIuhcHdaHBl6CZ05/cBo6AlMlAgMBAAE=
-----END RSA PUBLIC KEY-----
1) request key from server and server generates publickey and private key and send public key MODULUS and EXPONENT to android app and apply this code :
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(mod,exp);
KeyFactory keyFactory = KeyFactory.getInstance("RSA","BS");
PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BS");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plaintText.getBytes());
byte[] encodedBytes = org.bouncycastle.util.encoders.Base64.encode(encryptedBytes);
String encryptedData = new String(encodedBytes);
this code unable to decrypt message and i get this error from PHP SIDE
Decryption error in /security/RSA.php on line **2493**
RSA.php 2493 code
if (ord($em[0]) != 0 || ord($em[1]) > 2) {
user_error('Decryption error');
return false;
}
2) Second scenario is getting the publick key string and parse it
byte[] keyBytes = Base64.decode(keyString, Base64.DEFAULT);
String rsaPublicKeyString = new String(keyBytes);
String sliceKeyHeader = rsaPublicKeyString.replaceAll("(-+BEGIN RSA PUBLIC KEY-+\\r?\\n|-+END RSA PUBLICKEY-+\\r?\\n?)", "");
byte[] encodedDER = Base64.encode(sliceKeyHeader.getBytes(),Base64.DEFAULT);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedDER);
KeyFactory kf = KeyFactory.getInstance("RSA","BC");
PublicKey pkPublic = (PublicKey) kf.generatePublic(publicKeySpec);
with this i get error
java.security.spec.InvalidKeySpecException:
java.lang.ClassCastException: com.android.org.bouncycastle.asn1.DERApplicationSpecific
cannot be cast to com.android.org.bouncycastle.asn1.ASN1Sequence
I know that the encoded public key is DER encoded but still i dont know what to do here
--- i think someone can guide me with DER encode decode ---
3) The third scenario is
final Reader reader = new StringReader(rsaPublicKeyString);
PemReader pemReader = new PemReader(reader);
PemObject pemObject= pemReader.readPemObject();
pemReader.close();
AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(pemObject.getContent());
I forgot the error it was like
unable to cast pemObject to asymmetric ( not sure but something like that )
I even tried some of the codes from the above link but i am getting different errors
RSA Android Encrypt / RSA PHP Decrypt
PhpSeclib <-> BouncyCastle RSA
Please look into code and help me.
Source: (StackOverflow)
Let's say I have the following piece of code.
To test this, I change the server IP to mimic the error messages. The IP below doesn't exist so the Unhandled Exception
message is: Cannot connect to 10.199.1.7. Error 113. No route to host
This displays an ugly screen with PHP code. Is it possible to catch this error?
try {
$ssh = new Net_SSH2('10.199.1.7');
if (!$ssh->login('deploy', $key)) {
throw new Exception("Failed login");
}
} catch (Exception $e) {
???
}
Source: (StackOverflow)
I downloaded phpseclib-0.3.10 from http://phpseclib.sourceforge.net/
My php Version : PHP 5.2.4
OS : CentOS release 6.6
When I run following I am getting "Segmentation fault" at this line $ssh->login('username', 'password')
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include('Net/SSH2.php');
$ssh=new Net_SSH2('servername');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
?>
I am unable find the reason for this issue. Could you please help me to find the reason for this.
Source: (StackOverflow)
I have stumbled upon two functions i have never used before in php
set_include_path();
get_include_path();
I am currently looking to implement the phpseclib onto a project I am working on.. As i need to use the SFTP class extension of the SSH2 which in turn requires the MathBigInteger class.. etc etc.
The manual says about set_include_path():
"Sets the include_path configuration option for the duration of the script. "
What does this mean for the rest of my framework, will it set ALL include paths from the 'phpseclib' dir?
Also, I really don't get:
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
I am storing the php sec in a custom library directory in my file system, does get_include_path() some how magically find the phpseclib directory in my filesystem?
As you can see I am completely lost here.. could anyone be kind enough to shed some light for me please?
PS/
I only need this library at one partivular point in the application thus only want to include it when needed, at present I am wanting to include it within a child of my model class.
Source: (StackOverflow)
Here's how I'd do it with phpseclib (which works):
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setPassword('password');
$result = $rsa->loadKey('-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,E3B1C06E0D0C2633
gvmXzl6W7eV1a3N5rQNwBWKY9on3IgxZudS33cip5f88FotsPSDJMvqj6LVw2RxobDjhlOOzqmTb
VrlTnoQ6CogXFZSfiPmixiyyptCUEKJkSiEhYGM5GQm0OoGcLeLbgBb9tRpWh5IlXulKD6XFhx8q
/eGg5a+mSkX1i7kv2+Ih3jHmEKwrnfzhcA29pBF3OQJo+Ks9IYneuk676pHtsIs7CpFKq1tDvD8Q
O7URxnVnHLltaFvIxshqyZu92xbUYZR7YzjXl5+3w4TVgeAHUogEV+H9iZTosD/copUsbQO+78w2
E1D3iDS94wRgx0Tjv4xlwrTpOV38FS5rdL32492DcCRlCYM4VtuwjYeWi5shJg69jCb0EwGRqfAo
xko+lbKWELTuFKwD7n1rc/2fTarbGuf8S2AEggBLZyfXHC/9N84mXLFO2XKq+0WdiEFhQj2Cze+a
9qcSK6tPSrjK1LPlnOOppFgDElZaZ0rxsgjtiWSIAEw/Ad+SIM5u+vqwzF8J317JlsdKoBFDw8mS
MxCMuMksKJ23mgvY+THRIVgH3E7lEDZQzCi1Uy6ldLJcran/6wHwP88pVM2odiHkpnrJGcEBbbIk
qsxJZhFT8aUt/cUEBj3fnP7cxoNLQfTHMPqUTqKBWaVufFzGU9YB1R+XWFULLddwJHnV7gPheBlk
MDapowb+Is77+a9Y2VDsOXEvNpqTY0giiSrckG05IZnrhJ24JnSCwyNd99lm7XKdEGGrjBCMqIyI
Fqox8Ahkv3KWAJPYK1eOCc5d/KwZHlnlFJq7ZYy9u3fEnxQCjOEmeXLkLangKA==
-----END RSA PRIVATE KEY-----');
echo $result ? 'true' : 'false';
?>
For comparison purposes, however, I'm trying to do it with OpenSSL. Here's my code:
<?php
$pkey = openssl_pkey_get_private('-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,E3B1C06E0D0C2633
gvmXzl6W7eV1a3N5rQNwBWKY9on3IgxZudS33cip5f88FotsPSDJMvqj6LVw2RxobDjhlOOzqmTb
VrlTnoQ6CogXFZSfiPmixiyyptCUEKJkSiEhYGM5GQm0OoGcLeLbgBb9tRpWh5IlXulKD6XFhx8q
/eGg5a+mSkX1i7kv2+Ih3jHmEKwrnfzhcA29pBF3OQJo+Ks9IYneuk676pHtsIs7CpFKq1tDvD8Q
O7URxnVnHLltaFvIxshqyZu92xbUYZR7YzjXl5+3w4TVgeAHUogEV+H9iZTosD/copUsbQO+78w2
E1D3iDS94wRgx0Tjv4xlwrTpOV38FS5rdL32492DcCRlCYM4VtuwjYeWi5shJg69jCb0EwGRqfAo
xko+lbKWELTuFKwD7n1rc/2fTarbGuf8S2AEggBLZyfXHC/9N84mXLFO2XKq+0WdiEFhQj2Cze+a
9qcSK6tPSrjK1LPlnOOppFgDElZaZ0rxsgjtiWSIAEw/Ad+SIM5u+vqwzF8J317JlsdKoBFDw8mS
MxCMuMksKJ23mgvY+THRIVgH3E7lEDZQzCi1Uy6ldLJcran/6wHwP88pVM2odiHkpnrJGcEBbbIk
qsxJZhFT8aUt/cUEBj3fnP7cxoNLQfTHMPqUTqKBWaVufFzGU9YB1R+XWFULLddwJHnV7gPheBlk
MDapowb+Is77+a9Y2VDsOXEvNpqTY0giiSrckG05IZnrhJ24JnSCwyNd99lm7XKdEGGrjBCMqIyI
Fqox8Ahkv3KWAJPYK1eOCc5d/KwZHlnlFJq7ZYy9u3fEnxQCjOEmeXLkLangKA==
-----END RSA PRIVATE KEY-----', 'password');
if ($pkey === false) exit('FAILURE');
openssl_pkey_export($pkey, $out_key_file);
echo $out_key_file;
?>
Only problem: the code dies prematurely, echo'ing out FAILURE. ie. openssl_pkey_get_private() isn't loading the key. openssl_error_string says "error:0906D066:PEM routines:PEM_read_bio:bad end line".
Any ideas?
Source: (StackOverflow)
I have a web-service in php that generates a keypair to encrypt a message, and one application in java that retrives the privatekey and decrypt the message.
For php I'm using http://phpseclib.sourceforge.net/ and have this two files:
keypair.php
<?php
set_time_limit(0);
if( file_exists('private.key') )
{
echo file_get_contents('private.key');
}
else
{
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->createKey();
$res = $rsa->createKey();
$privateKey = $res['privatekey'];
$publicKey = $res['publickey'];
file_put_contents('public.key', $publicKey);
file_put_contents('private.key', $privateKey);
}
?>
encrypt.php
<?php
include('Crypt/RSA.php');
//header("Content-type: text/plain");
set_time_limit(0);
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->loadKey(file_get_contents('public.key')); // public key
$plaintext = 'Hello World!';
$ciphertext = $rsa->encrypt($plaintext);
echo base64_encode($ciphertext);
?>
and in java I have this code:
package com.example.app;
import java.io.DataInputStream;
import java.net.URL;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args)
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
try {
BASE64Decoder decoder = new BASE64Decoder();
String b64PrivateKey = getContents("http://localhost/api/keypair.php").trim();
String b64EncryptedStr = getContents("http://localhost/api/encrypt.php").trim();
System.out.println("PrivateKey (b64): " + b64PrivateKey);
System.out.println(" Encrypted (b64): " + b64EncryptedStr);
SecretKeySpec privateKey = new SecretKeySpec( decoder.decodeBuffer(b64PrivateKey) , "AES");
Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainText = decoder.decodeBuffer(b64EncryptedStr);
System.out.println(" Message: " + plainText);
}
catch( Exception e )
{
System.out.println(" Error: " + e.getMessage());
}
}
public static String getContents(String url)
{
try {
String result = "";
String line;
URL u = new URL(url);
DataInputStream theHTML = new DataInputStream(u.openStream());
while ((line = theHTML.readLine()) != null)
result = result + "\n" + line;
return result;
}
catch(Exception e){}
return "";
}
}
My questions are:
- Why I'm having a exception saying "not an RSA key!"?
- How can I improve this code? I have used base64 to avoid encoding and comunication errors between Java and PHP.
- This concept is correct? I mean, I'm using it correctly?
Source: (StackOverflow)
I'm having trouble using PHP to SFTP upload files to a remote server. When I use cURL, I'm getting the error described here:
http://stackoverflow.com/questions/1766822/sftp-from-php-undefined-constant-curloptprotocols-and-curlprotosftp
I also tried phpseclib as suggested in:
http://stackoverflow.com/questions/717854/sftp-from-within-php
But when i try phpseclib, i get these errors:
Warning: require_once(Math/BigInteger.php) [function.require-once]: failed to open stream: No such file or directory in /home/john/public_html/test/Net/SSH2.php on line 53
Fatal error: require_once() [function.require]: Failed opening required 'Math/BigInteger.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/john/public_html/test/Net/SSH2.php on line 53
I then tried using system commands in php like so, but nothing happened:
<?php
echo system('sftp user@ftp.domain.com');
echo system('password');
echo system('put file.csv');
?>
I also tried
<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>
but my php server says ss2_connect is not defined.
I tried to do the following from terminal
scp file.csv user@ftp.remote.com
password
But the server does not allow scp command. I do not have shell access to create ssh keys.
All i can do right now is sftp from terminal and manually upload. But I really want to automate this so a PHP website can do all this.
There aren't many tutorials on how to SFTP upload from PHP. Is it because it's a bad thing to do? If so, what should I be doing? The server I want to upload to only allows sftp connections.
Source: (StackOverflow)
So i need to execute one command but it will only run if i su to root (or sudo ) but I can't seem to figure out how to send the command to su to root
(i can log in and execute other commands with loginuser fine)
http://phpseclib.sourceforge.net/ssh/examples.html
My code as follows
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('255.255.255.255',22);
if (!$ssh->login('loginuser', 'fakepassword')) {
exit('Login Failed');
}
echo $ssh->read('[prompt]');
echo $ssh->write("su\n");
echo $ssh->read('Password:');
echo $ssh->write("rootfakepassword");
echo $ssh->read('[prompt]');
echo $ssh->exec('cc get_wireless_status');
?>
I've also tried using the exec command to do roughly the same thing with no luck
any suggestions?
current revision of the code (doesnt work)
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('255.255.99.74',22);
if (!$ssh->login('loginuser', 'password')) {
exit('Login Failed');
}
echo $ssh->read('loginuser@intranet:/home/login >');
$ssh->write("su\n");
echo $ssh->read('Password:');
$ssh->write("rootpassword\n");
echo $ssh->read('intranet:/home/login #');
$ssh->write("cc get_wireless_status\n");
echo $ssh->read('[prompt]');
?>
putty text of log in
login as: loginuser
loginuser@255.255.99.74's password:
Last login: Thu Feb 14 13:57:16 2013 from infong1045.lxa.perfora.net
Sophos UTM
(C) Copyrights by Astaro and by others 2000-2012.
For more copyright information look at /doc/astaro-license.txt
or http://www.astaro.com/doc/astaro-license.txt
NOTE: Any modifications done by root will void your support.
Please use WebAdmin for any configuration changes.
loginuser@intranet:/home/login > su
Password:
intranet:/home/login #
response from code on newest version
Last login: Thu Feb 14 14:00:00 2013 from 10.10.10.194 Sophos UTM (C) Copyrights by Astaro and by others 2000-2012. For more copyright information look at /doc/astaro-license.txt or http://www.astaro.com/doc/astaro-license.txt NOTE: Any modifications done by root will void your support. Please use WebAdmin for any configuration changes. loginuser@intranet:/home/login > Last login: Tue Feb 19 11:09:18 2013 from infong1045.lxa.perfora.net Sophos UTM (C) Copyrights by Astaro and by others 2000-2012. For more copyright information look at /doc/astaro-license.txt or http://www.astaro.com/doc/astaro-license.txt NOTE: Any modifications done by root will void your support. Please use WebAdmin for any configuration changes. loginuser@intranet:/home/login > su Password: intranet:/home/login # Last login: Tue Feb 19 11:09:23 2013 from infong1045.lxa.perfora.net Sophos UTM (C) Copyrights by Astaro and by others 2000-2012. For more copyright information look at /doc/astaro-license.txt or http://www.astaro.com/doc/astaro-license.txt NOTE: Any modifications done by root will void your support. Please use WebAdmin for any configuration changes. loginuser@intranet:/home/login > cc get_wireless_status -bash: /usr/local/bin/confd-client.plx: Permission denied loginuser@intranet:/home/login >
Source: (StackOverflow)
I try to sign a key with phpseclib and when I decode the result with openssl I get the following:
140513785948000:error:0D07209B:asn1 encoding routines:ASN1_get_object:too long:asn1_lib.c:142:
140513785948000:error:0D068066:asn1 encoding routines:ASN1_CHECK_TLEN:bad object header:tasn_dec.c:1306:
140513785948000:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:381:Type=X509
140513785948000:error:0906700D:PEM routines:PEM_ASN1_read_bio:ASN1 lib:pem_oth.c:83:
Why is it doing this?
(This bug took me a while to figure out, so I figured I'd help the next person with this issue out by posting it here)
Source: (StackOverflow)
My post from yesterday: phpseclib sftp port number
Ok, so yesterday I started learning about SSH / SFTP with php. I searched a bunch of forum posts and surmised that i needed to download the phpseclib.
Being relatively new to php thus starting on php5 i was not aware of previous php4's non-use of the __constructor, hence the above question/post.
The responses were conflicting, and a little off topic to the original Q however has delivered me to a question that I feel needs answering before i continue:
Which is better to use, ssh2 pecl extension OR phpseclib?
This question: phpseclib vs libssh2 is the same but I feel a little outdated now as asked on Nov 5 '10 at 17:37
Source: (StackOverflow)
I'm looking to allow a user to download a file directly from an sftp server, but in the browser.
I've found methods to read the file and echo the string (connections using ssh2.sftp or phpseclib) but I need to download, rather than read.
Also, I've seen solutions that suggest downloading from the sftp server to the web server, then use readfile() from the web server to the user's local disk. But this means two file transfers, and if the file is large I imagine this would be slow.
Can you download directly from sftp to the user's disk?
Cheers for any responses!
Source: (StackOverflow)
I'm using phpseclib - SFTP class and am trying to upload a file like so -
$sftp = new Net_SFTP('mydomain.com');
if (!$sftp->login('user', 'password')) {
exit('Login Failed');
}
$sftp->put('/some-dir/',$fileTempName);
The file however isn't being uploaded inside some-dir
but is uploaded one directory before (to the starting directory, lets say it's root). This is driving me crazy, I think I've tried all combinations of some-dir/
or /some-dir
or /some-dir/
, but the file won't upload there.
Source: (StackOverflow)
I'm trying to encrypt data in android side and decrypt it in php side
i'm using phpseclib in php to generate public/private keys
after i generate keys this public key i got in PHP side :
-----BEGIN RSA PUBLIC KEY-----".
"MIGJAoGBAKks62Itns2uU/dVZJ4kCkMinHgyeh/rdMD53a4Zu2a76OIJvdSZ8q4c".
"YTWvPj0giefVtMc7tV4c6AAw04jyIfmCTvcQUlHI+sspHxXDlQTagNoxCuA29b5L".
"9MKO6Ok0LwF9rGgTywC1heNEulZz9ISn9FQDazJT+Bd9cnNOrJRdAgMBAAE=".
"-----END RSA PUBLIC KEY-----
and then i encoded it to base64 and got this base64 encoded key
LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tTUlHSkFvR0JBS2tzNjJJdG5zMnVVL2RWWko0a0NrTWluSGd5ZWgvcmRNRDUzYTRadTJhNzZPSUp2ZFNaOHE0Y1lUV3ZQajBnaWVmVnRNYzd0VjRjNkFBdzA0anlJZm1DVHZjUVVsSEkrc3NwSHhYRGxRVGFnTm94Q3VBMjliNUw5TUtPNk9rMEx3RjlyR2dUeXdDMWhlTkV1bFp6OUlTbjlGUURhekpUK0JkOWNuTk9ySlJkQWdNQkFBRT0tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0t
i copied it to android side to encrypt data using it but i got InvalidKeySpecException
Android Side Code:
public static byte[] encrypt(String text) {
byte[] encodedPublicKey= Base64.decode("LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tTUlHSkFvR0JBS2tzNjJJdG5zMnVVL2RWWko0a0NrTWluSGd5ZWgvcmRNRDUzYTRadTJhNzZPSUp2ZFNaOHE0Y1lUV3ZQajBnaWVmVnRNYzd0VjRjNkFBdzA0anlJZm1DVHZjUVVsSEkrc3NwSHhYRGxRVGFnTm94Q3VBMjliNUw5TUtPNk9rMEx3RjlyR2dUeXdDMWhlTkV1bFp6OUlTbjlGUURhekpUK0JkOWNuTk9ySlJkQWdNQkFBRT0tLS0tLUVORCBSU0EgUFVCTElDIEtFWS0tLS0t", Base64.DEFAULT);
PublicKey publicKey=null;
KeyFactory keyFactory = null;
try {
keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
publicKey = keyFactory.generatePublic(publicKeySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (InvalidKeySpecException e) {
e.printStackTrace();
}
byte[] cipherText = null;
try {
// get an RSA cipher object and print the provider
final Cipher cipher = Cipher.getInstance("RSA");
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
Source: (StackOverflow)