Completed
Push — 5.x ( f5621b...536c78 )
by Lars
07:05
created

Swift_Signers_SMimeSigner::signMessage()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.0123

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 2
nop 1
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
ccs 8
cts 9
cp 0.8889
crap 3.0123
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
 *
15
 * @author Romain-Geissler
16
 * @author Sebastiaan Stok <[email protected]>
17
 */
18
class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
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
31
    /**
32
     * @var Swift_StreamFilters_StringReplacementFilterFactory
33
     */
34
    protected $replacementFactory;
35
36
    /**
37
     * @var Swift_Mime_HeaderFactory
38
     */
39
    protected $headerFactory;
40
41
    /**
42
     * Constructor.
43
     *
44
     * @param string|null $signCertificate
45
     * @param string|null $signPrivateKey
46
     * @param string|null $encryptCertificate
47
     */
48 8
    public function __construct($signCertificate = null, $signPrivateKey = null, $encryptCertificate = null)
49
    {
50 8
        if (null !== $signPrivateKey) {
51
            $this->setSignCertificate($signCertificate, $signPrivateKey);
52
        }
53
54 8
        if (null !== $encryptCertificate) {
55
            $this->setEncryptCertificate($encryptCertificate);
56
        }
57
58 8
        $this->replacementFactory = Swift_DependencyContainer::getInstance()
59 8
            ->lookup('transport.replacementfactory');
60
61 8
        $this->signOptions = PKCS7_DETACHED;
62
63
        // Supported since php5.4
64 8
        if (defined('OPENSSL_CIPHER_AES_128_CBC')) {
65
            $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC;
66
        } else {
67 8
            $this->encryptCipher = OPENSSL_CIPHER_RC2_128;
68
        }
69 8
    }
70
71
    /**
72
     * Returns an new Swift_Signers_SMimeSigner instance.
73
     *
74
     * @param string $certificate
75
     * @param string $privateKey
76
     *
77
     * @return self
78
     */
79
    public static function newInstance($certificate = null, $privateKey = null)
80
    {
81
        return new self($certificate, $privateKey);
82
    }
83
84
    /**
85
     * Set the certificate location to use for signing.
86
     *
87
     * @see http://www.php.net/manual/en/openssl.pkcs7.flags.php
88
     *
89
     * @param string       $certificate
90
     * @param string|array $privateKey  If the key needs an passphrase use array('file-location', 'passphrase') instead
91
     * @param int          $signOptions Bitwise operator options for openssl_pkcs7_sign()
92
     * @param string       $extraCerts  A file containing intermediate certificates needed by the signing certificate
93
     *
94
     * @return $this
95
     */
96 6
    public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED, $extraCerts = null)
97
    {
98 6
        $this->signCertificate = 'file://' . str_replace('\\', '/', realpath($certificate));
99
100 6 View Code Duplication
        if (null !== $privateKey) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101 6
            if (is_array($privateKey)) {
102
                $this->signPrivateKey = $privateKey;
103
                $this->signPrivateKey[0] = 'file://' . str_replace('\\', '/', realpath($privateKey[0]));
104
            } else {
105 6
                $this->signPrivateKey = 'file://' . str_replace('\\', '/', realpath($privateKey));
106
            }
107 6
        }
108
109 6
        $this->signOptions = $signOptions;
110 6
        if (null !== $extraCerts) {
111 1
            $this->extraCerts = str_replace('\\', '/', realpath($extraCerts));
112 1
        }
113
114 6
        return $this;
115
    }
116
117
    /**
118
     * Set the certificate location to use for encryption.
119
     *
120
     * @see http://www.php.net/manual/en/openssl.pkcs7.flags.php
121
     * @see http://nl3.php.net/manual/en/openssl.ciphers.php
122
     *
123
     * @param string $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates.
124
     * @param int          $cipher
125
     *
126
     * @return $this
127
     */
128 4
    public function setEncryptCertificate($recipientCerts, $cipher = null)
