コード例 #1
0
 /**
  * @param string $pem_format
  * @param string $password
  * @throws RSABadPEMFormat
  */
 public function __construct($pem_format, $password = null)
 {
     $this->pem_format = $pem_format;
     $this->rsa_imp = new \Crypt_RSA();
     if (!empty($password)) {
         $this->rsa_imp->setPassword($password);
     }
     $res = $this->rsa_imp->loadKey($this->pem_format, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
     if (!$res) {
         throw new RSABadPEMFormat(sprintf('pem %s', $pem_format));
     }
     $this->n = $this->rsa_imp->modulus;
 }
コード例 #2
0
ファイル: Ssh2.class.php プロジェクト: nao-pon/xupdate
 /**
  * app_login
  *
  * @param   string  $server
  *
  * @return	bool
  **/
 public function app_login($server)
 {
     $ftp_id = $this->mod_config['FTP_UserName'];
     $ftp_pass = $this->mod_config['FTP_password'];
     // LOGIN
     //		@define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);
     @define('NET_SFTP_LOGGING', NET_SFTP_LOG_SIMPLE);
     $this->Verbose = TRUE;
     //TRUE or FALSE
     $this->LocalEcho = FALSE;
     //$this->Passive(TRUE);
     $key = new Crypt_RSA();
     $key->setPassword($ftp_pass);
     $key->loadKey($this->mod_config['SSH_key']);
     $port = (int) $this->mod_config['SSH_port'];
     //phpseclib
     $this->sftp = new Net_SFTP($server, $port);
     if (!$this->sftp->login($ftp_id, $key)) {
         $this->mes .= "SSH Login Failed<br />\n";
         $this->mes .= $this->getSSH2Errors();
         return false;
     }
     $this->mes .= "PWD:" . $this->sftp->pwd() . "<br />\n";
     $this->mes .= $this->getSSH2Log();
     return true;
 }
コード例 #3
0
ファイル: Sftp.php プロジェクト: rudraks/application
 public function connect($test = false)
 {
     if (!$this->connection or $test) {
         $server = $this->server;
         require_once 'Crypt/RSA.php';
         require_once 'Net/SFTP.php';
         $this->connection = new \Net_SFTP($server['host'], $server['port'], 10);
         $logged_in = false;
         if (isset($server['sftp_key'])) {
             $key = new \Crypt_RSA();
             if (isset($server['pass']) && !empty($server['pass'])) {
                 $key->setPassword($server['pass']);
             }
             $key->loadKey(file_get_contents($server['sftp_key']));
             $logged_in = $this->connection->login($server['user'], $key);
             if (!$logged_in) {
                 Helpers::error("Could not login to {$this->host}. It may be because the key requires a passphrase, which you need to specify it as the 'pass' attribute.");
             }
         } else {
             $logged_in = $this->connection->login($server['user'], $server['pass']);
             if (!$logged_in) {
                 Helpers::error("Could not login to {$this->host}");
             }
         }
         if (!$this->connection->chdir($server['path'])) {
             Helpers::error("Could not change the directory to {$server['path']} on {$this->host}");
         }
         Helpers::logmessage("Connected to: {$this->host}");
         $this->current_commit = $this->get_file('REVISION', true);
     }
     if ($test) {
         $this->disconnect();
     }
 }
コード例 #4
0
 function connect()
 {
     $this->link = new Net_SFTP($this->options['hostname'], $this->options['port']);
     if (!$this->link) {
         $this->errors->add('connect', sprintf(__('Failed to connect to SSH2 Server %1$s:%2$s'), $this->options['hostname'], $this->options['port']));
         return false;
     }
     if (!$this->keys) {
         if (!$this->link->login($this->options['username'], $this->options['password'])) {
             $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username']));
             return false;
         }
     } else {
         $rsa = new Crypt_RSA();
         if ($this->password) {
             $rsa->setPassword($this->options['password']);
         }
         $rsa->loadKey($this->options['private_key']);
         if (!$this->link->login($this->options['username'], $rsa)) {
             $this->errors->add('auth', sprintf(__('Private key incorrect for %s'), $this->options['username']));
             return false;
         }
     }
     return true;
 }
コード例 #5
0
 function connect()
 {
     $this->link = new Net_SFTP($this->options['hostname'], $this->options['port']);
     if (!$this->keys) {
         if (!$this->link->login($this->options['username'], $this->options['password'])) {
             if ($this->handle_connect_error()) {
                 return false;
             }
             $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username']));
             return false;
         }
     } else {
         $rsa = new Crypt_RSA();
         if ($this->password) {
             $rsa->setPassword($this->options['password']);
         }
         $rsa->loadKey($this->options['private_key']);
         if (!$this->link->login($this->options['username'], $rsa)) {
             if ($this->handle_connect_error()) {
                 return false;
             }
             $this->errors->add('auth', sprintf(__('Private key incorrect for %s'), $this->options['username']));
             $this->errors->add('auth', __('Make sure that the key you are using is an RSA key and not a DSA key'));
             return false;
         }
     }
     return true;
 }
コード例 #6
0
ファイル: Release.class.php プロジェクト: Warkot/Bolt
 public function deploy()
 {
     $releaseId = $this->dataBase->startRelease();
     $ssh = new Net_SSH2(SSH_SERVER);
     $key = new Crypt_RSA();
     $key->setPassword(SSH_PASSWORD);
     $key->loadKey(file_get_contents(PATH_TO_PRIVATE_KEY));
     if (!$ssh->login(SSH_LOGIN, $key)) {
         $this->dataBase->logStep($releaseId, 'ssh ' . SSH_SERVER, ['error' => 'Login failed'], 1);
         exit('Login Failed');
     }
     $ssh->enableQuietMode();
     $command = $this->bash->dtLock('sandbox-mercury', 'mercury');
     $output['success'] = $ssh->exec($command);
     $output['error'] = $ssh->getStdError();
     $this->dataBase->logStep($releaseId, $command, $output, $ssh->getExitStatus());
     $command = $this->bash->dtPrep('sandbox-mercury', 'mercury', ["mercury" => "dev"]);
     $output['success'] = $ssh->exec($command);
     $output['error'] = $ssh->getStdError();
     $this->dataBase->logStep($releaseId, $command, $output, $ssh->getExitStatus());
     $command = $this->bash->dtPush('sandbox-mercury', 'mercury');
     $output['success'] = $ssh->exec($command);
     $output['error'] = $ssh->getStdError();
     $this->dataBase->logStep($releaseId, $command, $output, $ssh->getExitStatus());
 }
コード例 #7
0
ファイル: Rsa.php プロジェクト: sayiho/Jumper
 /**
  * @return RsaKey the rsa key
  */
 public function getAuthentication()
 {
     $key = new RsaKey();
     $key->loadKey(file_get_contents($this->key));
     if (!is_null($this->password)) {
         $key->setPassword($this->password);
     }
     return $key;
 }
コード例 #8
0
ファイル: BrSFTP.php プロジェクト: jagermesh/bright
 function connectWithKey($hostName, $userName, $keyFileName, $port = 22, $keyFilePassword = '')
 {
     $key = new Crypt_RSA();
     if ($keyFilePassword) {
         $key->setPassword($keyFilePassword);
     }
     $key->loadKey(file_get_contents($keyFileName));
     $this->connect($hostName, $userName, $key, $port);
 }
コード例 #9
0
ファイル: sftp_key.php プロジェクト: samj1912/repo
 /**
  * Returns the private key to be used for authentication to the remote server.
  *
  * @return \Crypt_RSA instance or null in case of a failure to load the key.
  */
 private function getPrivateKey()
 {
     $key = new \Crypt_RSA();
     $key->setPassword(\OC::$server->getConfig()->getSystemValue('secret', ''));
     if (!$key->loadKey($this->privateKey)) {
         // Should this exception rather than return null?
         return null;
     }
     return $key;
 }
コード例 #10
0
 private function generateSshKeys()
 {
     $rsa = new \Crypt_RSA();
     $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_OPENSSH);
     $rsa->setPassword(\OC::$server->getConfig()->getSystemValue('secret', ''));
     $key = $rsa->createKey();
     // Replace the placeholder label with a more meaningful one
     $key['publicKey'] = str_replace('phpseclib-generated-key', gethostname(), $key['publickey']);
     return $key;
 }
コード例 #11
0
ファイル: phpseclib.php プロジェクト: jamesduan/etbackuptool
 function ssh2_auth_pubkey_file($session, $username, $pubkeyfile, $privkeyfile, $passphrase = NULL)
 {
     $privkey = new Crypt_RSA();
     if (isset($passphrase)) {
         $privkey->setPassword($passphrase);
     }
     $privkey->loadKey(file_get_contents($privkeyfile));
     if ($privkey === false) {
         return false;
     }
     return $session->login($username, $privkey);
 }
コード例 #12
0
 /**
  * Generates random key with optonal passphrase and stores it
  * in the model
  */
 function generateKey($pack = null)
 {
     $rsa = new Crypt_RSA();
     if ($pack) {
         $rsa->setPassword($pack);
     }
     $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_OPENSSH);
     $key = $rsa->createKey();
     $this['kind'] = 'key';
     $this['host'] = '*';
     $this['data'] = $key['privatekey'];
     $this['is_secure'] = (bool) $pack;
     $this['notes'] = $key['publickey'];
 }
コード例 #13
0
 public function connect()
 {
     // we have to mangle the include path a little to find our plugins
     $oldIncludePath = get_include_path();
     set_include_path($oldIncludePath . ':' . TL_ROOT . '/plugins/phpseclib/:' . TL_ROOT . '/plugins/phpseclib/Net:' . TL_ROOT . '/plugins/phpseclib/Crypt');
     include 'SFTP.php';
     if ($GLOBALS['TL_CONFIG']['sftpKeyFile']) {
         include 'RSA.php';
     }
     set_include_path($oldIncludePath);
     $this->ftpHost = $GLOBALS['TL_CONFIG']['ftpHost'];
     $this->ftpPort = $GLOBALS['TL_CONFIG']['ftpPort'];
     $this->ftpUser = $GLOBALS['TL_CONFIG']['ftpUser'];
     if ($GLOBALS['TL_CONFIG']['sftpKeyFile']) {
         $key = new Crypt_RSA();
         if ($GLOBALS['TL_CONFIG']['sftpKeyPass']) {
             $key->setPassword($GLOBALS['TL_CONFIG']['sftpKeyPass']);
         }
         $key->loadKey(file_get_contents($GLOBALS['TL_CONFIG']['sftpKeyFile']));
         $this->ftpPass = $key;
     } else {
         $this->ftpPass = $GLOBALS['TL_CONFIG']['ftpPass'];
     }
     $this->ftpPath = $GLOBALS['TL_CONFIG']['ftpPath'];
     // Connect to FTP server
     if (!is_numeric($this->ftpPort) || $this->ftpPort == 0) {
         $this->ftpPort = 22;
     }
     if ($GLOBALS['TL_CONFIG']['debugSmhExtended']) {
         define('NET_SSH2_LOGGING', true);
         define('NET_SFTP_LOGGING', true);
     }
     if (($resConnection = new Net_SFTP($this->ftpHost, $this->ftpPort, 5)) != false) {
         // Login
         if (!$resConnection->login($this->ftpUser, $this->ftpPass)) {
             throw new Exception('Could not login to sftp: ' . $resConnection->getLastError() . (defined('NET_SSH2_LOGGING') ? implode("\n", $resConnection->message_number_log) : ''));
         }
         // security, clean user id and password as we won't need them anymore.
         $this->ftpUser = NULL;
         $this->ftpPass = NULL;
         // change to root directory to ensure we can really work.
         $resConnection->chdir($this->ftpPath);
         $this->resConnection = $resConnection;
         return $resConnection;
     } else {
         throw new Exception('Could not connect to sftp: ' . $resConnection->getLastError());
     }
 }
コード例 #14
0
 private final function InitSSH()
 {
     if ($this->ssh == null) {
         if (!$this->IsIPAddress($_SESSION['host'])) {
             //return print_r($_SESSION, 1);
             return 'InitSSH: Must select a Server to manage';
         }
         $this->ssh = new Net_SFTP($_SESSION['host']);
         $user = $pass = $privkey = $privpass = '';
         list($user, $pass, $privpass) = explode(' ', $this->Decrypt($_SESSION['cred']));
         //return "user:$user, pass:$pass";
         if (!$_SESSION['priv']) {
             if (!$this->ssh->login($user, $pass)) {
                 return 'InitSSH: Keyboard-Interactive Login Failed';
             }
         } else {
             $privkey = $this->Decrypt($_SESSION['priv']);
             if ($this->GetPrivateHostKeyType($privkey) != 'RSA') {
                 return 'InitSSH: Private Host Key Login Failed, Key not RSA';
             } else {
                 $key = new Crypt_RSA();
                 if ($privpass) {
                     $key->setPassword($privpass);
                 }
                 $key->loadKey($privkey);
                 if (!$this->ssh->login($user, $key)) {
                     return 'InitSSH: Private Host Key Login Failed';
                 }
             }
         }
     } else {
         $pubkey = $this->ssh->getServerPublicHostKey();
         if ($_SESSION['pubhost'] and $pubkey !== $this->Decrypt($_SESSION['pubhost'])) {
             return 'InitSSH: Possible Man-in-the-Middle Attack!';
         } else {
             if (!$_SESSION['pubhost']) {
                 $_SESSION['pubhost'] = $this->Encrypt($pubkey);
             }
         }
     }
     // http://phpseclib.sourceforge.net/ssh/examples.html#interactive
     //$_SESSION['uprompt'] = $_SESSION['rprompt'] = '';
     $this->GetSSHPrompts($pass, false);
     return true;
 }
コード例 #15
0
function ssh_connect($host)
{
    dbg_log("Connecting over SSH to {$host}");
    #define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);
    $ssh = new Net_SSH2($host);
    $key = new Crypt_RSA();
    $key->setPassword(get_config()->host_ssh_private_key_password);
    $keyPath = get_config()->host_ssh_private_key;
    $keyString = file_get_contents($keyPath);
    $userString = get_config()->host_ssh_username;
    if (!$key->loadKey($keyString)) {
        dbg_log(var_dump($ssh->getErrors(), true));
        exit("cannot import key {$keyPath}");
    }
    if (!$ssh->login($userString, $key)) {
        dbg_log($ssh->getLastError());
        exit('Login Failed');
    }
    return $ssh;
}
コード例 #16
0
 public function connect()
 {
     if ($this->connected) {
         return true;
     }
     AppKitLogger::verbose("Connecting to ssh instance %s:%s", $this->host, $this->port);
     $success = false;
     $this->resource = new Net_SSH2($this->host, $this->port);
     switch ($this->authType) {
         case 'none':
             AppKitLogger::verbose("No-auth login with %s", $this->username);
             $success = $this->resource->login($this->username);
             break;
         case 'password':
             AppKitLogger::verbose("Password login with %s", $this->username);
             $success = $this->resource->login($this->username, $this->password);
             break;
         case 'key':
             AppKitLogger::verbose("Pub-Key login with ssh key at %s", $this->privKeyLocation);
             if (!is_readable($this->privKeyLocation)) {
                 throw new ApiAuthorisationFailedException("SSH private key not found/readable at the specified location");
             }
             $key = new Crypt_RSA();
             if ($this->password) {
                 $key->setPassword($this->password);
             }
             $key->loadKey(file_get_contents($this->privKeyLocation));
             $success = $this->resource->login($this->username, $key);
             break;
         default:
             throw new ApiInvalidAuthTypeException("Unknown authtype " . $this->authType);
     }
     AppKitLogger::verbose("Login success: %s", $success);
     if (!$success || !is_object($this->resource)) {
         throw new ApiAuthorisationFailedException("SSH auth for user " . $this->username . " failed (using authtype " . $this->authType . ') :' . print_r($this->resource->getErrors(), true));
     }
     $this->connected = true;
 }
コード例 #17
0
ファイル: Host.php プロジェクト: romaninsh/dokku_alt
 function getPrivateKey()
 {
     $key = new \Crypt_RSA();
     if ($this['private_key']) {
         $key->loadKey($this['private_key']);
         return $key;
     }
     // else look in keychain
     $k = $this->add('Model_Keychain');
     $k->tryLoadBy('host', $this['addr']);
     if (!$k->loaded()) {
         $k->tryLoadBy('host', '*');
     }
     if (!$k->loaded()) {
         throw $this->exception('Could not find matching private key in Keychain');
     }
     $pack = $this->app->getPackingKey();
     if ($pack) {
         $key->setPassword($pack);
     }
     $key->loadKey($k['data']);
     return $key;
 }
コード例 #18
0
 /**
  * Return if PIN for card is valid
  *
  * @param  string $card
  * @param  int $pin
  * @return ITS SECRET
  */
 public function local_check_pin($card, $pin, $key)
 {
     global $DB, $CFG;
     try {
         if (empty($pin) || strlen($pin) < 4) {
             throw new Exception('PIN is invalid.');
         }
         $rsa = new Crypt_RSA();
         $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
         $rsa->loadKey(get_config('quiz_nitroreportpdf', 'privkey'));
         $ckey = $rsa->decrypt(base64_decode(rawurldecode($key)));
         $token = (new Parser())->parse((string) $ckey);
         if (!$token) {
             throw new Exception('The data is invalid or time expired.');
         }
         if ($token->getClaim('iss') != "NITROCARD" || $token->getClaim('aud') != "NITROCARD" || strtotime("now") >= $token->getClaim('exp') || $token->getClaim('login') != get_config('quiz_nitroreportpdf', 'apilogin') || $token->getClaim('pass') != get_config('quiz_nitroreportpdf', 'apipass') || $token->getClaim('md5') != md5(get_config('quiz_nitroreportpdf', 'pubkey'))) {
             throw new Exception('The data is invalid or time expired.');
         }
         if (empty(strip_tags($card)) || substr(strip_tags($card), 0, 9) != "NITROCARD" || strlen(strip_tags($card)) < 98 || strlen(strip_tags($card)) > 108) {
             throw new Exception('NitroCard is invalid');
         }
         $card_e = explode('.', strip_tags($card));
         if (count($card_e) != 5) {
             throw new Exception('NitroCard is invalid');
         }
         $reqdb = $DB->count_records_sql('SELECT count(fullcardid) FROM {nitrocard_cards} WHERE fullcardid="' . strip_tags($card) . '"');
         if ($reqdb == 1) {
             //local
             $reqdb2 = $DB->count_records_sql('SELECT count(fullcardid) FROM {nitrocard_cards} WHERE fullcardid="' . strip_tags($card) . '" AND pin="' . strip_tags($pin) . '"');
             if ($reqdb2 == 1) {
                 $token_allow = (new Builder())->setIssuer('NITROCARD')->setAudience('NITROCARD')->setId(substr(md5(strtotime("now")), 0, 10), true)->setIssuedAt(time())->setExpiration(time() + 60)->set('NITROCARDID', $card)->getToken();
                 $rsa = new Crypt_RSA();
                 $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
                 $rsa->loadKey(get_config('quiz_nitroreportpdf', 'privkey'));
                 $enc = base64_encode($rsa->encrypt($token_allow));
                 $loginurl = $CFG->wwwroot . '/login/index.php';
                 if (!empty($CFG->alternateloginurl)) {
                     $loginurl = $CFG->alternateloginurl;
                 }
                 $loginurl .= '?provider=nitrocard&auth=' . rawurlencode('' . $enc);
                 return $loginurl;
             } else {
                 $DB->execute('UPDATE {nitrocard_cards} SET count_to_blocked=count_to_blocked+1 WHERE fullcardid="' . strip_tags($card) . '"');
                 $reqdb3 = $DB->get_record_sql('SELECT count_to_blocked FROM {nitrocard_cards} WHERE fullcardid="' . strip_tags($card) . '"');
                 if ($reqdb3->count_to_blocked >= 3) {
                     $DB->execute('UPDATE {nitrocard_cards} SET blocked="1" WHERE fullcardid="' . strip_tags($card) . '"');
                     throw new Exception('NitroCard is blocked.');
                 }
                 throw new Exception('PIN is incorrect.');
             }
         } else {
             //remote
         }
     } catch (Exception $e) {
         setError($e->getMessage());
     }
     return false;
 }
