PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Symfony/Component/Mime/Crypto/DkimSigner.php

https://github.com/FabienD/symfony
PHP | 217 lines | 174 code | 23 blank | 20 comment | 22 complexity | f6f518b3b04130fe40edde9aebecf415 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mime\Crypto;
  11. use Symfony\Component\Mime\Exception\InvalidArgumentException;
  12. use Symfony\Component\Mime\Exception\RuntimeException;
  13. use Symfony\Component\Mime\Header\UnstructuredHeader;
  14. use Symfony\Component\Mime\Message;
  15. use Symfony\Component\Mime\Part\AbstractPart;
  16. /**
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. *
  19. * RFC 6376 and 8301
  20. */
  21. final class DkimSigner
  22. {
  23. public const CANON_SIMPLE = 'simple';
  24. public const CANON_RELAXED = 'relaxed';
  25. public const ALGO_SHA256 = 'rsa-sha256';
  26. public const ALGO_ED25519 = 'ed25519-sha256'; // RFC 8463
  27. private \OpenSSLAsymmetricKey $key;
  28. private string $domainName;
  29. private string $selector;
  30. private array $defaultOptions;
  31. /**
  32. * @param string $pk The private key as a string or the path to the file containing the private key, should be prefixed with file:// (in PEM format)
  33. * @param string $passphrase A passphrase of the private key (if any)
  34. */
  35. public function __construct(string $pk, string $domainName, string $selector, array $defaultOptions = [], string $passphrase = '')
  36. {
  37. if (!\extension_loaded('openssl')) {
  38. throw new \LogicException('PHP extension "openssl" is required to use DKIM.');
  39. }
  40. $this->key = openssl_pkey_get_private($pk, $passphrase) ?: throw new InvalidArgumentException('Unable to load DKIM private key: '.openssl_error_string());
  41. $this->domainName = $domainName;
  42. $this->selector = $selector;
  43. $this->defaultOptions = $defaultOptions + [
  44. 'algorithm' => self::ALGO_SHA256,
  45. 'signature_expiration_delay' => 0,
  46. 'body_max_length' => \PHP_INT_MAX,
  47. 'body_show_length' => false,
  48. 'header_canon' => self::CANON_RELAXED,
  49. 'body_canon' => self::CANON_RELAXED,
  50. 'headers_to_ignore' => [],
  51. ];
  52. }
  53. public function sign(Message $message, array $options = []): Message
  54. {
  55. $options += $this->defaultOptions;
  56. if (!\in_array($options['algorithm'], [self::ALGO_SHA256, self::ALGO_ED25519], true)) {
  57. throw new InvalidArgumentException(sprintf('Invalid DKIM signing algorithm "%s".', $options['algorithm']));
  58. }
  59. $headersToIgnore['return-path'] = true;
  60. $headersToIgnore['x-transport'] = true;
  61. foreach ($options['headers_to_ignore'] as $name) {
  62. $headersToIgnore[strtolower($name)] = true;
  63. }
  64. unset($headersToIgnore['from']);
  65. $signedHeaderNames = [];
  66. $headerCanonData = '';
  67. $headers = $message->getPreparedHeaders();
  68. foreach ($headers->getNames() as $name) {
  69. foreach ($headers->all($name) as $header) {
  70. if (isset($headersToIgnore[strtolower($header->getName())])) {
  71. continue;
  72. }
  73. if ('' !== $header->getBodyAsString()) {
  74. $headerCanonData .= $this->canonicalizeHeader($header->toString(), $options['header_canon']);
  75. $signedHeaderNames[] = $header->getName();
  76. }
  77. }
  78. }
  79. [$bodyHash, $bodyLength] = $this->hashBody($message->getBody(), $options['body_canon'], $options['body_max_length']);
  80. $params = [
  81. 'v' => '1',
  82. 'q' => 'dns/txt',
  83. 'a' => $options['algorithm'],
  84. 'bh' => base64_encode($bodyHash),
  85. 'd' => $this->domainName,
  86. 'h' => implode(': ', $signedHeaderNames),
  87. 'i' => '@'.$this->domainName,
  88. 's' => $this->selector,
  89. 't' => time(),
  90. 'c' => $options['header_canon'].'/'.$options['body_canon'],
  91. ];
  92. if ($options['body_show_length']) {
  93. $params['l'] = $bodyLength;
  94. }
  95. if ($options['signature_expiration_delay']) {
  96. $params['x'] = $params['t'] + $options['signature_expiration_delay'];
  97. }
  98. $value = '';
  99. foreach ($params as $k => $v) {
  100. $value .= $k.'='.$v.'; ';
  101. }
  102. $value = trim($value);
  103. $header = new UnstructuredHeader('DKIM-Signature', $value);
  104. $headerCanonData .= rtrim($this->canonicalizeHeader($header->toString()."\r\n b=", $options['header_canon']));
  105. if (self::ALGO_SHA256 === $options['algorithm']) {
  106. if (!openssl_sign($headerCanonData, $signature, $this->key, \OPENSSL_ALGO_SHA256)) {
  107. throw new RuntimeException('Unable to sign DKIM hash: '.openssl_error_string());
  108. }
  109. } else {
  110. throw new \RuntimeException(sprintf('The "%s" DKIM signing algorithm is not supported yet.', self::ALGO_ED25519));
  111. }
  112. $header->setValue($value.' b='.trim(chunk_split(base64_encode($signature), 73, ' ')));
  113. $headers->add($header);
  114. return new Message($headers, $message->getBody());
  115. }
  116. private function canonicalizeHeader(string $header, string $headerCanon): string
  117. {
  118. if (self::CANON_RELAXED !== $headerCanon) {
  119. return $header."\r\n";
  120. }
  121. $exploded = explode(':', $header, 2);
  122. $name = strtolower(trim($exploded[0]));
  123. $value = str_replace("\r\n", '', $exploded[1]);
  124. $value = trim(preg_replace("/[ \t][ \t]+/", ' ', $value));
  125. return $name.':'.$value."\r\n";
  126. }
  127. private function hashBody(AbstractPart $body, string $bodyCanon, int $maxLength): array
  128. {
  129. $hash = hash_init('sha256');
  130. $relaxed = self::CANON_RELAXED === $bodyCanon;
  131. $currentLine = '';
  132. $emptyCounter = 0;
  133. $isSpaceSequence = false;
  134. $length = 0;
  135. foreach ($body->bodyToIterable() as $chunk) {
  136. $canon = '';
  137. for ($i = 0, $len = \strlen($chunk); $i < $len; ++$i) {
  138. switch ($chunk[$i]) {
  139. case "\r":
  140. break;
  141. case "\n":
  142. // previous char is always \r
  143. if ($relaxed) {
  144. $isSpaceSequence = false;
  145. }
  146. if ('' === $currentLine) {
  147. ++$emptyCounter;
  148. } else {
  149. $currentLine = '';
  150. $canon .= "\r\n";
  151. }
  152. break;
  153. case ' ':
  154. case "\t":
  155. if ($relaxed) {
  156. $isSpaceSequence = true;
  157. break;
  158. }
  159. // no break
  160. default:
  161. if ($emptyCounter > 0) {
  162. $canon .= str_repeat("\r\n", $emptyCounter);
  163. $emptyCounter = 0;
  164. }
  165. if ($isSpaceSequence) {
  166. $currentLine .= ' ';
  167. $canon .= ' ';
  168. $isSpaceSequence = false;
  169. }
  170. $currentLine .= $chunk[$i];
  171. $canon .= $chunk[$i];
  172. }
  173. }
  174. if ($length + \strlen($canon) >= $maxLength) {
  175. $canon = substr($canon, 0, $maxLength - $length);
  176. $length += \strlen($canon);
  177. hash_update($hash, $canon);
  178. break;
  179. }
  180. $length += \strlen($canon);
  181. hash_update($hash, $canon);
  182. }
  183. // Add trailing Line return if last line is non empty
  184. if ('' !== $currentLine) {
  185. hash_update($hash, "\r\n");
  186. $length += \strlen("\r\n");
  187. }
  188. if (!$relaxed && 0 === $length) {
  189. hash_update($hash, "\r\n");
  190. $length = 2;
  191. }
  192. return [hash_final($hash, true), $length];
  193. }
  194. }