129
    {
130 4 View Code Duplication
        if (is_array($recipientCerts)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131 1
            $this->encryptCert = array();
132
133 1
            foreach ($recipientCerts as $cert) {
134 1
                $this->encryptCert[] = 'file://' . str_replace('\\', '/', realpath($cert));
135 1
            }
136 1
        } else {
137 3
            $this->encryptCert = 'file://' . str_replace('\\', '/', realpath($recipientCerts));
138
        }
139
140 4
        if (null !== $cipher) {
141
            $this->encryptCipher = $cipher;
142
        }
143
144 4
        return $this;
145
    }
146
147
    /**
148
     * @return string
149
     */
150
    public function getSignCertificate()
151
    {
152
        return $this->signCertificate;
153
    }
154
155
    /**
156
     * @return string
157
     */
158
    public function getSignPrivateKey()
159
    {
160
        return $this->signPrivateKey;
161
    }
162
163
    /**
164
     * Set perform signing before encryption.
165
     *
166
     * The default is to first sign the message and then encrypt.
167
     * But some older mail clients, namely Microsoft Outlook 2000 will work when the message first encrypted.
168
     * As this goes against the official specs, its recommended to only use 'encryption -> signing' when specifically targeting these 'broken' clients.
169
     *
170
     * @param bool $signThenEncrypt
171
     *
172
     * @return $this
173
     */
174 1
    public function setSignThenEncrypt($signThenEncrypt = true)
175
    {
176 1
        $this->signThenEncrypt = $signThenEncrypt;
177
178 1
        return $this;
179
    }
180
181
    /**
182
     * @return bool
183
     */
184
    public function isSignThenEncrypt()
185
    {
186
        return $this->signThenEncrypt;
187
    }
188
189
    /**
190
     * Resets internal states.
191
     *
192
     * @return $this
193
     */
194
    public function reset()
195
    {
196
        return $this;
197
    }
198
199
    /**
200
     * Change the Swift_Message to apply the signing.
201
     *
202
     * @param Swift_Message $message
203
     *
204
     * @return $this
205
     */
206 8
    public function signMessage(Swift_Message $message)
207
    {
208 8
        if (null === $this->signCertificate && null === $this->encryptCert) {
209
            return $this;
210
        }
211
212
        // Store the message using ByteStream to a file{1}
213
        // Remove all Children
214
        // Sign file{1}, parse the new MIME headers and set them on the primary MimeEntity
215
        // Set the singed-body as the new body (without boundary)
216
217 8
        $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
218 8
        $this->toSMimeByteStream($messageStream, $message);
219 8
        $message->setEncoder(Swift_DependencyContainer::getInstance()->lookup('mime.rawcontentencoder'));
220
221 8
        $message->setChildren(array());
222 8
        $this->streamToMime($messageStream, $message);
223 8
    }
224
225
    /**
226
     * Return the list of header a signer might tamper.
227
     *
228
     * @return string[]
229
     */
230 8
    public function getAlteredHeaders()
231
    {
232 8
        return array('Content-Type', 'Content-Transfer-Encoding', 'Content-Disposition');
233
    }
234
235
    /**
236
     * @param Swift_InputByteStream $inputStream
237
     */
238 8
    protected function toSMimeByteStream(Swift_InputByteStream $inputStream, Swift_Message $message)
239
    {
240 8
        $mimeEntity = $this->createMessage($message);
241 8
        $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
242
243 8
        $mimeEntity->toByteStream($messageStream);
244 8
        $messageStream->commit();
245
246 8
        if (null !== $this->signCertificate && null !== $this->encryptCert) {
247 2
            $temporaryStream = new Swift_ByteStream_TemporaryFileByteStream();
248
249 2
            if ($this->signThenEncrypt) {
250 1
                $this->messageStreamToSignedByteStream($messageStream, $temporaryStream);
251 1
                $this->messageStreamToEncryptedByteStream($temporaryStream, $inputStream);
252 1
            } else {
253 1
                $this->messageStreamToEncryptedByteStream($messageStream, $temporaryStream);
254 1
                $this->messageStreamToSignedByteStream($temporaryStream, $inputStream);
255
            }
256 8
        } elseif ($this->signCertificate !== null) {
257 4
            $this->messageStreamToSignedByteStream($messageStream, $inputStream);
258 4
        } else {
259 2
            $this->messageStreamToEncryptedByteStream($messageStream, $inputStream);
260
        }
261 8
    }
262
263
    /**
264
     * @param Swift_Message $message
265
     *
266
     * @return Swift_Message
267
     */
268 8
    protected function createMessage(Swift_Message $message)
269
    {
270 8
        $mimeEntity = new Swift_Message('', $message->getBody(), $message->getContentType(), $message->getCharset());
0 ignored issues
show
Security Bug introduced by
It seems like $message->getCharset() targeting Swift_Mime_MimePart::getCharset() can also be of type false; however, Swift_Message::__construct() does only seem to accept string|null, did you maybe forget to handle an error condition?
Loading history...
Bug introduced by
It seems like $message->getContentType() targeting Swift_Mime_SimpleMimeEntity::getContentType() can also be of type array<integer,string>; however, Swift_Message::__construct() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
271 8
        $mimeEntity->setChildren($message->getChildren());
272
273 8
        $messageHeaders = $mimeEntity->getHeaders();
274 8
        $messageHeaders->remove('Message-ID');
275 8
        $messageHeaders->remove('Date');
276 8
        $messageHeaders->remove('Subject');
277 8
        $messageHeaders->remove('MIME-Version');
278 8
        $messageHeaders->remove('To');
279 8
        $messageHeaders->remove('From');
280
281 8
        return $mimeEntity;
282
    }
283
284
    /**
285
     * @param Swift_FileStream      $outputStream
286
     * @param Swift_InputByteStream $inputStream
287
     *
288
     * @throws Swift_IoException
289
     */
290 6
    protected function messageStreamToSignedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $inputStream)
291
    {
292 6
        $signedMessageStream = new Swift_ByteStream_TemporaryFileByteStream();
293
294 6
        $args = array($outputStream->getPath(), $signedMessageStream->getPath(), $this->signCertificate, $this->signPrivateKey, array(), $this->signOptions);
295 6
        if (null !== $this->extraCerts) {
296 1
            $args[] = $this->extraCerts;
297 1
        }
298
299 6
        if (!call_user_func_array('openssl_pkcs7_sign', $args)) {
300
            throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
301
        }
302
303 6
        $this->copyFromOpenSSLOutput($signedMessageStream, $inputStream);
304 6
    }
305
306
    /**
307
     * @param Swift_FileStream      $outputStream
308
     * @param Swift_InputByteStream $is
309
     *
310
     * @throws Swift_IoException
311
     */
312 4
    protected function messageStreamToEncryptedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $is)
313
    {
314 4
        $encryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream();
315
316 4
        if (!openssl_pkcs7_encrypt($outputStream->getPath(), $encryptedMessageStream->getPath(), $this->encryptCert, array(), 0, $this->encryptCipher)) {
317
            throw new Swift_IoException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
318
        }
319
320 4
        $this->copyFromOpenSSLOutput($encryptedMessageStream, $is);
321 4
    }
322
323
    /**
324
     * @param Swift_OutputByteStream $fromStream
325
     * @param Swift_InputByteStream  $toStream
326
     */
327 8
    protected function copyFromOpenSSLOutput(Swift_OutputByteStream $fromStream, Swift_InputByteStream $toStream)
328
    {
329 8
        $bufferLength = 4096;
330 8
        $filteredStream = new Swift_ByteStream_TemporaryFileByteStream();
331 8
        $filteredStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF');
332 8
        $filteredStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF');
333
334 8
        while (false !== ($buffer = $fromStream->read($bufferLength))) {
335 8
            $filteredStream->write($buffer);
0 ignored issues
show
Bug introduced by
It seems like $buffer defined by $fromStream->read($bufferLength) on line 334 can also be of type boolean; however, Swift_ByteStream_Abstrac...bleInputStream::write() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
336 8
        }
337
338 8
        $filteredStream->flushBuffers();
339
340 8
        while (false !== ($buffer = $filteredStream->read($bufferLength))) {
341 8
            $toStream->write($buffer);
342 8
        }
343
344 8
        $toStream->commit();
345 8
    }
346
347
    /**
348
     * Merges an OutputByteStream to Swift_Message.
349
     *
350
     * @param Swift_OutputByteStream $fromStream
351
     * @param Swift_Message          $message
352
     *
353
     * @throws Swift_DependencyException
354
     * @throws Swift_SwiftException
355
     */
356 8
    protected function streamToMime(Swift_OutputByteStream $fromStream, Swift_Message $message)
357
    {
358 8
        $bufferLength = 78;
359 8
        $headerData = '';
360
361 8
        $fromStream->setReadPointer(0);
362
363 8
        while (($buffer = $fromStream->read($bufferLength)) !== false) {
364 8
            $headerData .= $buffer;
365
366 8
            if (false !== strpos($buffer, "\r\n\r\n")) {
367 8
                break;
368
            }
369 8
        }
370
371 8
        $headersPosEnd = strpos($headerData, "\r\n\r\n");
372 8
        $headerData = trim($headerData);
373 8
        $headerData = substr($headerData, 0, $headersPosEnd);
374 8
        $headerLines = explode("\r\n", $headerData);
375 8
        unset($headerData);
376
377 8
        $headers = array();
378 8
        $currentHeaderName = '';
379
380 8
        foreach ($headerLines as $headerLine) {
381
            // Line separated
382 8
            if (ctype_space($headerLines[0]) || false === strpos($headerLine, ':')) {
383
                $headers[$currentHeaderName] .= ' ' . trim($headerLine);
384
                continue;
385
            }
386
387 8
            $header = explode(':', $headerLine, 2);
388 8
            $currentHeaderName = Swift::strtolowerWithStaticCache($header[0]);
389 8
            $headers[$currentHeaderName] = trim($header[1]);
390 8
        }
391
392 8
        $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
393 8
        $messageStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF');
394 8
        $messageStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF');
395
396 8
        $messageHeaders = $message->getHeaders();
397
398
        // No need to check for 'application/pkcs7-mime', as this is always base64
399 8
        if ('multipart/signed;' === substr($headers['content-type'], 0, 17)) {
400 4
            if (!preg_match('/boundary=("[^"]+"|(?:[^\s]+|$))/is', $headers['content-type'], $contentTypeData)) {
401
                throw new Swift_SwiftException('Failed to find Boundary parameter');
402
            }
403
404 4
            $boundary = trim($contentTypeData['1'], '"');
405
406
            // Skip the header and CRLF CRLF
407 4
            $fromStream->setReadPointer($headersPosEnd + 4);
408
409 4
            while (false !== ($buffer = $fromStream->read($bufferLength))) {
410 4
                $messageStream->write($buffer);
0 ignored issues
show
Bug introduced by
It seems like $buffer defined by $fromStream->read($bufferLength) on line 409 can also be of type boolean; however, Swift_ByteStream_Abstrac...bleInputStream::write() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
411 4
            }
412
413 4
            $messageStream->commit();
414
415 4
            $messageHeaders->remove('Content-Transfer-Encoding');
416 4
            $message->setContentType($headers['content-type']);
417 4
            $message->setBoundary($boundary);
418 4
            $message->setBody($messageStream);
419 4
        } else {
420 4
            $fromStream->setReadPointer($headersPosEnd + 4);
421
422 4
            if (null === $this->headerFactory) {
423 4
                $this->headerFactory = Swift_DependencyContainer::getInstance()->lookup('mime.headerfactory');
424 4
            }
425
426 4
            $message->setContentType($headers['content-type']);
427 4
            $messageHeaders->set($this->headerFactory->createTextHeader('Content-Transfer-Encoding', $headers['content-transfer-encoding']));
428 4
            $messageHeaders->set($this->headerFactory->createTextHeader('Content-Disposition', $headers['content-disposition']));
429
430 4
            while (false !== ($buffer = $fromStream->read($bufferLength))) {
431 4
                $messageStream->write($buffer);
0 ignored issues
show
Bug introduced by
It seems like $buffer defined by $fromStream->read($bufferLength) on line 430 can also be of type boolean; however, Swift_ByteStream_Abstrac...bleInputStream::write() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
432 4
            }
433
434 4
            $messageStream->commit();
435 4
            $message->setBody($messageStream);
436
        }
437 8
    }
438
}
439