コード例 #19
0
ファイル: DB_Proxy.php プロジェクト: haya-sann/INTER-Mediator
 function decrypting($paramCryptResponse)
 {
     $generatedPrivateKey = '';
     $passPhrase = '';
     $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR;
     $currentDirParam = $currentDir . 'params.php';
     $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php';
     if (file_exists($parentDirParam)) {
         include $parentDirParam;
     } else {
         if (file_exists($currentDirParam)) {
             include $currentDirParam;
         }
     }
     $rsa = new Crypt_RSA();
     $rsa->setPassword($passPhrase);
     $rsa->loadKey($generatedPrivateKey);
     $rsa->setPassword();
     $privatekey = $rsa->getPrivateKey();
     $priv = $rsa->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
     require_once 'lib/bi2php/biRSA.php';
     $keyDecrypt = new biRSAKeyPair('0', $priv['privateExponent']->toHex(), $priv['modulus']->toHex());
     $decrypted = $keyDecrypt->biDecryptedString($paramCryptResponse);
     if ($decrypted === false) {
         return array(false, false);
     }
     $nlPos = strpos($decrypted, "\n");
     $nlPos = $nlPos === false ? strlen($decrypted) : $nlPos;
     $password = $keyDecrypt->biDecryptedString(substr($decrypted, 0, $nlPos));
     $password = strlen($password) == 0 ? "f32b309d4759446fc81de858322ed391a0c167a0" : $password;
     $challenge = substr($decrypted, $nlPos + 1);
     return array($password, $challenge);
 }
コード例 #20
0
 public function generateInitialJSCode($datasource, $options, $dbspecification, $debug)
 {
     $q = '"';
     $generatedPrivateKey = null;
     $passPhrase = null;
     /*
      * Decide the params.php file and load it.
      */
     $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR;
     $currentDirParam = $currentDir . 'params.php';
     $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php';
     if (file_exists($parentDirParam)) {
         include $parentDirParam;
     } else {
         if (file_exists($currentDirParam)) {
             include $currentDirParam;
         }
     }
     /*
      * Read the JS programs regarding by the developing or deployed.
      */
     if (file_exists($currentDir . 'INTER-Mediator-Lib.js')) {
         echo $this->combineScripts($currentDir);
     } else {
         readfile($currentDir . 'INTER-Mediator.js');
     }
     /*
      * Generate the link to the definition file editor
      */
     $relativeToDefFile = '';
     $editorPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'INTER-Mediator-Support';
     $defFilePath = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['SCRIPT_NAME'];
     while (strpos($defFilePath, $editorPath) !== 0 && strlen($editorPath) > 1) {
         $editorPath = dirname($editorPath);
         $relativeToDefFile .= '..' . DIRECTORY_SEPARATOR;
     }
     $relativeToDefFile .= substr($defFilePath, strlen($editorPath) + 1);
     $editorPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'INTER-Mediator-Support' . DIRECTORY_SEPARATOR . 'defedit.html';
     if (file_exists($editorPath)) {
         $relativeToEditor = substr($editorPath, strlen($_SERVER['DOCUMENT_ROOT']));
         $this->generateAssignJS("INTERMediatorOnPage.getEditorPath", "function(){return {$q}{$relativeToEditor}?target={$relativeToDefFile}{$q};}");
     } else {
         $this->generateAssignJS("INTERMediatorOnPage.getEditorPath", "function(){return '';}");
     }
     /*
      * from db-class, determine the default key field string
      */
     $defaultKey = null;
     $dbClassName = 'DB_' . (isset($dbspecification['db-class']) ? $dbspecification['db-class'] : (isset($dbClass) ? $dbClass : ''));
     require_once "{$dbClassName}.php";
     if ((double) phpversion() < 5.3) {
         $dbInstance = new $dbClassName();
         if ($dbInstance != null) {
             $defaultKey = $dbInstance->getDefaultKey();
         }
     } else {
         $defaultKey = call_user_func(array($dbClassName, 'defaultKey'));
     }
     if ($defaultKey !== null) {
         $items = array();
         foreach ($datasource as $context) {
             if (!array_key_exists('key', $context)) {
                 $context['key'] = $defaultKey;
             }
             $items[] = $context;
         }
         $datasource = $items;
     }
     /*
      * Determine the uri of myself
      */
     if (isset($callURL)) {
         $pathToMySelf = $callURL;
     } else {
         if (isset($scriptPathPrefix) || isset($scriptPathSuffix)) {
             $pathToMySelf = (isset($scriptPathPrefix) ? $scriptPathPrefix : '') . $_SERVER['SCRIPT_NAME'] . (isset($scriptPathSufix) ? $scriptPathSuffix : '');
         } else {
             $pathToMySelf = $_SERVER['SCRIPT_NAME'];
         }
     }
     $this->generateAssignJS("INTERMediatorOnPage.getEntryPath", "function(){return {$q}{$pathToMySelf}{$q};}");
     $this->generateAssignJS("INTERMediatorOnPage.getDataSources", "function(){return ", arrayToJSExcluding($datasource, '', array('password')), ";}");
     $this->generateAssignJS("INTERMediatorOnPage.getOptionsAliases", "function(){return ", arrayToJS(isset($options['aliases']) ? $options['aliases'] : array(), ''), ";}");
     $this->generateAssignJS("INTERMediatorOnPage.getOptionsTransaction", "function(){return ", arrayToJS(isset($options['transaction']) ? $options['transaction'] : '', ''), ";}");
     $this->generateAssignJS("INTERMediatorOnPage.getDBSpecification", "function(){return ", arrayToJSExcluding($dbspecification, '', array('dsn', 'option', 'database', 'user', 'password', 'server', 'port', 'protocol', 'datatype')), ";}");
     $isEmailAsUsernae = isset($options['authentication']) && isset($options['authentication']['email-as-username']) && $options['authentication']['email-as-username'] === true;
     $this->generateAssignJS("INTERMediatorOnPage.isEmailAsUsername", $isEmailAsUsernae ? "true" : "false");
     $messageClass = null;
     if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
         $clientLangArray = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
         foreach ($clientLangArray as $oneLanguage) {
             $langCountry = explode(';', $oneLanguage);
             if (strlen($langCountry[0]) > 0) {
                 $clientLang = explode('-', $langCountry[0]);
                 $messageClass = "MessageStrings_{$clientLang['0']}";
                 if (file_exists("{$currentDir}{$messageClass}.php")) {
                     $messageClass = new $messageClass();
                     break;
                 }
             }
             $messageClass = null;
         }
     }
     if ($messageClass == null) {
         require_once 'MessageStrings.php';
         $messageClass = new MessageStrings();
     }
     $this->generateAssignJS("INTERMediatorOnPage.getMessages", "function(){return ", arrayToJS($messageClass->getMessages(), ''), ";}");
     if (isset($options['browser-compatibility'])) {
         $browserCompatibility = $options['browser-compatibility'];
     }
     $this->generateAssignJS("INTERMediatorOnPage.browserCompatibility", "function(){return ", arrayToJS($browserCompatibility, ''), ";}");
     $clientIdSeed = time() + $_SERVER['REMOTE_ADDR'] + mt_rand();
     $randomSecret = mt_rand();
     $clientId = hash_hmac('sha256', $clientIdSeed, $randomSecret);
     $this->generateAssignJS("INTERMediatorOnPage.clientNotificationIdentifier", "function(){return ", arrayToJS($clientId, ''), ";}");
     $pusherParams = null;
     if (isset($pusherParameters)) {
         $pusherParams = $pusherParameters;
     } else {
         if (isset($options['pusher'])) {
             $pusherParams = $options['pusher'];
         }
     }
     if (!is_null($pusherParams)) {
         $appKey = isset($pusherParams['key']) ? $pusherParams['key'] : "_im_key_isnt_supplied";
         $chName = isset($pusherParams['channel']) ? $pusherParams['channel'] : "_im_pusher_default_channel";
         $this->generateAssignJS("INTERMediatorOnPage.clientNotificationKey", "function(){return ", arrayToJS($appKey, ''), ";}");
         $this->generateAssignJS("INTERMediatorOnPage.clientNotificationChannel", "function(){return ", arrayToJS($chName, ''), ";}");
     }
     if (isset($prohibitDebugMode) && $prohibitDebugMode) {
         $this->generateAssignJS("INTERMediator.debugMode", "false");
     } else {
         $this->generateAssignJS("INTERMediator.debugMode", $debug === false ? "false" : $debug);
     }
     // Check Authentication
     $boolValue = "false";
     $requireAuthenticationContext = array();
     if (isset($options['authentication'])) {
         $boolValue = "true";
     }
     foreach ($datasource as $aContext) {
         if (isset($aContext['authentication'])) {
             $boolValue = "true";
             $requireAuthenticationContext[] = $aContext['name'];
         }
     }
     $this->generateAssignJS("INTERMediatorOnPage.requireAuthentication", $boolValue);
     $this->generateAssignJS("INTERMediatorOnPage.authRequiredContext", arrayToJS($requireAuthenticationContext, ''));
     $this->generateAssignJS("INTERMediatorOnPage.isNativeAuth", isset($options['authentication']) && isset($options['authentication']['user']) && $options['authentication']['user'][0] === 'database_native' ? "true" : "false");
     $this->generateAssignJS("INTERMediatorOnPage.authStoring", $q, isset($options['authentication']) && isset($options['authentication']['storing']) ? $options['authentication']['storing'] : 'cookie', $q);
     $this->generateAssignJS("INTERMediatorOnPage.authExpired", isset($options['authentication']) && isset($options['authentication']['authexpired']) ? $options['authentication']['authexpired'] : '3600');
     $this->generateAssignJS("INTERMediatorOnPage.realm", $q, isset($options['authentication']) && isset($options['authentication']['realm']) ? $options['authentication']['realm'] : '', $q);
     if (isset($generatedPrivateKey)) {
         $rsa = new Crypt_RSA();
         $rsa->setPassword($passPhrase);
         $rsa->loadKey($generatedPrivateKey);
         $rsa->setPassword();
         $publickey = $rsa->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW);
         $this->generateAssignJS("INTERMediatorOnPage.publickey", "new biRSAKeyPair('", $publickey['e']->toHex(), "','0','", $publickey['n']->toHex(), "')");
     }
 }
