Skip to content

can't load ssh key with extra spaces #2116

@simonLeary42

Description

@simonLeary42

phpseclib cannot load an authorized_keys-formatted public key with extra spaces:

<?php
ini_set("display_errors", 0);
require "./vendor/autoload.php";
echo "loading normal key...\n";
\phpseclib3\Crypt\PublicKeyLoader::load('ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPbF9S6UiJErdX2OK9TCTn+CODCLTvBur2uAFyHluYLf foo');
echo "loading key with 2 spaces...\n";
\phpseclib3\Crypt\PublicKeyLoader::load('ssh-ed25519  AAAAC3NzaC1lZDI1NTE5AAAAIPbF9S6UiJErdX2OK9TCTn+CODCLTvBur2uAFyHluYLf bar');
loading normal key...
loading key with 2 spaces...
PHP Fatal error:  Uncaught phpseclib3\Exception\NoKeyLoadedException: Unable to read key in /.../vendor/phpseclib/phpseclib/phpseclib/Crypt/PublicKeyLoader.php:64
Stack trace:
#0 /.../test.php(7): phpseclib3\Crypt\PublicKeyLoader::load(false)
#1 {main}
  thrown in /.../vendor/phpseclib/phpseclib/phpseclib/Crypt/PublicKeyLoader.php on line 64

This is due to the behavior of explode:

$parts = explode(' ', $key, 3);
if (!isset($parts[1])) {
$key = base64_decode($parts[0]);
$comment = false;
} else {
$asciiType = $parts[0];
self::checkType($parts[0]);
$key = base64_decode($parts[1]);
$comment = $parts[2] ?? false;
}
if ($key === false) {
throw new UnexpectedValueException('Key should be a string - not a ' . gettype($key));
}
[$type] = Strings::unpackSSH2('s', $key);
self::checkType($type);
if (isset($asciiType) && $asciiType != $type) {
throw new RuntimeException('Two different types of keys are claimed: ' . $asciiType . ' and ' . $type);
}

php > var_dump(explode(" ", "hello world"));
array(2) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(5) "world"
}
php > var_dump(explode(" ", "hello  world"));
array(3) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(0) ""
  [2]=>
  string(5) "world"
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions