Kevin Gravell Kevin Gravell - 5 years ago 202
PHP Question

Check if an entered public key is a valid OpenPGP key

I'm using the GnuPG class from PHP. I'm not having any problem importing valid public key but if I try to import something random like "test" which obviously isn't a public key, I'm getting error 502 bad gateway. I saw into PHP documentation that

gnupg_keyinfo
shows information introducing a name stored in the keyring. I searched around the internet and I didn't find a way to check if an entered public key is in the right format or not.
I'm using the following piece of code:

<?php
putenv('GNUPGHOME=/home/kevin/.gnupg');
$gpg = '/usr/bin/gpg';
$gpg = new gnupg();
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

if(isset($_POST['2fa'])){
try {
$key = $_POST['new_pgp'];
$retVal = $gpg->import($key);
echo $retVal['imported'] . ' key(s) imported.';
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}

}
?>
<html>
<body>
<form action="testpgp.php" method="post">
<textarea name="new_pgp"></textarea><br>
<input type="submit" name="2fa" value="Send">
</form>
</body>
</html>

Answer Source

An error 502 "Bad Gateway" indicates that the connection between the web server and something behind it got interrupted -- this happens for example when using nginx together with php-fpm, which is accessed throughout another network connection/socket. In the comments requesting further debug information you confirmed that guess, and also realized php is crashing because of a segmentation fault, which means some invalid memory location should have been accessed.

This can either happen because of a bug (which I wouldn't expect in this case, as an invalid key is not some completely surprising input nobody would test for) or because the compiled versions do not really fit together. You explained you build some parts on your own.

Debugging this is a hassle and often takes hours and hours, you'd need to attach a debugger and realize what's going wrong. If you have any chance, try to install everything from the package manager of your choice, do not use different sources like PECL and your packager manager to prevent problems. In Debian (and very likely also Ubuntu and other distributions, I didn't verify) some package like php5-gnupg should be available:

$ apt-cache show php5-gnupg
Package: php5-gnupg
Source: php-gnupg
Version: 1.3.6-1
Installed-Size: 84
Maintainer: Debian PHP PECL Maintainers <pkg-php-pecl@lists.alioth.debian.org>
Architecture: amd64
Depends: phpapi-20131226, php5-common (>= 4.4), libc6 (>= 2.4), libgpgme11 (>= 1.2.0)
Description-en: wrapper around the gpgme library
 This extension provides methods to interact with gnupg.
[snip]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download