コード例 #21
0
    public function testSavePKCS8PrivateKey()
    {
        $rsa = new Crypt_RSA();
        $key = '-----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->setPassword('password');
        $this->assertTrue($rsa->loadKey($key));
        $key = $rsa->getPrivateKey(CRYPT_RSA_PRIVATE_FORMAT_PKCS8);
        $this->assertInternalType('string', $key);
        $this->assertTrue($rsa->loadKey($key));
    }
コード例 #22
0
ファイル: functions_ts3.php プロジェクト: Eun/developer
function tsdns($action, $sship, $sshport, $sshuser, $keyuse, $sshkey, $sshpw, $notified, $path, $bitversion, $tsip, $tsport, $tsdns, $reseller_id, $maxnotified = 2)
{
    global $sql;
    $sshSftpObject = new Net_SFTP($sship, $sshport);
    if ($keyuse != 'N') {
        $privateKey = EASYWIDIR . '/keys/' . removePub($sshkey);
        $sshpw = new Crypt_RSA();
        if ($keyuse == 'B') {
            $sshpw->setPassword($sshpw);
        }
        $keyContent = @file_get_contents($privateKey);
        if ($keyContent) {
            $sshpw->loadKey($keyContent);
        }
    }
    if ($sshSftpObject->login($sshuser, $sshpw)) {
        $split_config = preg_split('/\\//', $path, -1, PREG_SPLIT_NO_EMPTY);
        $folderfilecount = count($split_config) - 1;
        $i = 0;
        $folders = substr($path, 0, 1) == '/' ? '/' : '';
        $lastFolder = '';
        while ($i <= $folderfilecount) {
            $folders .= $split_config[$i] . '/';
            $lastFolder = $split_config[$i];
            $i++;
        }
        if ($lastFolder != 'tsdns' or substr($path, 0, 1) != '/') {
            $folders .= 'tsdns/';
        }
        if ($action == 'md' or $action == 'dl') {
            $newip = $tsip[0];
            $oldip = isset($tsip[1]) ? $tsip[1] : '';
            $newport = $tsport[0];
            $oldport = isset($tsport[1]) ? $tsport[1] : '';
            $newdns = $tsdns[0];
            $olddns = isset($tsdns[1]) ? $tsdns[1] : '';
        } else {
            $dnsarray = array();
        }
        $file = substr($path, 0, 1) == '/' ? $folders . 'tsdns_settings.ini' : '/home/' . $sshuser . '/' . $folders . 'tsdns_settings.ini';
        if ($action != 'rs') {
            $data = $sshSftpObject->get($file);
            $data = str_replace(array("", "\\b", "\r", "\\Z"), '', $data);
        }
        if ($action != 'rs' and $action != 'mw') {
            $edited = false;
            $ca = array();
            foreach (preg_split('/\\n/', $data, -1, PREG_SPLIT_NO_EMPTY) as $configLine) {
                if ($action != 'li' and $configLine != $olddns . '=' . $oldip . ':' . $oldport and $configLine != $newdns . '=' . $newip . ':' . $newport) {
                    $ca[] = $configLine . "\r\n";
                } else {
                    if ($action == 'md' and $edited == false and ($configLine == $olddns . '=' . $oldip . ':' . $oldport or $configLine == $newdns . '=' . $newip . ':' . $newport)) {
                        $edited = true;
                        $ca[] = $newdns . '=' . $newip . ':' . $newport . "\r\n";
                    }
                }
                if ($action == 'li' and $configLine != '' and !preg_match('/^#(|\\s+)(.*)$/', $configLine)) {
                    $dnsconfig = explode('=', $configLine);
                    if (isset($dnsconfig[1])) {
                        $linedns = $dnsconfig[0];
                        $lineserver = $dnsconfig[1];
                        $dnsarray[$lineserver] = $linedns;
                    }
                }
            }
            if ($action == 'md' and $edited == false) {
                $ca[] = $newdns . '=' . $newip . ':' . $newport . "\r\n";
            }
            if ($action != 'li') {
                $ca = array_unique($ca);
                sort($ca);
                $newcfg = '';
                foreach ($ca as $line) {
                    $newcfg .= $line;
                }
                if ($newcfg == '') {
                    $newcfg = '# No TSDNS data entered';
                }
                $sshSftpObject->put($file, $newcfg);
            }
        }
        if ($action == 'mw' and isset($data)) {
            $usedIPs = array();
            foreach (preg_split('/\\n/', $data, -1, PREG_SPLIT_NO_EMPTY) as $configLine) {
                if ($configLine != '' and !preg_match('/^#(|\\s+)(.*)$/', $configLine)) {
                    $splittedLine = preg_split('/\\=/', $configLine, -1, PREG_SPLIT_NO_EMPTY);
                    $usedIPs[] = isset($splittedLine[1]) ? array('dns' => $splittedLine[0], 'address' => $splittedLine[1]) : $configLine;
                } else {
                    $usedIPs[] = $configLine;
                }
            }
            foreach ($tsip as $newLine) {
                $splittedLine = preg_split('/\\=/', strtolower($newLine), -1, PREG_SPLIT_NO_EMPTY);
                if (isset($splittedLine[1]) and !array_key_exists($splittedLine[1], $usedIPs)) {
                    $usedIPs[] = array('dns' => $splittedLine[0], 'address' => $splittedLine[1]);
                }
            }
            function array_multi_dimensional_unique($multi)
            {
                $unique = array();
                foreach ($multi as $sub) {
                    if (!in_array($sub, $unique)) {
                        $unique[] = $sub;
                    }
                }
                return $unique;
            }
            $newCfg = '';
            $usedIPs = array_multi_dimensional_unique($usedIPs);
            sort($usedIPs);
            foreach ($usedIPs as $value) {
                $newCfg .= (isset($value['dns']) and isset($value['address']) and !preg_match('/^#(|\\s+)(.*)$/', $value['dns'])) ? $value['dns'] . '=' . $value['address'] . "\r\n" : $value . "\r\n";
            }
            if ($newCfg == '') {
                $bad = 'Nothing to write';
            } else {
                $sshSftpObject->put($file, $newCfg);
            }
        }
        if (!isset($bad) and $action != 'li') {
            $sshObject = new Net_SSH2($sship, $sshport);
            if ($sshObject->error === false) {
                if ($sshObject->login($sshuser, $sshpw)) {
                    $bin = $bitversion == 32 ? 'tsdnsserver_linux_x86' : 'tsdnsserver_linux_amd64';
                    $ssh2cmd = 'cd ' . $folders . ' && function restart () { if [ "`ps fx | grep ' . $bin . ' | grep -v grep`" == "" ]; then ./' . $bin . ' > /dev/null & else ./' . $bin . ' --update > /dev/null & fi }; restart& ';
                    $sshObject->exec($ssh2cmd);
                    if ($notified > 0) {
                        $query = $sql->prepare("UPDATE `voice_masterserver` SET `notified`=0 WHERE `ssh2ip`=? AND `resellerid`=? LIMIT 1");
                        $query->execute(array($sship, $reseller_id));
                    }
                } else {
                    $bad = 'The login data does not work';
                    $notified++;
                }
            } else {
                $bad = 'Could not connect to Server';
                $notified++;
            }
        }
    } else {
        $bad = 'Could not connect to Server';
    }
    if (isset($bad) and $notified == $maxnotified) {
        if ($reseller_id == 0) {
            $query = $sql->prepare("SELECT `id`,`mail_serverdown` FROM `userdata` WHERE `resellerid`=0 AND `accounttype`='a'");
            $query->execute();
        } else {
            $query = $sql->prepare("SELECT `id`,`mail_serverdown` FROM `userdata` WHERE (`id`=? AND `id`=`resellerid`) OR (`resellerid`=0 AND `accounttype`='a')");
            $query->execute(array($reseller_id));
        }
        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            if ($row['mail_serverdown'] == 'Y') {
                sendmail('emaildown', $row['id'], 'TS3 Master ' . $sship . ' ( ' . $bad . ' )', '');
            }
        }
        $query = $sql->prepare("UPDATE `voice_masterserver` SET `notified`=`notified`+1 WHERE `ssh2ip`=? AND `resellerid`=? LIMIT 1");
        $query->execute(array($sship, $reseller_id));
        return $bad;
    } else {
        if (isset($bad)) {
            return $bad;
        } else {
            if ($action == 'li' and isset($dnsarray)) {
                return $dnsarray;
            }
        }
    }
    return 'ok';
}
コード例 #23
0
 /**
  * @param $privateKey
  * @param $password
  * @return \Crypt_RSA
  */
 private function getRsaCrypt($privateKey, $password = null)
 {
     $crypt = new \Crypt_RSA();
     $crypt->loadKey($privateKey);
     $crypt->setPassword($password);
     return $crypt;
 }
