SMimeSigner.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. * MIME Message Signer used to apply S/MIME Signature/Encryption to a message.
  11. *
  12. * @author Romain-Geissler
  13. * @author Sebastiaan Stok <s.stok@rollerscapes.net>
  14. * @author Jan Flora <jf@penneo.com>
  15. */
  16. class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
  17. {
  18. protected $signCertificate;
  19. protected $signPrivateKey;
  20. protected $encryptCert;
  21. protected $signThenEncrypt = true;
  22. protected $signLevel;
  23. protected $encryptLevel;
  24. protected $signOptions;
  25. protected $encryptOptions;
  26. protected $encryptCipher;
  27. protected $extraCerts = null;
  28. protected $wrapFullMessage = false;
  29. /**
  30. * @var Swift_StreamFilters_StringReplacementFilterFactory
  31. */
  32. protected $replacementFactory;
  33. /**
  34. * @var Swift_Mime_SimpleHeaderFactory
  35. */
  36. protected $headerFactory;
  37. /**
  38. * Constructor.
  39. *
  40. * @param string|null $signCertificate
  41. * @param string|null $signPrivateKey
  42. * @param string|null $encryptCertificate
  43. */
  44. public function __construct($signCertificate = null, $signPrivateKey = null, $encryptCertificate = null)
  45. {
  46. if (null !== $signPrivateKey) {
  47. $this->setSignCertificate($signCertificate, $signPrivateKey);
  48. }
  49. if (null !== $encryptCertificate) {
  50. $this->setEncryptCertificate($encryptCertificate);
  51. }
  52. $this->replacementFactory = Swift_DependencyContainer::getInstance()
  53. ->lookup('transport.replacementfactory');
  54. $this->signOptions = PKCS7_DETACHED;
  55. $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC;
  56. }
  57. /**
  58. * Set the certificate location to use for signing.
  59. *
  60. * @see https://secure.php.net/manual/en/openssl.pkcs7.flags.php
  61. *
  62. * @param string $certificate
  63. * @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead
  64. * @param int $signOptions Bitwise operator options for openssl_pkcs7_sign()
  65. * @param string $extraCerts A file containing intermediate certificates needed by the signing certificate
  66. *
  67. * @return $this
  68. */
  69. public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED, $extraCerts = null)
  70. {
  71. $this->signCertificate = 'file://'.str_replace('\\', '/', realpath($certificate));
  72. if (null !== $privateKey) {
  73. if (\is_array($privateKey)) {
  74. $this->signPrivateKey = $privateKey;
  75. $this->signPrivateKey[0] = 'file://'.str_replace('\\', '/', realpath($privateKey[0]));
  76. } else {
  77. $this->signPrivateKey = 'file://'.str_replace('\\', '/', realpath($privateKey));
  78. }
  79. }
  80. $this->signOptions = $signOptions;
  81. $this->extraCerts = $extraCerts ? realpath($extraCerts) : null;
  82. return $this;
  83. }
  84. /**
  85. * Set the certificate location to use for encryption.
  86. *
  87. * @see https://secure.php.net/manual/en/openssl.pkcs7.flags.php
  88. * @see https://secure.php.net/manual/en/openssl.ciphers.php
  89. *
  90. * @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates.
  91. * @param int $cipher
  92. *
  93. * @return $this
  94. */
  95. public function setEncryptCertificate($recipientCerts, $cipher = null)
  96. {
  97. if (\is_array($recipientCerts)) {
  98. $this->encryptCert = [];
  99. foreach ($recipientCerts as $cert) {
  100. $this->encryptCert[] = 'file://'.str_replace('\\', '/', realpath($cert));
  101. }
  102. } else {
  103. $this->encryptCert = 'file://'.str_replace('\\', '/', realpath($recipientCerts));
  104. }
  105. if (null !== $cipher) {
  106. $this->encryptCipher = $cipher;
  107. }
  108. return $this;
  109. }
  110. /**
  111. * @return string
  112. */
  113. public function getSignCertificate()
  114. {
  115. return $this->signCertificate;
  116. }
  117. /**
  118. * @return string
  119. */
  120. public function getSignPrivateKey()
  121. {
  122. return $this->signPrivateKey;
  123. }
  124. /**
  125. * Set perform signing before encryption.
  126. *
  127. * The default is to first sign the message and then encrypt.
  128. * But some older mail clients, namely Microsoft Outlook 2000 will work when the message first encrypted.
  129. * As this goes against the official specs, its recommended to only use 'encryption -> signing' when specifically targeting these 'broken' clients.
  130. *
  131. * @param bool $signThenEncrypt
  132. *
  133. * @return $this
  134. */
  135. public function setSignThenEncrypt($signThenEncrypt = true)
  136. {
  137. $this->signThenEncrypt = $signThenEncrypt;
  138. return $this;
  139. }
  140. /**
  141. * @return bool
  142. */
  143. public function isSignThenEncrypt()
  144. {
  145. return $this->signThenEncrypt;
  146. }
  147. /**
  148. * Resets internal states.
  149. *
  150. * @return $this
  151. */
  152. public function reset()
  153. {
  154. return $this;
  155. }
  156. /**
  157. * Specify whether to wrap the entire MIME message in the S/MIME message.
  158. *
  159. * According to RFC5751 section 3.1:
  160. * In order to protect outer, non-content-related message header fields
  161. * (for instance, the "Subject", "To", "From", and "Cc" fields), the
  162. * sending client MAY wrap a full MIME message in a message/rfc822
  163. * wrapper in order to apply S/MIME security services to these header
  164. * fields. It is up to the receiving client to decide how to present
  165. * this "inner" header along with the unprotected "outer" header.
  166. *
  167. * @param bool $wrap
  168. *
  169. * @return $this
  170. */
  171. public function setWrapFullMessage($wrap)
  172. {
  173. $this->wrapFullMessage = $wrap;
  174. }
  175. /**
  176. * Change the Swift_Message to apply the signing.
  177. *
  178. * @return $this
  179. */
  180. public function signMessage(Swift_Message $message)
  181. {
  182. if (null === $this->signCertificate && null === $this->encryptCert) {
  183. return $this;
  184. }
  185. if ($this->signThenEncrypt) {
  186. $this->smimeSignMessage($message);
  187. $this->smimeEncryptMessage($message);
  188. } else {
  189. $this->smimeEncryptMessage($message);
  190. $this->smimeSignMessage($message);
  191. }
  192. }
  193. /**
  194. * Return the list of header a signer might tamper.
  195. *
  196. * @return array
  197. */
  198. public function getAlteredHeaders()
  199. {
  200. return ['Content-Type', 'Content-Transfer-Encoding', 'Content-Disposition'];
  201. }
  202. /**
  203. * Sign a Swift message.
  204. */
  205. protected function smimeSignMessage(Swift_Message $message)
  206. {
  207. // If we don't have a certificate we can't sign the message
  208. if (null === $this->signCertificate) {
  209. return;
  210. }
  211. // Work on a clone of the original message
  212. $signMessage = clone $message;
  213. $signMessage->clearSigners();
  214. if ($this->wrapFullMessage) {
  215. // The original message essentially becomes the body of the new
  216. // wrapped message
  217. $signMessage = $this->wrapMimeMessage($signMessage);
  218. } else {
  219. // Only keep header needed to parse the body correctly
  220. $this->clearAllHeaders($signMessage);
  221. $this->copyHeaders(
  222. $message,
  223. $signMessage,
  224. [
  225. 'Content-Type',
  226. 'Content-Transfer-Encoding',
  227. 'Content-Disposition',
  228. ]
  229. );
  230. }
  231. // Copy the cloned message into a temporary file stream
  232. $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
  233. $signMessage->toByteStream($messageStream);
  234. $messageStream->commit();
  235. $signedMessageStream = new Swift_ByteStream_TemporaryFileByteStream();
  236. // Sign the message using openssl
  237. if (!openssl_pkcs7_sign(
  238. $messageStream->getPath(),
  239. $signedMessageStream->getPath(),
  240. $this->signCertificate,
  241. $this->signPrivateKey,
  242. [],
  243. $this->signOptions,
  244. $this->extraCerts
  245. )
  246. ) {
  247. throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
  248. }
  249. // Parse the resulting signed message content back into the Swift message
  250. // preserving the original headers
  251. $this->parseSSLOutput($signedMessageStream, $message);
  252. }
  253. /**
  254. * Encrypt a Swift message.
  255. */
  256. protected function smimeEncryptMessage(Swift_Message $message)
  257. {
  258. // If we don't have a certificate we can't encrypt the message
  259. if (null === $this->encryptCert) {
  260. return;
  261. }
  262. // Work on a clone of the original message
  263. $encryptMessage = clone $message;
  264. $encryptMessage->clearSigners();
  265. if ($this->wrapFullMessage) {
  266. // The original message essentially becomes the body of the new
  267. // wrapped message
  268. $encryptMessage = $this->wrapMimeMessage($encryptMessage);
  269. } else {
  270. // Only keep header needed to parse the body correctly
  271. $this->clearAllHeaders($encryptMessage);
  272. $this->copyHeaders(
  273. $message,
  274. $encryptMessage,
  275. [
  276. 'Content-Type',
  277. 'Content-Transfer-Encoding',
  278. 'Content-Disposition',
  279. ]
  280. );
  281. }
  282. // Convert the message content (including headers) to a string
  283. // and place it in a temporary file
  284. $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
  285. $encryptMessage->toByteStream($messageStream);
  286. $messageStream->commit();
  287. $encryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream();
  288. // Encrypt the message
  289. if (!openssl_pkcs7_encrypt(
  290. $messageStream->getPath(),
  291. $encryptedMessageStream->getPath(),
  292. $this->encryptCert,
  293. [],
  294. 0,
  295. $this->encryptCipher
  296. )
  297. ) {
  298. throw new Swift_IoException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
  299. }
  300. // Parse the resulting signed message content back into the Swift message
  301. // preserving the original headers
  302. $this->parseSSLOutput($encryptedMessageStream, $message);
  303. }
  304. /**
  305. * Copy named headers from one Swift message to another.
  306. */
  307. protected function copyHeaders(
  308. Swift_Message $fromMessage,
  309. Swift_Message $toMessage,
  310. array $headers = []
  311. ) {
  312. foreach ($headers as $header) {
  313. $this->copyHeader($fromMessage, $toMessage, $header);
  314. }
  315. }
  316. /**
  317. * Copy a single header from one Swift message to another.
  318. *
  319. * @param string $headerName
  320. */
  321. protected function copyHeader(Swift_Message $fromMessage, Swift_Message $toMessage, $headerName)
  322. {
  323. $header = $fromMessage->getHeaders()->get($headerName);
  324. if (!$header) {
  325. return;
  326. }
  327. $headers = $toMessage->getHeaders();
  328. switch ($header->getFieldType()) {
  329. case Swift_Mime_Header::TYPE_TEXT:
  330. $headers->addTextHeader($header->getFieldName(), $header->getValue());
  331. break;
  332. case Swift_Mime_Header::TYPE_PARAMETERIZED:
  333. $headers->addParameterizedHeader(
  334. $header->getFieldName(),
  335. $header->getValue(),
  336. $header->getParameters()
  337. );
  338. break;
  339. }
  340. }
  341. /**
  342. * Remove all headers from a Swift message.
  343. */
  344. protected function clearAllHeaders(Swift_Message $message)
  345. {
  346. $headers = $message->getHeaders();
  347. foreach ($headers->listAll() as $header) {
  348. $headers->removeAll($header);
  349. }
  350. }
  351. /**
  352. * Wraps a Swift_Message in a message/rfc822 MIME part.
  353. *
  354. * @return Swift_MimePart
  355. */
  356. protected function wrapMimeMessage(Swift_Message $message)
  357. {
  358. // Start by copying the original message into a message stream
  359. $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
  360. $message->toByteStream($messageStream);
  361. $messageStream->commit();
  362. // Create a new MIME part that wraps the original stream
  363. $wrappedMessage = new Swift_MimePart($messageStream, 'message/rfc822');
  364. $wrappedMessage->setEncoder(new Swift_Mime_ContentEncoder_PlainContentEncoder('7bit'));
  365. return $wrappedMessage;
  366. }
  367. protected function parseSSLOutput(Swift_InputByteStream $inputStream, Swift_Message $message)
  368. {
  369. $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
  370. $this->copyFromOpenSSLOutput($inputStream, $messageStream);
  371. $this->streamToMime($messageStream, $message);
  372. }
  373. /**
  374. * Merges an OutputByteStream from OpenSSL to a Swift_Message.
  375. */
  376. protected function streamToMime(Swift_OutputByteStream $fromStream, Swift_Message $message)
  377. {
  378. // Parse the stream into headers and body
  379. list($headers, $messageStream) = $this->parseStream($fromStream);
  380. // Get the original message headers
  381. $messageHeaders = $message->getHeaders();
  382. // Let the stream determine the headers describing the body content,
  383. // since the body of the original message is overwritten by the body
  384. // coming from the stream.
  385. // These are all content-* headers.
  386. // Default transfer encoding is 7bit if not set
  387. $encoding = '';
  388. // Remove all existing transfer encoding headers
  389. $messageHeaders->removeAll('Content-Transfer-Encoding');
  390. // See whether the stream sets the transfer encoding
  391. if (isset($headers['content-transfer-encoding'])) {
  392. $encoding = $headers['content-transfer-encoding'];
  393. }
  394. // We use the null content encoder, since the body is already encoded
  395. // according to the transfer encoding specified in the stream
  396. $message->setEncoder(new Swift_Mime_ContentEncoder_NullContentEncoder($encoding));
  397. // Set the disposition, if present
  398. if (isset($headers['content-disposition'])) {
  399. $messageHeaders->addTextHeader('Content-Disposition', $headers['content-disposition']);
  400. }
  401. // Copy over the body from the stream using the content type dictated
  402. // by the stream content
  403. $message->setChildren([]);
  404. $message->setBody($messageStream, $headers['content-type']);
  405. }
  406. /**
  407. * This message will parse the headers of a MIME email byte stream
  408. * and return an array that contains the headers as an associative
  409. * array and the email body as a string.
  410. *
  411. * @return array
  412. */
  413. protected function parseStream(Swift_OutputByteStream $emailStream)
  414. {
  415. $bufferLength = 78;
  416. $headerData = '';
  417. $headerBodySeparator = "\r\n\r\n";
  418. $emailStream->setReadPointer(0);
  419. // Read out the headers section from the stream to a string
  420. while (false !== ($buffer = $emailStream->read($bufferLength))) {
  421. $headerData .= $buffer;
  422. $headersPosEnd = strpos($headerData, $headerBodySeparator);
  423. // Stop reading if we found the end of the headers
  424. if (false !== $headersPosEnd) {
  425. break;
  426. }
  427. }
  428. // Split the header data into lines
  429. $headerData = trim(substr($headerData, 0, $headersPosEnd));
  430. $headerLines = explode("\r\n", $headerData);
  431. unset($headerData);
  432. $headers = [];
  433. $currentHeaderName = '';
  434. // Transform header lines into an associative array
  435. foreach ($headerLines as $headerLine) {
  436. // Handle headers that span multiple lines
  437. if (false === strpos($headerLine, ':')) {
  438. $headers[$currentHeaderName] .= ' '.trim($headerLine ?? '');
  439. continue;
  440. }
  441. $header = explode(':', $headerLine, 2);
  442. $currentHeaderName = strtolower($header[0] ?? '');
  443. $headers[$currentHeaderName] = trim($header[1] ?? '');
  444. }
  445. // Read the entire email body into a byte stream
  446. $bodyStream = new Swift_ByteStream_TemporaryFileByteStream();
  447. // Skip the header and separator and point to the body
  448. $emailStream->setReadPointer($headersPosEnd + \strlen($headerBodySeparator));
  449. while (false !== ($buffer = $emailStream->read($bufferLength))) {
  450. $bodyStream->write($buffer);
  451. }
  452. $bodyStream->commit();
  453. return [$headers, $bodyStream];
  454. }
  455. protected function copyFromOpenSSLOutput(Swift_OutputByteStream $fromStream, Swift_InputByteStream $toStream)
  456. {
  457. $bufferLength = 4096;
  458. $filteredStream = new Swift_ByteStream_TemporaryFileByteStream();
  459. $filteredStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF');
  460. $filteredStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF');
  461. while (false !== ($buffer = $fromStream->read($bufferLength))) {
  462. $filteredStream->write($buffer);
  463. }
  464. $filteredStream->flushBuffers();
  465. while (false !== ($buffer = $filteredStream->read($bufferLength))) {
  466. $toStream->write($buffer);
  467. }
  468. $toStream->commit();
  469. }
  470. }