You are here

protected function PGPAnalyzer::verifySignature in Mailhandler 8

Verifies the PGP signature.

Parameters

\Drupal\inmail\DefaultAnalyzerResult $result: The analyzer result instance containing PGP context.

Throws

\Exception Throws an exception in case verification fails.

1 call to PGPAnalyzer::verifySignature()
PGPAnalyzer::analyze in src/Plugin/inmail/Analyzer/PGPAnalyzer.php

File

src/Plugin/inmail/Analyzer/PGPAnalyzer.php, line 144

Class

PGPAnalyzer
An analyzer for PGP signed messages.

Namespace

Drupal\mailhandler\Plugin\inmail\Analyzer

Code

protected function verifySignature(DefaultAnalyzerResult $result) {
  if (!extension_loaded('gnupg')) {
    throw new \Exception('PHP extension "gnupg" has to enabled to verify the signature.');
  }
  $pgp_context = $result
    ->getContext('pgp');

  // Initialize GnuPG resource.
  $gpg = gnupg_init();

  // Verify PGP signature.
  $verification = gnupg_verify($gpg, $pgp_context
    ->getContextValue()['signed_text'], $pgp_context
    ->getContextValue()['signature']);

  // Only support "full" and "ultimate" trust levels.
  if (!$verification || $verification[0]['validity'] < GNUPG_VALIDITY_FULL) {
    throw new \Exception('Failed to analyze the message. PGP signature cannot be verified.');
  }

  // Get a fingerprint for the GPG public key.
  $fingerprint = $verification[0]['fingerprint'];
  $key_info = gnupg_keyinfo($gpg, $fingerprint);
  $key_info = reset($key_info);

  // Compare the fingerprint with the identified user's fingerprint.
  if ($fingerprint != $result
    ->getAccount()
    ->get('mailhandler_gpg_key')->fingerprint) {
    throw new \Exception('Failed to analyze the message. GPG key fingerprint mismatch.');
  }

  // Do not accept disabled, expired or revoked public keys.
  if ($key_info['disabled'] || $key_info['expired'] || $key_info['revoked']) {
    throw new \Exception('Failed to analyze the message. GPG public key was either disabled, expired or revoked.');
  }

  // Set a message verification flag to the context.
  $result
    ->setContext('verified', new Context(new ContextDefinition('string'), TRUE));
}