コード例 #24
0
    echo join('\\n', $startErrors);
    exit(1);
}
$ssh = new Net_SSH2($remoteHost, $remotePort);
if (strlen($password) == 0) {
    echo "Please enter key password:\n";
    system('stty -echo');
    $password = trim(fgets(STDIN));
    system('stty echo');
}
if (strlen($keyPath) > 0) {
    echo 'Using Key: ' . $keyPath . "\n";
    $privateKey = file_get_contents($keyPath);
    $key = new Crypt_RSA();
    if (strlen($password) > 0) {
        $key->setPassword($password);
    }
    $key->loadKey($privateKey);
    if ($ssh->login($username, $key)) {
        shellOut($ssh);
    } else {
        echo "Login Failed!\n";
    }
} else {
    if ($ssh->login($username, $password)) {
        shellOut($ssh);
    } else {
        echo "Login Failed!\n";
    }
}
function shellOut($ssh)
コード例 #25
0
ファイル: class_app.php プロジェクト: Eun/developer
 private function getKeyAndOrPassword()
 {
     if ($this->appMasterServerDetails['ssh2Publickey'] != 'N' and file_exists($this->appMasterServerDetails['privateKey'])) {
         $ssh2Pass = new Crypt_RSA();
         if ($this->appMasterServerDetails['ssh2Publickey'] == 'B') {
             $ssh2Pass->setPassword($this->appMasterServerDetails['ssh2DecryptedPass']);
         }
         $ssh2Pass->loadKey(file_get_contents($this->appMasterServerDetails['privateKey']));
     } else {
         $ssh2Pass = $this->appMasterServerDetails['ssh2DecryptedPass'];
     }
     return $ssh2Pass;
 }
