DkimSigner.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 $key;
  28. private $domainName;
  29. private $selector;
  30. private $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. if (!$this->key = openssl_pkey_get_private($pk, $passphrase)) {
  41. throw new InvalidArgumentException('Unable to load DKIM private key: '.openssl_error_string());
  42. }
  43. $this->domainName = $domainName;
  44. $this->selector = $selector;
  45. $this->defaultOptions = $defaultOptions + [
  46. 'algorithm' => self::ALGO_SHA256,
  47. 'signature_expiration_delay' => 0,
  48. 'body_max_length' => \PHP_INT_MAX,
  49. 'body_show_length' => false,
  50. 'header_canon' => self::CANON_RELAXED,
  51. 'body_canon' => self::CANON_RELAXED,
  52. 'headers_to_ignore' => [],
  53. ];
  54. }
  55. public function sign(Message $message, array $options = []): Message
  56. {
  57. $options += $this->defaultOptions;
  58. if (!\in_array($options['algorithm'], [self::ALGO_SHA256, self::ALGO_ED25519], true)) {
  59. throw new InvalidArgumentException('Invalid DKIM signing algorithm "%s".', $options['algorithm']);
  60. }
  61. $headersToIgnore['return-path'] = true;
  62. foreach ($options['headers_to_ignore'] as $name) {
  63. $headersToIgnore[strtolower($name)] = true;
  64. }
  65. unset($headersToIgnore['from']);
  66. $signedHeaderNames = [];
  67. $headerCanonData = '';
  68. $headers = $message->getPreparedHeaders();
  69. foreach ($headers->getNames() as $name) {
  70. foreach ($headers->all($name) as $header) {
  71. if (isset($headersToIgnore[strtolower($header->getName())])) {
  72. continue;
  73. }
  74. if ('' !== $header->getBodyAsString()) {
  75. $headerCanonData .= $this->canonicalizeHeader($header->toString(), $options['header_canon']);
  76. $signedHeaderNames[] = $header->getName();
  77. }
  78. }
  79. }
  80. [$bodyHash, $bodyLength] = $this->hashBody($message->getBody(), $options['body_canon'], $options['body_max_length']);
  81. $params = [
  82. 'v' => '1',
  83. 'q' => 'dns/txt',
  84. 'a' => $options['algorithm'],
  85. 'bh' => base64_encode($bodyHash),
  86. 'd' => $this->domainName,
  87. 'h' => implode(': ', $signedHeaderNames),
  88. 'i' => '@'.$this->domainName,
  89. 's' => $this->selector,
  90. 't' => time(),
  91. 'c' => $options['header_canon'].'/'.$options['body_canon'],
  92. ];
  93. if ($options['body_show_length']) {
  94. $params['l'] = $bodyLength;
  95. }
  96. if ($options['signature_expiration_delay']) {
  97. $params['x'] = $params['t'] + $options['signature_expiration_delay'];
  98. }
  99. $value = '';
  100. foreach ($params as $k => $v) {
  101. $value .= $k.'='.$v.'; ';
  102. }
  103. $value = trim($value);
  104. $header = new UnstructuredHeader('DKIM-Signature', $value);
  105. $headerCanonData .= rtrim($this->canonicalizeHeader($header->toString()."\r\n b=", $options['header_canon']));
  106. if (self::ALGO_SHA256 === $options['algorithm']) {
  107. if (!openssl_sign($headerCanonData, $signature, $this->key, \OPENSSL_ALGO_SHA256)) {
  108. throw new RuntimeException('Unable to sign DKIM hash: '.openssl_error_string());
  109. }
  110. } else {
  111. throw new \RuntimeException(sprintf('The "%s" DKIM signing algorithm is not supported yet.', self::ALGO_ED25519));
  112. }
  113. $header->setValue($value.' b='.trim(chunk_split(base64_encode($signature), 73, ' ')));
  114. $headers->add($header);
  115. return new Message($headers, $message->getBody());
  116. }
  117. private function canonicalizeHeader(string $header, string $headerCanon): string
  118. {
  119. if (self::CANON_RELAXED !== $headerCanon) {
  120. return $header."\r\n";
  121. }
  122. $exploded = explode(':', $header, 2);
  123. $name = strtolower(trim($exploded[0]));
  124. $value = str_replace("\r\n", '', $exploded[1]);
  125. $value = trim(preg_replace("/[ \t][ \t]+/", ' ', $value));
  126. return $name.':'.$value."\r\n";
  127. }
  128. private function hashBody(AbstractPart $body, string $bodyCanon, int $maxLength): array
  129. {
  130. $hash = hash_init('sha256');
  131. $relaxed = self::CANON_RELAXED === $bodyCanon;
  132. $currentLine = '';
  133. $emptyCounter = 0;
  134. $isSpaceSequence = false;
  135. $length = 0;
  136. foreach ($body->bodyToIterable() as $chunk) {
  137. $canon = '';
  138. for ($i = 0, $len = \strlen($chunk); $i < $len; ++$i) {
  139. switch ($chunk[$i]) {
  140. case "\r":
  141. break;
  142. case "\n":
  143. // previous char is always \r
  144. if ($relaxed) {
  145. $isSpaceSequence = false;
  146. }
  147. if ('' === $currentLine) {
  148. ++$emptyCounter;
  149. } else {
  150. $currentLine = '';
  151. $canon .= "\r\n";
  152. }
  153. break;
  154. case ' ':
  155. case "\t":
  156. if ($relaxed) {
  157. $isSpaceSequence = true;
  158. break;
  159. }
  160. // no break
  161. default:
  162. if ($emptyCounter > 0) {
  163. $canon .= str_repeat("\r\n", $emptyCounter);
  164. $emptyCounter = 0;
  165. }
  166. if ($isSpaceSequence) {
  167. $currentLine .= ' ';
  168. $canon .= ' ';
  169. $isSpaceSequence = false;
  170. }
  171. $currentLine .= $chunk[$i];
  172. $canon .= $chunk[$i];
  173. }
  174. }
  175. if ($length + \strlen($canon) >= $maxLength) {
  176. $canon = substr($canon, 0, $maxLength - $length);
  177. $length += \strlen($canon);
  178. hash_update($hash, $canon);
  179. break;
  180. }
  181. $length += \strlen($canon);
  182. hash_update($hash, $canon);
  183. }
  184. if (0 === $length) {
  185. hash_update($hash, "\r\n");
  186. $length = 2;
  187. }
  188. return [hash_final($hash, true), $length];
  189. }
  190. }