DKIMSigner.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. <?php
  2. /*
  3. * This file is part of SwiftMailer.
  4. * (c) 2004-2009 Chris Corbyn
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * DKIM Signer used to apply DKIM Signature to a message
  11. *
  12. * @author Xavier De Cock <xdecock@gmail.com>
  13. */
  14. class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner
  15. {
  16. /**
  17. * PrivateKey
  18. *
  19. * @var string
  20. */
  21. protected $_privateKey;
  22. /**
  23. * DomainName
  24. *
  25. * @var string
  26. */
  27. protected $_domainName;
  28. /**
  29. * Selector
  30. *
  31. * @var string
  32. */
  33. protected $_selector;
  34. /**
  35. * Hash algorithm used
  36. *
  37. * @var string
  38. */
  39. protected $_hashAlgorithm = 'rsa-sha1';
  40. /**
  41. * Body canon method
  42. *
  43. * @var string
  44. */
  45. protected $_bodyCanon = 'simple';
  46. /**
  47. * Header canon method
  48. *
  49. * @var string
  50. */
  51. protected $_headerCanon = 'simple';
  52. /**
  53. * Headers not being signed
  54. *
  55. * @var array
  56. */
  57. protected $_ignoredHeaders = array();
  58. /**
  59. * Signer identity
  60. *
  61. * @var unknown_type
  62. */
  63. protected $_signerIdentity;
  64. /**
  65. * BodyLength
  66. *
  67. * @var int
  68. */
  69. protected $_bodyLen = 0;
  70. /**
  71. * Maximum signedLen
  72. *
  73. * @var int
  74. */
  75. protected $_maxLen = PHP_INT_MAX;
  76. /**
  77. * Embbed bodyLen in signature
  78. *
  79. * @var bool
  80. */
  81. protected $_showLen = false;
  82. /**
  83. * When the signature has been applied (true means time()), false means not embedded
  84. *
  85. * @var mixed
  86. */
  87. protected $_signatureTimestamp = true;
  88. /**
  89. * When will the signature expires false means not embedded, if sigTimestamp is auto
  90. * Expiration is relative, otherwhise it's absolute
  91. *
  92. * @var int
  93. */
  94. protected $_signatureExpiration = false;
  95. /**
  96. * Must we embed signed headers?
  97. *
  98. * @var bool
  99. */
  100. protected $_debugHeaders = false;
  101. // work variables
  102. /**
  103. * Headers used to generate hash
  104. *
  105. * @var array
  106. */
  107. protected $_signedHeaders = array();
  108. /**
  109. * If debugHeaders is set store debugDatas here
  110. *
  111. * @var string
  112. */
  113. private $_debugHeadersData = '';
  114. /**
  115. * Stores the bodyHash
  116. *
  117. * @var string
  118. */
  119. private $_bodyHash = '';
  120. /**
  121. * Stores the signature header
  122. *
  123. * @var Swift_Mime_Headers_ParameterizedHeader
  124. */
  125. protected $_dkimHeader;
  126. /**
  127. * Hash Handler
  128. *
  129. * @var hash_ressource
  130. */
  131. private $_headerHashHandler;
  132. private $_bodyHashHandler;
  133. private $_headerHash;
  134. private $_headerCanonData = '';
  135. private $_bodyCanonEmptyCounter = 0;
  136. private $_bodyCanonIgnoreStart = 2;
  137. private $_bodyCanonSpace = false;
  138. private $_bodyCanonLastChar = null;
  139. private $_bodyCanonLine = '';
  140. private $_bound = array();
  141. /**
  142. * Constructor
  143. *
  144. * @param string $privateKey
  145. * @param string $domainName
  146. * @param string $selector
  147. */
  148. public function __construct($privateKey, $domainName, $selector)
  149. {
  150. $this->_privateKey = $privateKey;
  151. $this->_domainName = $domainName;
  152. $this->_signerIdentity = '@' . $domainName;
  153. $this->_selector = $selector;
  154. }
  155. /**
  156. * Instanciate DKIMSigner
  157. *
  158. * @param string $privateKey
  159. * @param string $domainName
  160. * @param string $selector
  161. * @return Swift_Signers_DKIMSigner
  162. */
  163. public static function newInstance($privateKey, $domainName, $selector)
  164. {
  165. return new static($privateKey, $domainName, $selector);
  166. }
  167. /**
  168. * Reset the Signer
  169. * @see Swift_Signer::reset()
  170. */
  171. public function reset()
  172. {
  173. $this->_headerHash = null;
  174. $this->_signedHeaders = array();
  175. $this->_headerHashHandler = null;
  176. $this->_bodyHash = null;
  177. $this->_bodyHashHandler = null;
  178. $this->_bodyCanonIgnoreStart = 2;
  179. $this->_bodyCanonEmptyCounter = 0;
  180. $this->_bodyCanonLastChar = null;
  181. $this->_bodyCanonSpace = false;
  182. }
  183. /**
  184. * Writes $bytes to the end of the stream.
  185. *
  186. * Writing may not happen immediately if the stream chooses to buffer. If
  187. * you want to write these bytes with immediate effect, call {@link commit()}
  188. * after calling write().
  189. *
  190. * This method returns the sequence ID of the write (i.e. 1 for first, 2 for
  191. * second, etc etc).
  192. *
  193. * @param string $bytes
  194. * @return int
  195. * @throws Swift_IoException
  196. */
  197. public function write($bytes)
  198. {
  199. $this->_canonicalizeBody($bytes);
  200. foreach ($this->_bound as $is) {
  201. $is->write($bytes);
  202. }
  203. }
  204. /**
  205. * For any bytes that are currently buffered inside the stream, force them
  206. * off the buffer.
  207. *
  208. * @throws Swift_IoException
  209. */
  210. public function commit()
  211. {
  212. // Nothing to do
  213. return;
  214. }
  215. /**
  216. * Attach $is to this stream.
  217. * The stream acts as an observer, receiving all data that is written.
  218. * All {@link write()} and {@link flushBuffers()} operations will be mirrored.
  219. *
  220. * @param Swift_InputByteStream $is
  221. */
  222. public function bind(Swift_InputByteStream $is)
  223. {
  224. // Don't have to mirror anything
  225. $this->_bound[] = $is;
  226. return;
  227. }
  228. /**
  229. * Remove an already bound stream.
  230. * If $is is not bound, no errors will be raised.
  231. * If the stream currently has any buffered data it will be written to $is
  232. * before unbinding occurs.
  233. *
  234. * @param Swift_InputByteStream $is
  235. */
  236. public function unbind(Swift_InputByteStream $is)
  237. {
  238. // Don't have to mirror anything
  239. foreach ($this->_bound as $k => $stream) {
  240. if ($stream === $is) {
  241. unset($this->_bound[$k]);
  242. return;
  243. }
  244. }
  245. return;
  246. }
  247. /**
  248. * Flush the contents of the stream (empty it) and set the internal pointer
  249. * to the beginning.
  250. *
  251. * @throws Swift_IoException
  252. */
  253. public function flushBuffers()
  254. {
  255. $this->reset();
  256. }
  257. /**
  258. * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256
  259. *
  260. * @param string $hash
  261. * @return Swift_Signers_DKIMSigner
  262. */
  263. public function setHashAlgorithm($hash)
  264. {
  265. // Unable to sign with rsa-sha256
  266. if ($hash == 'rsa-sha1') {
  267. $this->_hashAlgorithm = 'rsa-sha1';
  268. } else {
  269. $this->_hashAlgorithm = 'rsa-sha256';
  270. }
  271. return $this;
  272. }
  273. /**
  274. * Set the body canonicalization algorithm
  275. *
  276. * @param string $canon
  277. * @return Swift_Signers_DKIMSigner
  278. */
  279. public function setBodyCanon($canon)
  280. {
  281. if ($canon == 'relaxed') {
  282. $this->_bodyCanon = 'relaxed';
  283. } else {
  284. $this->_bodyCanon = 'simple';
  285. }
  286. return $this;
  287. }
  288. /**
  289. * Set the header canonicalization algorithm
  290. *
  291. * @param string $canon
  292. * @return Swift_Signers_DKIMSigner
  293. */
  294. public function setHeaderCanon($canon)
  295. {
  296. if ($canon == 'relaxed') {
  297. $this->_headerCanon = 'relaxed';
  298. } else {
  299. $this->_headerCanon = 'simple';
  300. }
  301. return $this;
  302. }
  303. /**
  304. * Set the signer identity
  305. *
  306. * @param string $identity
  307. * @return Swift_Signers_DKIMSigner
  308. */
  309. public function setSignerIdentity($identity)
  310. {
  311. $this->_signerIdentity = $identity;
  312. return $this;
  313. }
  314. /**
  315. * Set the length of the body to sign
  316. *
  317. * @param mixed $len (bool or int)
  318. * @return Swift_Signers_DKIMSigner
  319. */
  320. public function setBodySignedLen($len)
  321. {
  322. if ($len === true) {
  323. $this->_showLen = true;
  324. $this->_maxLen = PHP_INT_MAX;
  325. } elseif ($len === false) {
  326. $this->showLen = false;
  327. $this->_maxLen = PHP_INT_MAX;
  328. } else {
  329. $this->_showLen = true;
  330. $this->_maxLen = (int) $len;
  331. }
  332. return $this;
  333. }
  334. /**
  335. * Set the signature timestamp
  336. *
  337. * @param timestamp $time
  338. * @return Swift_Signers_DKIMSigner
  339. */
  340. public function setSignatureTimestamp($time)
  341. {
  342. $this->_signatureTimestamp = $time;
  343. return $this;
  344. }
  345. /**
  346. * Set the signature expiration timestamp
  347. *
  348. * @param timestamp $time
  349. * @return Swift_Signers_DKIMSigner
  350. */
  351. public function setSignatureExpiration($time)
  352. {
  353. $this->_signatureExpiration = $time;
  354. return $this;
  355. }
  356. /**
  357. * Enable / disable the DebugHeaders
  358. *
  359. * @param bool $debug
  360. * @return Swift_Signers_DKIMSigner
  361. */
  362. public function setDebugHeaders($debug)
  363. {
  364. $this->_debugHeaders = (bool) $debug;
  365. return $this;
  366. }
  367. /**
  368. * Start Body
  369. *
  370. */
  371. public function startBody()
  372. {
  373. // Init
  374. switch ($this->_hashAlgorithm) {
  375. case 'rsa-sha256' :
  376. $this->_bodyHashHandler = hash_init('sha256');
  377. break;
  378. case 'rsa-sha1' :
  379. $this->_bodyHashHandler = hash_init('sha1');
  380. break;
  381. }
  382. $this->_bodyCanonLine = '';
  383. }
  384. /**
  385. * End Body
  386. *
  387. */
  388. public function endBody()
  389. {
  390. $this->_endOfBody();
  391. }
  392. /**
  393. * Returns the list of Headers Tampered by this plugin
  394. *
  395. * @return array
  396. */
  397. public function getAlteredHeaders()
  398. {
  399. if ($this->_debugHeaders) {
  400. return array('DKIM-Signature', 'X-DebugHash');
  401. } else {
  402. return array('DKIM-Signature');
  403. }
  404. }
  405. /**
  406. * Adds an ignored Header
  407. *
  408. * @param string $header_name
  409. * @return Swift_Signers_DKIMSigner
  410. */
  411. public function ignoreHeader($header_name)
  412. {
  413. $this->_ignoredHeaders[strtolower($header_name)] = true;
  414. return $this;
  415. }
  416. /**
  417. * Set the headers to sign
  418. *
  419. * @param Swift_Mime_HeaderSet $headers
  420. * @return Swift_Signers_DKIMSigner
  421. */
  422. public function setHeaders(Swift_Mime_HeaderSet $headers)
  423. {
  424. $this->_headerCanonData = '';
  425. // Loop through Headers
  426. $listHeaders = $headers->listAll();
  427. foreach ($listHeaders as $hName) {
  428. // Check if we need to ignore Header
  429. if (! isset($this->_ignoredHeaders[strtolower($hName)])) {
  430. if ($headers->has($hName)) {
  431. $tmp = $headers->getAll($hName);
  432. foreach ($tmp as $header) {
  433. if ($header->getFieldBody() != '') {
  434. $this->_addHeader($header->toString());
  435. $this->_signedHeaders[] = $header->getFieldName();
  436. }
  437. }
  438. }
  439. }
  440. }
  441. return $this;
  442. }
  443. /**
  444. * Add the signature to the given Headers
  445. *
  446. * @param Swift_Mime_HeaderSet $headers
  447. * @return Swift_Signers_DKIMSigner
  448. */
  449. public function addSignature(Swift_Mime_HeaderSet $headers)
  450. {
  451. // Prepare the DKIM-Signature
  452. $params = array('v' => '1', 'a' => $this->_hashAlgorithm, 'bh' => base64_encode($this->_bodyHash), 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'i' => $this->_signerIdentity, 's' => $this->_selector);
  453. if ($this->_bodyCanon != 'simple') {
  454. $params['c'] = $this->_headerCanon . '/' . $this->_bodyCanon;
  455. } elseif ($this->_headerCanon != 'simple') {
  456. $params['c'] = $this->_headerCanon;
  457. }
  458. if ($this->_showLen) {
  459. $params['l'] = $this->_bodyLen;
  460. }
  461. if ($this->_signatureTimestamp === true) {
  462. $params['t'] = time();
  463. if ($this->_signatureExpiration !== false) {
  464. $params['x'] = $params['t'] + $this->_signatureExpiration;
  465. }
  466. } else {
  467. if ($this->_signatureTimestamp !== false) {
  468. $params['t'] = $this->_signatureTimestamp;
  469. }
  470. if ($this->_signatureExpiration !== false) {
  471. $params['x'] = $this->_signatureExpiration;
  472. }
  473. }
  474. if ($this->_debugHeaders) {
  475. $params['z'] = implode('|', $this->_debugHeadersData);
  476. }
  477. $string = '';
  478. foreach ($params as $k => $v) {
  479. $string .= $k . '=' . $v . '; ';
  480. }
  481. $string = trim($string);
  482. $headers->addTextHeader('DKIM-Signature', $string);
  483. // Add the last DKIM-Signature
  484. $tmp = $headers->getAll('DKIM-Signature');
  485. $this->_dkimHeader = end($tmp);
  486. $this->_addHeader(trim($this->_dkimHeader->toString()) . "\r\n b=", true);
  487. $this->_endOfHeaders();
  488. if ($this->_debugHeaders) {
  489. $headers->addTextHeader('X-DebugHash', base64_encode($this->_headerHash));
  490. }
  491. $this->_dkimHeader->setValue($string . " b=" . trim(chunk_split(base64_encode($this->_getEncryptedHash()), 73, " ")));
  492. return $this;
  493. }
  494. /* Private helpers */
  495. protected function _addHeader($header, $is_sig = false)
  496. {
  497. switch ($this->_headerCanon) {
  498. case 'relaxed' :
  499. // Prepare Header and cascade
  500. $exploded = explode(':', $header, 2);
  501. $name = strtolower(trim($exploded[0]));
  502. $value = str_replace("\r\n", "", $exploded[1]);
  503. $value = preg_replace("/[ \t][ \t]+/", " ", $value);
  504. $header = $name . ":" . trim($value) . ($is_sig ? '' : "\r\n");
  505. case 'simple' :
  506. // Nothing to do
  507. }
  508. $this->_addToHeaderHash($header);
  509. }
  510. protected function _endOfHeaders()
  511. {
  512. //$this->_headerHash=hash_final($this->_headerHashHandler, true);
  513. }
  514. protected function _canonicalizeBody($string)
  515. {
  516. $len = strlen($string);
  517. $canon = '';
  518. $method = ($this->_bodyCanon == "relaxed");
  519. for ($i = 0; $i < $len; ++$i) {
  520. if ($this->_bodyCanonIgnoreStart > 0) {
  521. --$this->_bodyCanonIgnoreStart;
  522. continue;
  523. }
  524. switch ($string[$i]) {
  525. case "\r" :
  526. $this->_bodyCanonLastChar = "\r";
  527. break;
  528. case "\n" :
  529. if ($this->_bodyCanonLastChar == "\r") {
  530. if ($method) {
  531. $this->_bodyCanonSpace = false;
  532. }
  533. if ($this->_bodyCanonLine == '') {
  534. ++$this->_bodyCanonEmptyCounter;
  535. } else {
  536. $this->_bodyCanonLine = '';
  537. $canon .= "\r\n";
  538. }
  539. } else {
  540. // Wooops Error
  541. // todo handle it but should never happen
  542. }
  543. break;
  544. case " " :
  545. case "\t" :
  546. if ($method) {
  547. $this->_bodyCanonSpace = true;
  548. break;
  549. }
  550. default :
  551. if ($this->_bodyCanonEmptyCounter > 0) {
  552. $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter);
  553. $this->_bodyCanonEmptyCounter = 0;
  554. }
  555. if ($this->_bodyCanonSpace) {
  556. $this->_bodyCanonLine .= ' ';
  557. $canon .= ' ';
  558. $this->_bodyCanonSpace = false;
  559. }
  560. $this->_bodyCanonLine .= $string[$i];
  561. $canon .= $string[$i];
  562. }
  563. }
  564. $this->_addToBodyHash($canon);
  565. }
  566. protected function _endOfBody()
  567. {
  568. // Add trailing Line return if last line is non empty
  569. if (strlen($this->_bodyCanonLine) > 0) {
  570. $this->_addToBodyHash("\r\n");
  571. }
  572. $this->_bodyHash = hash_final($this->_bodyHashHandler, true);
  573. }
  574. private function _addToBodyHash($string)
  575. {
  576. $len = strlen($string);
  577. if ($len > ($new_len = ($this->_maxLen - $this->_bodyLen))) {
  578. $string = substr($string, 0, $new_len);
  579. $len = $new_len;
  580. }
  581. hash_update($this->_bodyHashHandler, $string);
  582. $this->_bodyLen += $len;
  583. }
  584. private function _addToHeaderHash($header)
  585. {
  586. if ($this->_debugHeaders) {
  587. $this->_debugHeadersData[] = trim($header);
  588. }
  589. $this->_headerCanonData .= $header;
  590. }
  591. /**
  592. * @throws Swift_SwiftException
  593. * @return string
  594. */
  595. private function _getEncryptedHash()
  596. {
  597. $signature = '';
  598. switch ($this->_hashAlgorithm) {
  599. case 'rsa-sha1':
  600. $algorithm = OPENSSL_ALGO_SHA1;
  601. break;
  602. case 'rsa-sha256':
  603. $algorithm = OPENSSL_ALGO_SHA256;
  604. break;
  605. }
  606. $pkeyId=openssl_get_privatekey($this->_privateKey);
  607. if (!$pkeyId) {
  608. throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']');
  609. }
  610. if (openssl_sign($this->_headerCanonData, $signature, $pkeyId, $algorithm)) {
  611. return $signature;
  612. }
  613. throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']');
  614. }
  615. }