コード例 #26
0
 /**
  * @param $dbProxyInstance
  * @param $options
  * @param $file
  * @param $isURL
  * @return array
  */
 public function checkForFileMakerMedia($dbProxyInstance, $options, $file, $isURL)
 {
     if (strpos($file, "/fmi/xml/cnt/") === 0) {
         // FileMaker's container field storing an image.
         if (isset($options['authentication']['user'][0]) && $options['authentication']['user'][0] == 'database_native') {
             $passPhrase = '';
             $generatedPrivateKey = '';
             // avoid errors for defined in params.php.
             $currentDir = dirname(__FILE__) . DIRECTORY_SEPARATOR;
             $currentDirParam = $currentDir . 'params.php';
             $parentDirParam = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'params.php';
             if (file_exists($parentDirParam)) {
                 include $parentDirParam;
             } else {
                 if (file_exists($currentDirParam)) {
                     include $currentDirParam;
                 }
             }
             $rsa = new Crypt_RSA();
             $rsa->setPassword($passPhrase);
             $rsa->loadKey($generatedPrivateKey);
             $rsa->setPassword();
             $privatekey = $rsa->getPrivateKey();
             $priv = $rsa->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
             require_once 'lib/bi2php/biRSA.php';
             $keyDecrypt = new biRSAKeyPair('0', $priv['privateExponent']->toHex(), $priv['modulus']->toHex());
             $cookieNameUser = '******';
             $cookieNamePassword = '******';
             $credential = isset($_COOKIE[$cookieNameUser]) ? urlencode($_COOKIE[$cookieNameUser]) : '';
             if (isset($_COOKIE[$cookieNamePassword])) {
                 $credential .= ':' . urlencode($keyDecrypt->biDecryptedString($_COOKIE[$cookieNamePassword]));
             }
             $urlHost = $dbProxyInstance->dbSettings->getDbSpecProtocol() . '://' . $credential . '@' . $dbProxyInstance->dbSettings->getDbSpecServer() . ':' . $dbProxyInstance->dbSettings->getDbSpecPort();
         } else {
             $urlHost = $dbProxyInstance->dbSettings->getDbSpecProtocol() . "://" . urlencode($dbProxyInstance->dbSettings->getDbSpecUser()) . ":" . urlencode($dbProxyInstance->dbSettings->getDbSpecPassword()) . "@" . $dbProxyInstance->dbSettings->getDbSpecServer() . ":" . $dbProxyInstance->dbSettings->getDbSpecPort();
         }
         $file = $urlHost . str_replace(" ", "%20", $file);
         foreach ($_GET as $key => $value) {
             if ($key !== 'media' && $key !== 'attach') {
                 $file .= "&" . urlencode($key) . "=" . urlencode($value);
             }
         }
         $isURL = true;
         return array($file, $isURL);
     }
     return array($file, $isURL);
 }
コード例 #27
0
ファイル: Database.php プロジェクト: svenjantzen/imscp
 /**
  * Decrypt any SSL private key
  *
  * @return array SQL statements to be executed
  */
 public function r178()
 {
     $sqlUdp = array();
     $stmt = execute_query('SELECT cert_id, password, `key` FROM ssl_certs');
     if ($stmt->rowCount()) {
         while ($row = $stmt->fetchRow(PDO::FETCH_ASSOC)) {
             $certId = quoteValue($row['cert_id'], PDO::PARAM_INT);
             $privateKey = new Crypt_RSA();
             if ($row['password'] != '') {
                 $privateKey->setPassword($row['password']);
             }
             if (!$privateKey->loadKey($row['key'], CRYPT_RSA_PRIVATE_FORMAT_PKCS1)) {
                 $sqlUdp[] = "DELETE FROM ssl_certs WHERE cert_id = {$certId}";
                 continue;
             }
             // Clear out passphrase
             $privateKey->setPassword();
             // Get unencrypted private key
             $privateKey = $privateKey->getPrivateKey();
             $privateKey = quoteValue($privateKey);
             $sqlUdp[] = "UPDATE ssl_certs SET `key` = {$privateKey} WHERE cert_id = {$certId}";
         }
     }
     return $sqlUdp;
 }
コード例 #28
0
ファイル: yf_ssh.class.php プロジェクト: yfix/yf
 /**
  * SFTP subsystem for phpseclib
  */
 function _init_sftp_phpseclib($server_info = [])
 {
     if (!$this->DRIVER == 'phpseclib') {
         return false;
     }
     if (!$this->_INIT_OK || !$server_info) {
         return false;
     }
     $ssh_host = $server_info['base_ip'] ? $server_info['base_ip'] : $server_info['ssh_host'];
     $ssh_port = $server_info['ssh_port'] ? $server_info['ssh_port'] : 22;
     if (!$ssh_host) {
         trigger_error('SSH: missing server IP to connect', E_USER_WARNING);
         return false;
     }
     $_SERVER_ID = $this->_get_server_id($server_info);
     // Cache calls to the same server
     if (isset($this->_sftp_connected[$_SERVER_ID])) {
         return $this->_sftp_connected[$_SERVER_ID];
     }
     if ($this->_sftp_try_to_connect[$_SERVER_ID] >= $this->MAX_RECONNECTS) {
         return $this->_sftp_connected[$_SERVER_ID];
     }
     $ssh_user = $server_info['ssh_user'] ? $server_info['ssh_user'] : '******';
     $ssh_pswd = $server_info['ssh_pswd'];
     if (DEBUG_MODE) {
         $time_start = microtime(true);
     }
     // Try to connect to server with selected params
     // This avoid long timeouts if server not connected
     $fp = fsockopen($ssh_host, $ssh_port, $errno, $errstr, $this->CONNECT_TIMEOUT);
     if (!$fp) {
         $this->_ssh_try_to_connect[$_SERVER_ID]++;
         trigger_error('SSH: cannot connect to: ' . $_SERVER_ID, E_USER_WARNING);
         return false;
     } else {
         fclose($fp);
     }
     $use_pswd = true;
     if ($this->AUTH_TYPE == 'pubkey' && !empty($server_info['ssh_key_private'])) {
         $use_pswd = false;
     }
     if (!$use_pswd) {
         $key = new Crypt_RSA();
         if ($server_info['ssh_key_pswd']) {
             $key->setPassword($server_info['ssh_key_pswd']);
             // password for key
         }
         $key_result = $key->loadKey(file_get_contents($server_info['ssh_key_private']));
         if (!$key_result) {
             $this->_ssh_try_to_connect[$_SERVER_ID]++;
             trigger_error('SSH: wrong key: ' . $server_info['ssh_key_private'] . ' for: ' . $_SERVER_ID . '', E_USER_WARNING);
             return false;
         }
     }
     require_once 'Net/SFTP.php';
     $con = new Net_SFTP($ssh_host);
     $auth_result = $con->login($ssh_user, $use_pswd ? $ssh_pswd : $key);
     if (DEBUG_MODE) {
         $this->_debug['connect_time'] += microtime(true) - $time_start;
     }
     if (!$con) {
         $this->_sftp_try_to_connect[$_SERVER_ID]++;
         trigger_error('SSH: cannot connect to: ' . $_SERVER_ID, E_USER_WARNING);
         return false;
     }
     if ($auth_result) {
         $this->_sftp_connected[$_SERVER_ID] = $con;
         $this->_log($server_info, __FUNCTION__, 'user: '******', auth successful');
         return $con;
     } else {
         trigger_error('SSH: auth on ' . $ssh_host . ':' . $ssh_port . ' failed for ' . ($this->AUTH_TYPE == 'pubkey' ? 'pubkey: ' . $server_info['pubkey_path'] : 'user: '******''), E_USER_WARNING);
     }
     return false;
 }
コード例 #29
0
ファイル: cron.php プロジェクト: xiaokangrj/cdp
 $ssh = new Net_SSH2($backupserver['host'], $backupserver['port']);
 $sftp = new Net_SFTP($backupserver['host'], $backupserver['port']);
 if ($backupserver['authtype'] == 'password') {
     if (!$ssh->login($backupserver['username'], $backupserver['password'])) {
         $log .= 'SSH password login failed' . PHP_EOL;
         exitcron();
     }
     if (!$sftp->login($backupserver['username'], $backupserver['password'])) {
         $log .= 'SFTP password login failed' . PHP_EOL;
         exitcron();
     }
 } elseif ($backupserver['authtype'] == 'key') {
     $serverkey = explode(' ', $backupserver['password']);
     $key = new Crypt_RSA();
     if (isset($serverkey[1])) {
         $key->setPassword($serverkey[1]);
     }
     $key->loadKey(file_get_contents($serverkey[0]));
     if (!$ssh->login($backupserver['username'], $key)) {
         $log .= 'SSH key login failed' . PHP_EOL;
         exitcron();
     }
     if (!$sftp->login($backupserver['username'], $key)) {
         $log .= 'SFTP key login failed' . PHP_EOL;
         exitcron();
     }
 } else {
     $log .= 'SSH login failed' . PHP_EOL;
     exitcron();
 }
 $dirname = 'cdpme-' . date("Y-m-d-H-i-s") . '-' . $backupjob['id'];
コード例 #30
0
 public function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB, $PAGE;
     if (empty($_GET['provider'])) {
         $token = (new Builder())->setIssuer('NITROCARD')->setAudience('NITROCARD')->setId(substr(md5(strtotime("now")), 0, 10), true)->setIssuedAt(time())->setExpiration(time() + 1800)->set('login', get_config('quiz_nitroreportpdf', 'apilogin'))->set('pass', get_config('quiz_nitroreportpdf', 'apipass'))->set('md5', md5(get_config('quiz_nitroreportpdf', 'pubkey')))->getToken();
         $rsa = new Crypt_RSA();
         $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
         $rsa->loadKey(get_config('quiz_nitroreportpdf', 'pubkey'));
         $enc = base64_encode($rsa->encrypt($token));
         unset($_COOKIE['nitrocardauth']);
         //LANG STRINGS FOR JS
         setcookie('nitrocardauth', '', time() - 3600, '/');
         setcookie("nitrocardauth", $enc, time() + 1800, "/");
         $PAGE->requires->jquery();
         $PAGE->requires->css(new moodle_url($CFG->wwwroot . "/auth/nitrocard/nitrocard.css"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.min.js"));
         $PAGE->requires->css(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.css"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/html5-qrcode/lib/html5-qrcode.min.js"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/jquery.json.min.js"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/jquery.jsonrpcclient.js"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/script.js"));
         $button = '<br /><br /><a href="javascript:void(0);" onclick="javascript:M.auth_nitrocard.main(\'start\');"><img src="' . new moodle_url($CFG->wwwroot . "/auth/nitrocard/login_ico.png") . '"></a><br /><br />';
         $PAGE->requires->js_init_call('M.auth_nitrocard.showbutton', array($button));
     } elseif ($_GET['provider'] == "nitrocard") {
         try {
             //LANG STRINGS FOR JS
             //	setcookie('nitrocard_lang_pleasewait', '', time() - 3600, '/');
             $PAGE->requires->jquery();
             $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.min.js"));
             $PAGE->requires->css(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.css"));
             $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/authload.js"));
             echo '<body onload="$.fn.nitro();"></body>';
             $rsa = new Crypt_RSA();
             $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
             $rsa->loadKey(get_config('quiz_nitroreportpdf', 'pubkey'));
             $ckey = $rsa->decrypt(base64_decode($_GET['auth']));
             $token = (new Parser())->parse((string) $ckey);
             if (!$token) {
                 throw new Exception('The data is invalid or time expired.');
             }
             if ($token->getClaim('iss') != "NITROCARD" || $token->getClaim('aud') != "NITROCARD" || strtotime("now") >= $token->getClaim('exp')) {
                 throw new Exception('The data is invalid or time expired.');
             }
             if (substr(strip_tags($token->getClaim('NITROCARDID')), 0, 9) != "NITROCARD" || strlen($token->getClaim('NITROCARDID')) < 98 || strlen($token->getClaim('NITROCARDID')) > 108) {
                 throw new Exception('NitroCard is invalid');
             }
             $card_e = explode('.', $token->getClaim('NITROCARDID'));
             if (count($card_e) != 5) {
                 throw new Exception('NitroCard is invalid');
             }
             $reqdb = $DB->count_records_sql('SELECT count(fullcardid) FROM {nitrocard_cards} WHERE fullcardid="' . $token->getClaim('NITROCARDID') . '" AND userid="' . $card_e[2] . '" AND cardid="' . $card_e[3] . '"AND hash="' . $card_e[4] . '"');
             if ($reqdb == 0) {
                 throw new Exception('NitroCard is invalid');
             } else {
                 $info = $DB->get_record_sql('SELECT user FROM {nitrocard_cards} WHERE fullcardid="' . $token->getClaim('NITROCARDID') . '"');
                 $user = get_complete_user_data('id', $info->user);
                 $USER = complete_user_login($user);
                 $USER->loggedin = true;
                 $USER->site = $CFG->wwwroot;
                 redirect(new moodle_url($CFG->wwwroot));
             }
         } catch (Exception $e) {
             throw new Exception($e->getMessage());
         }
     }
 }