-
Notifications
You must be signed in to change notification settings - Fork 127
/
Smime.php
710 lines (636 loc) · 20.6 KB
/
Smime.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
<?php
/**
* Copyright 2002-2017 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (GPL). If you
* did not receive this file, see http://www.horde.org/licenses/gpl.
*
* @category Horde
* @copyright 2002-2017 Horde LLC
* @license http://www.horde.org/licenses/gpl GPL
* @package IMP
*/
/**
* Contains code related to handling S/MIME messages within IMP.
*
* @author Mike Cochrane <mike@graftonhall.co.nz>
* @author Jan Schneider <jan@horde.org>
* @category Horde
* @copyright 2002-2017 Horde LLC
* @license http://www.horde.org/licenses/gpl GPL
* @package IMP
*/
class IMP_Smime
{
/* Name of the S/MIME public key field in addressbook. */
const PUBKEY_FIELD = 'smimePublicKey';
/* Encryption type constants. */
const ENCRYPT = 'smime_encrypt';
const SIGN = 'smime_sign';
const SIGNENC = 'smime_signenc';
/* Which key to use. */
const KEY_PRIMARY = 0;
const KEY_SECONDARY = 1;
const KEY_SECONDARY_OR_PRIMARY = 2;
/**
* S/MIME object.
*
* @var Horde_Crypt_Smime
*/
protected $_smime;
/**
* Return whether PGP support is current enabled in IMP.
*
* @return boolean True if PGP support is enabled.
*/
public static function enabled()
{
global $conf, $prefs;
return (!empty($conf['openssl']['path']) &&
$prefs->getValue('use_smime') &&
Horde_Util::extensionExists('openssl'));
}
/**
* Constructor.
*
* @param Horde_Crypt_Smime $pgp S/MIME object.
*/
public function __construct(Horde_Crypt_Smime $smime)
{
$this->_smime = $smime;
}
/**
* Returns the list of available encryption options for composing.
*
* @return array Keys are encryption type constants, values are gettext
* strings describing the encryption type.
*/
public function encryptList()
{
global $injector, $registry;
$ret = array();
if ($registry->hasMethod('contacts/getField') ||
$injector->getInstance('Horde_Core_Hooks')->hookExists('smime_key', 'imp')) {
$ret += array(
self::ENCRYPT => _("S/MIME Encrypt Message")
);
}
if ($this->getPersonalPrivateKey()) {
$ret += array(
self::SIGN => _("S/MIME Sign Message"),
self::SIGNENC => _("S/MIME Sign/Encrypt Message")
);
}
return $ret;
}
/**
* Adds the personal public key to the prefs.
*
* @param string|array $key The public key to add.
* @param boolean $signkey Is this the secondary key for signing?
*/
public function addPersonalPublicKey($key, $signkey = false)
{
$GLOBALS['prefs']->setValue(
$signkey ? 'smime_public_sign_key' : 'smime_public_key',
is_array($key) ? implode('', $key) : $key
);
}
/**
* Adds the personal private key to the prefs.
*
* @param string|array $key The private key to add.
* @param boolean $signkey Is this the secondary key for signing?
*/
public function addPersonalPrivateKey($key, $signkey = false)
{
$GLOBALS['prefs']->setValue(
$signkey ? 'smime_private_sign_key' : 'smime_private_key',
is_array($key) ? implode('', $key) : $key
);
}
/**
* Adds a list of additional certs to the prefs.
*
* @param string|array $key The additional certifcate(s) to add.
* @param boolean $signkey Is this the secondary key for signing?
*/
public function addAdditionalCert($key, $signkey = false)
{
$GLOBALS['prefs']->setValue(
$signkey ? 'smime_additional_sign_cert' : 'smime_additional_cert',
is_array($key) ? implode('', $key) : $key
);
}
/**
* Returns the personal public key from the prefs.
*
* @param integer $signkey One of the IMP_Sime::KEY_* constants.
*
* @return string The personal S/MIME public key.
*/
public function getPersonalPublicKey($signkey = self::KEY_PRIMARY)
{
global $prefs;
$key = $prefs->getValue(
$signkey ? 'smime_public_sign_key' : 'smime_public_key'
);
if (!$key && $signkey == self::KEY_SECONDARY_OR_PRIMARY) {
$key = $prefs->getValue('smime_public_key');
}
return $key;
}
/**
* Returns the personal private key from the prefs.
*
* @param integer $signkey One of the IMP_Sime::KEY_* constants.
*
* @return string The personal S/MIME private key.
*/
public function getPersonalPrivateKey($signkey = self::KEY_PRIMARY)
{
global $prefs;
$key = $prefs->getValue(
$signkey ? 'smime_private_sign_key' : 'smime_private_key'
);
if (!$key && $signkey == self::KEY_SECONDARY_OR_PRIMARY) {
$key = $prefs->getValue('smime_private_key');
}
return $key;
}
/**
* Returns any additional certificates from the prefs.
*
* @param integer $signkey One of the IMP_Sime::KEY_* constants.
*
* @return string Additional signing certs for inclusion.
*/
public function getAdditionalCert($signkey = self::KEY_PRIMARY)
{
global $prefs;
$key = $prefs->getValue(
$signkey ? 'smime_additional_sign_cert' : 'smime_additional_cert'
);
if (!$key && $signkey == self::KEY_SECONDARY_OR_PRIMARY) {
$key = $prefs->getValue('smime_additional_cert');
}
return $key;
}
/**
* Deletes the specified personal keys from the prefs.
*
* @param boolean $signkey Return the secondary key for signing?
*/
public function deletePersonalKeys($signkey = false)
{
global $prefs;
// We always delete the secondary keys because we cannot have them
// without primary keys.
$prefs->setValue('smime_public_sign_key', '');
$prefs->setValue('smime_private_sign_key', '');
$prefs->setValue('smime_additional_sign_cert', '');
if (!$signkey) {
$prefs->setValue('smime_public_key', '');
$prefs->setValue('smime_private_key', '');
$prefs->setValue('smime_additional_cert', '');
}
$this->unsetPassphrase($signkey);
}
/**
* Adds a public key to an address book.
*
* @param string $cert A public certificate to add.
*
* @throws Horde_Exception
*/
public function addPublicKey($cert)
{
global $prefs, $registry;
list($name, $email) = $this->publicKeyInfo($cert);
$registry->call(
'contacts/addField',
array(
$email,
$name,
self::PUBKEY_FIELD,
$cert,
$prefs->getValue('add_source')
)
);
}
/**
* Returns information about a public certificate.
*
* @param string $cert The public certificate.
*
* @return array Two element array: the name and e-mail for the cert.
* @throws Horde_Crypt_Exception
*/
public function publicKeyInfo($cert)
{
/* Make sure the certificate is valid. */
$key_info = openssl_x509_parse($cert);
if (!is_array($key_info) || !isset($key_info['subject'])) {
throw new Horde_Crypt_Exception(_("Not a valid public key."));
}
/* Add key to the user's address book. */
$email = $this->_smime->getEmailFromKey($cert);
if (is_null($email)) {
throw new Horde_Crypt_Exception(
_("No email information located in the public key.")
);
}
/* Get the name corresponding to this key. */
if (isset($key_info['subject']['CN'])) {
$name = $key_info['subject']['CN'];
} elseif (isset($key_info['subject']['OU'])) {
$name = $key_info['subject']['OU'];
} else {
$name = $email;
}
return array($name, $email);
}
/**
* Returns the params needed to encrypt a message being sent to the
* specified email address(es).
*
* @param Horde_Mail_Rfc822_List $addr The recipient addresses.
*
* @return array The list of parameters needed by encrypt().
* @throws Horde_Crypt_Exception
*/
protected function _encryptParameters(Horde_Mail_Rfc822_List $addr)
{
return array(
'pubkey' => array_map(
array($this, 'getPublicKey'),
$addr->bare_addresses
),
'type' => 'message'
);
}
/**
* Retrieves a public key by e-mail.
*
* The key will be retrieved from a user's address book(s).
*
* @param string $address The e-mail address to search for.
*
* @return string The S/MIME public key requested.
* @throws Horde_Exception
*/
public function getPublicKey($address)
{
global $injector, $registry;
try {
$key = $injector->getInstance('Horde_Core_Hooks')->callHook(
'smime_key',
'imp',
array($address)
);
if ($key) {
return $key;
}
} catch (Horde_Exception_HookNotSet $e) {}
$contacts = $injector->getInstance('IMP_Contacts');
try {
$key = $registry->call(
'contacts/getField',
array(
$address,
self::PUBKEY_FIELD,
$contacts->sources,
true,
true
)
);
} catch (Horde_Exception $e) {
/* See if the address points to the user's public key. */
$personal_pubkey = $this->getPersonalPublicKey();
if (!empty($personal_pubkey) &&
$injector->getInstance('IMP_Identity')->hasAddress($address)) {
return $personal_pubkey;
}
throw $e;
}
/* If more than one public key is returned, just return the first in
* the array. There is no way of knowing which is the "preferred" key,
* if the keys are different. */
return is_array($key) ? reset($key) : $key;
}
/**
* Retrieves all public keys from a user's address book(s).
*
* @return array All S/MIME public keys available.
* @throws Horde_Crypt_Exception
*/
public function listPublicKeys()
{
global $injector, $registry;
$sources = $injector->getInstance('IMP_Contacts')->sources;
if (empty($sources)) {
return array();
}
return $registry->call(
'contacts/getAllAttributeValues',
array(self::PUBKEY_FIELD, $sources)
);
}
/**
* Deletes a public key from a user's address book(s) by e-mail.
*
* @param string $email The e-mail address to delete.
*
* @throws Horde_Crypt_Exception
*/
public function deletePublicKey($email)
{
global $injector, $registry;
$registry->call(
'contacts/deleteField',
array(
$email,
self::PUBKEY_FIELD,
$injector->getInstance('IMP_Contacts')->sources
)
);
}
/**
* Returns the parameters needed for signing a message.
*
* @return array The list of parameters needed by encrypt().
*/
protected function _signParameters()
{
$pubkey = $this->getPersonalPublicKey(true);
$additional = array();
if ($pubkey) {
$additional[] = $this->getPersonalPublicKey();
$secondary = true;
} else {
$pubkey = $this->getPersonalPublicKey();
$secondary = false;
}
$additional[] = $this->getAdditionalCert($secondary);
if ($secondary) {
$additional[] = $this->getAdditionalCert();
}
return array(
'type' => 'signature',
'pubkey' => $pubkey,
'privkey' => $this->getPersonalPrivateKey($secondary),
'passphrase' => $this->getPassphrase($secondary),
'sigtype' => 'detach',
'certs' => implode("\n", $additional),
);
}
/**
* Verifies a signed message with a given public key.
*
* @param string $text The text to verify.
*
* @return stdClass See Horde_Crypt_Smime::verify().
* @throws Horde_Crypt_Exception
*/
public function verifySignature($text)
{
global $conf;
return $this->_smime->verify(
$text,
empty($conf['openssl']['cafile'])
? array()
: $conf['openssl']['cafile']
);
}
/**
* Decrypts a message with user's public/private keypair.
*
* @param string $text The text to decrypt.
*
* @return string See Horde_Crypt_Smime::decrypt().
* @throws Horde_Crypt_Exception
*/
public function decryptMessage($text)
{
return $this->_smime->decrypt($text, array(
'type' => 'message',
'pubkey' => $this->getPersonalPublicKey(),
'privkey' => $this->getPersonalPrivateKey(),
'passphrase' => $this->getPassphrase()
));
}
/**
* Returns the user's passphrase from the session cache.
*
* @param integer $signkey One of the IMP_Sime::KEY_* constants.
*
* @return mixed The passphrase, if set. Returns false if the passphrase
* has not been loaded yet. Returns null if no passphrase
* is needed.
*/
public function getPassphrase($signkey = self::KEY_PRIMARY)
{
global $prefs, $session;
if ($signkey == self::KEY_SECONDARY_OR_PRIMARY) {
if ($private_key = $this->getPersonalPrivateKey(self::KEY_SECONDARY)) {
$signkey = self::KEY_SECONDARY;
} else {
$private_key = $this->getPersonalPrivateKey();
$signkey = self::KEY_PRIMARY;
}
} else {
$private_key = $this->getPersonalPrivateKey($signkey);
}
if (empty($private_key)) {
return false;
}
$suffix = $signkey ? '_sign' : '';
if ($session->exists('imp', 'smime_passphrase' . $suffix)) {
return $session->get('imp', 'smime_passphrase' . $suffix);
}
if (!$session->exists('imp', 'smime_null_passphrase' . $suffix)) {
$session->set(
'imp',
'smime_null_passphrase' . $suffix,
$this->_smime->verifyPassphrase($private_key, null)
? null
: false
);
}
return $session->get('imp', 'smime_null_passphrase' . $suffix);
}
/**
* Stores the user's passphrase in the session cache.
*
* @param string $passphrase The user's passphrase.
* @param integer $signkey One of the IMP_Sime::KEY_* constants.
*
* @return boolean Returns true if correct passphrase, false if incorrect.
*/
public function storePassphrase($passphrase, $signkey = self::KEY_PRIMARY)
{
global $session;
if ($signkey == self::KEY_SECONDARY_OR_PRIMARY) {
if ($key = $this->getPersonalPrivateKey(self::KEY_SECONDARY)) {
$signkey = self::KEY_SECONDARY;
} else {
$key = $this->getPersonalPrivateKey();
$signkey = self::KEY_PRIMARY;
}
} else {
$key = $this->getPersonalPrivateKey($signkey);
}
if ($this->_smime->verifyPassphrase($key, $passphrase) !== false) {
$session->set(
'imp',
$signkey ? 'smime_passphrase_sign' : 'smime_passphrase',
$passphrase,
$session::ENCRYPT
);
return true;
}
return false;
}
/**
* Clears the passphrase from the session cache.
*
* @param boolean $signkey Is this the secondary key for signing?
*/
public function unsetPassphrase($signkey = false)
{
global $session;
if ($signkey) {
$session->remove('imp', 'smime_null_passphrase_sign');
$session->remove('imp', 'smime_passphrase_sign');
} else {
$session->remove('imp', 'smime_null_passphrase');
$session->remove('imp', 'smime_passphrase');
}
}
/**
* Encrypts a MIME part using S/MIME using IMP defaults.
*
* @param Horde_Mime_Part $mime_part The object to encrypt.
* @param Horde_Mail_Rfc822_List $recip The recipient address(es).
*
* @return Horde_Mime_Part See Horde_Crypt_Smime::encryptMIMEPart().
* @throws Horde_Crypt_Exception
*/
public function encryptMimePart($mime_part,
Horde_Mail_Rfc822_List $recip)
{
return $this->_smime->encryptMIMEPart(
$mime_part,
$this->_encryptParameters($recip)
);
}
/**
* Signs a MIME part using S/MIME using IMP defaults.
*
* @param MIME_Part $mime_part The MIME_Part object to sign.
*
* @return Horde_Mime_Part See Horde_Crypt_Smime::signMIMEPart().
* @throws Horde_Crypt_Exception
*/
public function signMimePart($mime_part)
{
return $this->_smime->signMIMEPart(
$mime_part,
$this->_signParameters()
);
}
/**
* Signs and encrypts a MIME part using S/MIME using IMP defaults.
*
* @param Horde_Mime_Part $mime_part The object to sign and encrypt.
* @param Horde_Mail_Rfc822_List $recip The recipient address(es).
*
* @return Horde_Mime_Part See
* Horde_Crypt_Smime::signAndencryptMIMEPart().
* @throws Horde_Crypt_Exception
*/
public function signAndEncryptMimePart($mime_part,
Horde_Mail_Rfc822_List $recip)
{
return $this->_smime->signAndEncryptMIMEPart(
$mime_part,
$this->_signParameters(),
$this->_encryptParameters($recip)
);
}
/**
* Stores the public/private/additional certificates in the preferences
* from a given PKCS 12 file.
*
* @param string $pkcs12 The PKCS 12 data.
* @param string $password The password of the PKCS 12 file.
* @param string $pkpass The password to use to encrypt the private key.
* @param boolean $signkey Is this the secondary key for signing?
*
* @throws Horde_Crypt_Exception
*/
public function addFromPKCS12(
$pkcs12, $password, $pkpass = null, $signkey = false
)
{
global $conf;
$sslpath = empty($conf['openssl']['path'])
? null
: $conf['openssl']['path'];
$params = array('sslpath' => $sslpath, 'password' => $password);
if (!empty($pkpass)) {
$params['newpassword'] = $pkpass;
}
$result = $this->_smime->parsePKCS12Data($pkcs12, $params);
$this->addPersonalPrivateKey($result->private, $signkey);
$this->addPersonalPublicKey($result->public, $signkey);
$this->addAdditionalCert($result->certs, $signkey);
}
/**
* Extracts the contents from signed S/MIME data.
*
* @param string $data The signed S/MIME data.
*
* @return string The contents embedded in the signed data.
* @throws Horde_Crypt_Exception
*/
public function extractSignedContents($data)
{
global $conf;
$sslpath = empty($conf['openssl']['path'])
? null
: $conf['openssl']['path'];
return $this->_smime->extractSignedContents($data, $sslpath);
}
/**
* Checks for the presence of the OpenSSL extension to PHP.
*
* @throws Horde_Crypt_Exception
*/
public function checkForOpenSsl()
{
$this->_smime->checkForOpenSSL();
}
/**
* Converts a PEM format certificate to readable HTML version.
*
* @param string $cert PEM format certificate.
*
* @return string HTML detailing the certificate.
*/
public function certToHTML($cert)
{
return $this->_smime->certToHTML($cert);
}
/**
* Extracts the contents of a PEM format certificate to an array.
*
* @param string $cert PEM format certificate.
*
* @return array All extractable information about the certificate.
*/
public function parseCert($cert)
{
return $this->_smime->parseCert($cert);
}
}