[ Index ]

MailPress 7.2

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

title

Body

[close]

/mp-includes/composer/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Signers/ -> SMimeSigner.php (source)

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


Generated: Tue May 19 15:55:14 2020 Cross-referenced by PHPXref 0.7.1