Skip to content

Instantly share code, notes, and snippets.

@piotrplenik
Created August 3, 2012 14:25
Show Gist options
  • Save piotrplenik/3248095 to your computer and use it in GitHub Desktop.
Save piotrplenik/3248095 to your computer and use it in GitHub Desktop.
SSH-RSA/SSH-DSA validation
<?php
public function validateKey($value)
{
$key_parts = explode(' ', $value, 3);
if (count($key_parts) < 2) {
return false;
}
if (count($key_parts) > 3) {
return false;
}
$algorithm = $key_parts[0];
$key = $key_parts[1];
if (!in_array($algorithm, array('ssh-rsa', 'ssh-dss'))) {
return false;
}
$key_base64_decoded = base64_decode($key, true);
if ($key_base64_decoded == FALSE) {
return false;
}
$check = base64_decode(substr($key,0,16));
$check = preg_replace("/[^\w\-]/","", $check);
if((string) $check !== (string) $algorithm) {
return false;
}
return true;
}
@Rixafy
Copy link

Rixafy commented Feb 7, 2023

There is an vulnerability at

 if (count($key_parts) > 3) {

because explode(' ', $value, 3) will always result in count <= 3, so invalid key could pass.

Solution is to change explode(' ', $value, 3) to explode(' ', $value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment