-
Notifications
You must be signed in to change notification settings - Fork 2
/
function.php
1856 lines (1585 loc) · 64.9 KB
/
function.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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set('error_log', 'syslog');
use Pdp\Rules;
use Pdp\Domain;
function username() {
if (isset ($_SERVER['REMOTE_USER'])) $user = $_SERVER['REMOTE_USER'];
else if (isset ($_SERVER['USER'])) $user = $_SERVER['USER'];
else if ( isset($_SERVER['PHP_AUTH_USER']) ) $user = $_SERVER['PHP_AUTH_USER'];
else {
syslog(LOG_ALERT, "unknown: Alert: No user given by connection from {$_SERVER['REMOTE_ADDR']}. Exiting");
exit(0);
}
return $user;
}
$username = username();
function addErrorReturn (&$err, $add, $fileA, $fileB) {
/* Only used in delayed delete to shortcut a sane return */
$err .= "\n".$add;
unlink($fileA);
unlink($fileB);
return -4;
}
function printTableHeader($title,$content,$footer=FALSE,$fcontent) {
print <<<END
<caption>$title</caption>
<thead>
<tr>
END;
$cols = count($content);
for ($i=0; $i<$cols; $i++)
print '<th>'.$content[$i].'</th>';
print '</tr></thead>';
if ($footer) {
print '<tfoot><tr>';
print "<th colspan=\"$cols\">".$fcontent.'</th>';
print '</tr></tfoot>';
}
return TRUE;
}
function buildSel ($dkconf, $selclass, $dom) {
/* Build a selector in current time slot */
if ( $dkconf['selector']['hash'] )
return $selclass . $dkconf['selector']['separator'] .
hash( $dkconf['selector']['hash'], hash( 'sha256', date( $dkconf['scheme']['period'] ). $dom ) );
else
return $selclass . $dkconf['selector']['separator'] . date( $dkconf['scheme']['period'] ) .
strtr( $dom, '.', "\0" );
}
/* LDAP class */
/* Low level LDAP Class */
function conn_ldap($host,$port,$user,$pwd) {
$username = username();
$ldapconn = ldap_connect($host, $port);
ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, 5);
if ($ldapconn) {
// binding to ldap server
syslog(LOG_INFO, "$username: Info: LDAP: Successfully connected to $host:$port");
$ldapbind = ldap_bind($ldapconn, $user, $pwd);
// verify binding
if ($ldapbind) {
syslog(LOG_INFO, "$username: Info: LDAP: Successfully BIND as <".$user.'>.');
return $ldapconn;
}
else {
$err = 'LDAP: Error trying to bind as <'.$user.'>: '.ldap_error($ldapconn);
syslog(LOG_ERR, "$username: Error: $err.");
ldap_unbind($ldapconn);
return FALSE;
}
}
else {
$err = 'LDAP: Could not connect to LDAP server '.$host.':'.$port;
syslog(LOG_ERR, $username.": Error: $err.");
return FALSE;
}
}
function getPrivSel ($ds, $basedn, $dom, $selclass, $selAttr, &$err) {
/* Read selector value from KeyTable. Return selector value or FALSE otherwise */
$username = username();
$selAttr = strtolower($selAttr);
$dn = "ou=KeyTable,ou=$dom,ou=$selclass".','.$basedn;
if ( $sr = @ldap_read($ds, $dn, "$selAttr=*", array("$selAttr")) ) {
$info = ldap_get_entries($ds, $sr);
ldap_free_result($sr);
switch ( $info['count'] > 1 ? '2':$info['count'] ) {
case 0:
$err = "LDAP: <$selclass> selector for <$dom> does not exist.";
syslog(LOG_ERR, "$username: Error: $err");
return FALSE;
case 1:
$err = "LDAP: <$selclass> selector for <$dom> is <{$info[0]["$selAttr"][0]}>";
syslog(LOG_INFO,"$username: Info: $err");
return $info[0]["$selAttr"][0];
case 2:
$err = "LDAP: <$selclass> selector for <$dom> has {$info['count']} values! Setup broken, you must fix it.";
syslog(LOG_ERR, "$username: Error: $err");
return FALSE;
}
}
$err = "LDAP: <$selclass> selector for <$dom> not found. Reason: ".ldap_error($ds);
syslog(LOG_WARNING, "$username: Warn: $err");
return FALSE;
}
function ldap_pardom_get_privSel ($ds, $basedn, &$dom, $selclass, $selAttr, $strictmode, &$err) {
/* Find selector on dom or parent dom of at least second level */
/* Return the selector and the associated domain, or FALSE and tld */
// $selector = <selclass><sep><hashtag>
if (! ( $occurrence = strstr($dom, '.')) )
return FALSE;
if ( ($sel = getPrivSel ($ds, $basedn, $dom, $selclass, $selAttr, $error)) !== FALSE )
return $sel;
else
$err .= $error."\n";
if ( $dom == orgDom($dom) ) return FALSE;
$dom = substr($occurrence,1);
if ($strictmode) return FALSE;
return ldap_pardom_get_privSel ($ds, $basedn, $dom, $selclass, $selAttr, $strictmode, $err);
}
function is_tree ($ds, $dn, $attrcheck, $value='*') {
$attrcheck = strtolower($attrcheck);
// I append '@' because dn could not exist and generate a warning
if ( $sr = @ldap_read($ds, $dn, "$attrcheck=$value", array("$attrcheck")) ) {
$info = ldap_get_entries($ds, $sr);
ldap_free_result($sr);
if ( ($value != '*') and ($info['count'] > 0) )
if ( $info[0]["$attrcheck"][0] == $value )
return TRUE;
else return FALSE;
else if ( $info['count'] > 0 )
return TRUE;
}
return FALSE;
}
function del_ldap($ds,$dn,&$err,$recursive=false) {
$username = username();
if ($recursive)
$errmore = 'and all its childs';
else $errmore = NULL;
$err = "LDAP: <$dn> $errmore deleted successfully";
if (!ldap_delete_r($ds, $dn, $recursive)) {
$err = "LDAP: Can't delete <$dn> $errmore: Reason: ".ldap_error($ds);
syslog(LOG_ERR, $username.": Error: $err.");
return FALSE;
}
syslog(LOG_INFO, $username.": Info: $err.");
return TRUE;
}
function ldap_delete_r($ds,$dn,$recursive=false){
if($recursive == false){
return(ldap_delete($ds,$dn));
}else{
//searching for sub entries
// See at search for CoS entries in RH Directory Server manual.
$sr=ldap_list($ds,$dn,"(|(objectclass=*)(objectclass=ldapSubEntry))",array(""));
$info = ldap_get_entries($ds, $sr);
for($i=0;$i<$info['count'];$i++){
//deleting recursively sub entries
$result=ldap_delete_r($ds,$info[$i]['dn'],$recursive);
if(!$result){
//return result code, if delete fails
return($result);
}
}
return(ldap_delete($ds,$dn));
}
}
function add_ldap ($ds, $dn, &$add,&$err) {
$username = username();
$err = "LDAP: <$dn> successfully added";
if (!ldap_add($ds, $dn, $add)) {
$err = "LDAP: Can't create <$dn>. Reason: ".ldap_error($ds);
syslog(LOG_ERR, $username.": Error: $err.");
return FALSE;
}
$add = array();
syslog(LOG_INFO, $username.": Info: $err.");
return TRUE;
}
function replace_ldap ($ds, $dn, &$entry, &$err) {
$username = username();
$err = "LDAP: <$dn> successfully modified";
if (!ldap_mod_replace($ds, $dn, $entry)) {
$err = "LDAP: Can't modify <$dn>. Reason: ".ldap_error($ds);
syslog(LOG_ERR, $username.": Error: $err.");
return FALSE;
}
$entry=array();
syslog(LOG_INFO, $username.": Info: $err.");
return TRUE;
}
/* Middleware LDAP Class*/
function ldap_delayed_delete($ds,$base,$sel,$dom,&$err) {
/* Insert old key in the delayed delete db */
//$sel = <selclass><sep><hashtag>
$oldDKIMrecord = $sel.'._domainkey.'.$dom;
/* Prepare the data to add */
$dn = "dc=$sel-$dom,$base";
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'domain';
$info['objectClass'][2] = 'dkimdelete';
$info['objectClass'][3] = 'dkim';
$info['dkimdomain'] = $dom;
$info['dkimselector'] = $sel;
$info['dkimrecord'] = $oldDKIMrecord;
if ( add_ldap ($ds, $dn, $info, $err) )
return TRUE;
else
return FALSE;
}
function ldap_isDelayedRecord($ds, $record, $ldapdelconf) {
/* Return TRUE if the DNS record is in delayed deleted state */
$user = username();
/* Construct the query */
$query = $ldapdelconf['delayATTR']."=$record";
if ( $sr = ldap_list($ds, $ldapdelconf['delayDN'], $query, array($ldapdelconf['delayATTR'])) ) {
$c = ldap_count_entries($ds, $sr);
ldap_free_result($sr);
switch ($c > 1 ? '2': $c) {
case 0:
syslog(LOG_INFO, "$user: Info: LDAP: The record <$record> is currently active.");
break;
case 1:
syslog(LOG_INFO, "$user: Info: LDAP: The record <$record> is delayed deleted.");
return TRUE;
case 2:
syslog(LOG_ERR, "$user: Error: LDAP: It seems that <$record> is duplicated in delayed DB.");
return FALSE;
default:
syslog(LOG_ERR, "$user: Error: LDAP: some error during query: unexpected result.");
}
}
return FALSE;
}
function ldap_deleteOldRecord($ldapconf, $nsupdateconf, $createTimestamp) {
/* Delete entry based on her createTimestamp value */
$username = username();
$records = array();
// connect
$ds = conn_ldap($ldapconf['server']['host'], $ldapconf['server']['port'],$ldapconf['server']['user'],$ldapconf['server']['pwd']);
if (!$ds) {
$err = 'Program terminated abnormally, no entries deleted.';
syslog(LOG_ERR, $username.': Error: '.$err);
return FALSE;
}
/* Construct the query */
$myzone= $createTimestamp->getTimezone();
$createTimestamp->setTimezone(new DateTimeZone('UCT'));
$createTimestamp->format('YmdHis\Z');
$query = '(&('.$ldapconf['delaydel']['delayATTR'].'=*)(createtimestamp<='.$createTimestamp->format('YmdHis\Z').'))';
$createTimestamp->setTimezone($myzone);
/* Looking for the record to delete */
if ( $sr = ldap_list($ds, $ldapconf['delaydel']['delayDN'], $query, array($ldapconf['delaydel']['delayATTR'])) ) {
$info = ldap_get_entries($ds, $sr);
if ( $info['count'] == 0 ) {
$err = 'LDAP: I haven\'t found any record to delete.';
syslog(LOG_WARNING, $username.": Warn: $err");
return TRUE;
}
$nr = 0;
for ($i = 0; $i < $info['count']; $i++) {
if ($info[$i][$ldapconf['delaydel']['delayATTR']]['count'] != 1)
syslog(LOG_WARNING, $username.': Warn: '.
'Skipping <'.$info[$i]['dn'].'> because it seems to have '.
$info[$i][$ldapconf['delaydel']['delayATTR']]['count'].' values of <'.
$ldapconf['delaydel']['delayATTR'].'>.');
else {
$records['values'][] = $info[$i][$ldapconf['delaydel']['delayATTR']][0];
$records['dn'][] = $info[$i]['dn'];
$nr++;
}
}
}
else {
$err = 'LDAP: Error during search! Reason: '.ldap_error($ds);
syslog(LOG_ERR, $username.": Error: $err.");
return FALSE;
}
syslog (LOG_INFO, $username.": Info: $nr delayed deleted records found before ".$createTimestamp->format('Y-m-d H:i:s T').'.');
/* Real delete */
$ret = TRUE;
$retL = FALSE;
for ($i=0; $i<$nr; $i++) {
if ( $retD = updatezone($nsupdateconf['key'], $nsupdateconf['name'], 'delete',
array('dom' => $records['values'][$i], 'prereq' => "yxdomain {$records['values'][$i]}", 'type' => 'TXT'), '', $err ) )
if ( $retL = del_ldap($ds,$records['dn'][$i],$err) )
syslog (LOG_INFO, $username.': Info: record <'. $records['values'][$i].'> deleted at all successfully.');
else syslog(LOG_ERR, $username.': Error: <'. $records['values'][$i].'> deleted only from DNS and not from LDAP!');
else syslog(LOG_ERR, $username.': Error: Can\'t delete <'.$records['values'][$i].'>.');
$ret = $ret && $retD && $retL;
}
ldap_unbind($ds);
/* Return operation status */
return $ret;
}
function add_dkim_ldap($ds, $base, $dom, $sel, $selclass, $key, &$err) {
/* Add tree and key for a new domain */
// $sel = <selclass><sep><hashtag>
/* Prepare the data to add */
/* OU root Container */
$dn = "ou=$dom,ou=$selclass,$base";
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'organizationalunit';
$info['ou'] = $dom;
if (!add_ldap ($ds, $dn, $info, $err)) return FALSE;
/* CoS Template for the domain */
$dnT = "cn=CosTemplate_DKIMSelector,ou=$dom,ou=$selclass,$base";
$info['cn'] = 'CosTemplate_DKIMSelector';
$info['DKIMSelector'] = $sel;
$info['cosPriority'] = 0;
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'costemplate';
$info['objectClass'][2] = 'ldapsubentry';
$info['objectClass'][3] = 'extensibleobject';
if (!add_ldap ($ds, $dnT, $info, $err)) return FALSE;
/* CoS for the domain */
$dn = "cn=$selclass CoS,ou=$dom,ou=$selclass,$base";
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'ldapsubentry';
$info['objectClass'][2] = 'cossuperdefinition';
$info['objectClass'][3] = 'cosPointerDefinition';
$info['cn'] = "$selclass CoS";
$info['costemplatedn'] = $dnT;
$info['cosAttribute'] = 'dkimselector override';
$info['description'] = "CoS to force DKIMSelector to $selclass type";
if (!add_ldap ($ds, $dn, $info, $err)) return FALSE;
/* Keytable */
$dn = "ou=KeyTable,ou=$dom,ou=$selclass,$base";
$info['DKIMDomain'] = $dom;
$info['DKIMSelector'] = $sel;
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'organizationalunit';
$info['objectClass'][2] = 'dkim';
$info['ou'] = 'KeyTable';
$info['DKIMKey'] = $key;
if (!add_ldap ($ds, $dn, $info, $err)) return FALSE;
/* SigningTable */
$dn = "ou=SigningTable,ou=$dom,ou=$selclass,$base";
$info['DKIMIdentity'] = '@'.$dom;
$info['mail'] = $dom;
$info['DKIMSelector'] = $sel;
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'organizationalunit';
$info['objectClass'][2] = 'dkim';
$info['objectClass'][3] = 'dkimmailrecipient';
$info['ou'] = 'SigningTable';
if (! add_ldap ($ds, $dn, $info, $err) ) return FALSE;
syslog(LOG_INFO, username().": Info: LDAP: The new domain <$dom> has added to DKIM for <$sel>.");
return TRUE;
}
function mod_dkim_ldap($ds, $base, $dom, $sel, $curSel, $selclass, $key, &$err) {
/* Modify Selector and privKey for an existing domain */
// $sel = <selclass><sep><hashtag>
$username = username();
/* CoS Selector */
if ( !$curSel ) return FALSE;
if ( $curSel === $sel ) {
$err = "LDAP: The current selector is already <$sel>. I can't change key of existing selector.";
syslog(LOG_ERR, $username.": Error: $err");
return FALSE;
}
$entry['DKIMSelector'][0] = $sel;
/* Change Selector value */
$dnT = "cn=CosTemplate_DKIMSelector,ou=$dom,ou=$selclass,$base";
if (!replace_ldap ($ds, $dnT, $entry, $err)) return FALSE;
/* Change privKey */
$dn = "ou=KeyTable,ou=$dom,ou=$selclass,$base";
$entry['DKIMKey'] = $key;
if ( replace_ldap ($ds, $dn, $entry, $err) ) {
$err = "LDAP: The current DKIMSelector of value <$curSel> has been replaced with the value <$sel>.";
syslog(LOG_INFO, $username.": Info: $err");
return TRUE;
}
return FALSE;
}
function add_dkim_subdom_ldap($ds, $base, $dom, $subdom, $sel, $selclass, &$err) {
/* Add signing path for a new domain */
// $sel = <selclass><sep><hashtag>
$username = username();
if ( strpos($subdom,$dom) === FALSE ) {
$err = "LDAP: You try to add <$subdom> which is not a subdomain of <$dom>";
syslog(LOG_ERR, $username.": Error: $err");
return FALSE;
}
if (! dns_getMX ($subdom, $err))
return FALSE;
/* Prepare the data to add */
$ou = substr($subdom, 0, strrpos($subdom,'.'.$dom));
/* OU main Container */
$dn = "ou=$ou,ou=SigningTable,ou=$dom,ou=$selclass,$base";
$info['DKIMIdentity'] = '@'.$subdom;
$info['mail'] = $subdom;
$info['ou'][0] = $ou;
#$info['ou'][1] = $subdom;
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'organizationalunit';
$info['objectClass'][2] = 'dkim';
$info['objectClass'][3] = 'dkimmailrecipient';
$info['DKIMSelector'] = $sel;
syslog (LOG_INFO, $username.': Info: LDAP: adding DKIM Identity for '.$subdom);
return add_ldap ($ds, $dn, $info, $err);
}
function add_dkim_email_ldap($ds, $base, $dom, $email, $alias, $gn, $sn, $sel, $selclass, &$err) {
/* Add signing path for a new email */
// $sel = <selclass><sep><hashtag>
$username = username();
$edom = substr(strstr($email, '@'),1);
$uid = strstr($email, '@',TRUE);
if ( strpos($edom,$dom) === FALSE ) {
$err = "LDAP: You are trying to add an email with <$edom> which is not a subdomain of <$dom>.";
syslog(LOG_ERR, $username.": Error: $err");
return FALSE;
}
if (! dns_getMX ($edom, $err))
return FALSE;
/* Prepare the data to add */
if ( $edom === $dom )
$dn = "uid=$uid,ou=SigningTable,ou=$dom,ou=$selclass,$base";
else
{
$dnbase = 'ou='.substr($edom, 0, strrpos($edom,'.'.$dom)).",ou=SigningTable,ou=$dom,ou=$selclass,$base";
if (is_tree( $ds, $dnbase, 'DKIMSelector' ) )
$dn = "uid=$uid,$dnbase";
else {
$err = "LDAP: You MUST define the default DKIM Identity of subdomain <$edom> before to add an email.";
syslog(LOG_ERR, $username.": Error: $err");
return FALSE;
}
}
/* Entry */
$info['DKIMIdentity'] = $email;
$info['mail'] = $email;
$info['uid'] = $uid;
$info['objectClass'][0] = 'top';
$info['objectClass'][1] = 'person';
$info['objectClass'][2] = 'organizationalPerson';
$info['objectClass'][3] = 'inetorgperson';
$info['objectClass'][4] = 'dkim';
$info['objectClass'][5] = 'dkimmailrecipient';
$info['DKIMSelector'] = $sel;
$info['givenName'] = $gn;
$info['sn'] = $sn;
$info['cn'] = $gn.' '.$sn;
syslog(LOG_INFO, $username.": Info: LDAP: adding DKIM email identity <$email> to <$dom> key.");
if (!is_null($alias)) {
$adom = substr(strstr($alias, '@'),1);
if (! dns_getMX ($adom, $err)) return FALSE;
if ( strpos($adom,$edom) === FALSE ) {
$err = "LDAP: You try to add an email with <$adom> which is not a subdomain of <$edom>.";
syslog(LOG_ERR, $username.": Error: $err");
return FALSE;
}
$info['mailAlternateAddress'] = $alias;
syslog(LOG_WARNING, $username.": Warn: LDAP: adding DKIM alias email identity <$alias> for <$email> to <$dom> key.".
' This could cause warning at higher reputation level.');
}
if ( add_ldap ($ds, $dn, $info, $err) ) return TRUE;
return FALSE;
}
function is_already($ds, $base_dn, $dom) {
/* Check if dom and parents is already present on DKIM LDAP setup as domain or SigningTable's subdomain */
if (! ($occurrence = strstr($dom, '.')) )
return FALSE;
if ( ($sr = ldap_search($ds, $base_dn, "(&(objectclass=organizationalunit)(ou=$dom))",array('ou'),1)) === FALSE )
return FALSE;
$info = ldap_get_entries($ds, $sr);
if ( $info["count"] ) return TRUE;
return is_already($ds, $base_dn, $dom = substr($occurrence,1));
}
function subdomains($ds,$base_dn, $dom, $selclass) {
/* Return a list of signing subdomains of $dom */
$dn = "ou=SigningTable,ou=$dom,ou=$selclass,$base_dn";
if ( $sr = ldap_list($ds, $dn, '(&(objectclass=dkim)(ou=*))', array('ou')) )
return ldap_get_entries($ds, $sr);
return FALSE;
}
function signemails($ds,$base_dn, $dom, $selclass) {
/* Return a list of signing VIP emails of $dom */
$dn = "ou=SigningTable,ou=$dom,ou=$selclass,$base_dn";
if ( $sr = ldap_search($ds, $dn, '(&(objectclass=dkim)(uid=*)(mail=*))', array('DKIMIdentity')) )
return ldap_get_entries($ds, $sr);
return FALSE;
}
function currentLDAPSel ($ds, $dn, &$err) {
/* Return current selector as <selclass><sep><hashtag> */
$username = username();
if ( $sr = ldap_read($ds, $dn, 'DKIMSelector=*', array('DKIMSelector')) ) {
$info = ldap_get_entries($ds, $sr);
if ( $info['count'] != 1 ) {
$err = 'LDAP: Error in number of DKIMSelector values. Returned: '.$info['count'].'. Expected: 1';
syslog(LOG_EMERG, $username.": Emerg: $err.");
return FALSE;
}
return $info[0]['dkimselector'][0];
}
$err = 'LDAP: I can\'t find any DKIMSelector! Reason: '.ldap_error($ds);
syslog(LOG_EMERG, $username.": Emerg: $err.");
return FALSE;
}
/* DNS Class */
function readRecord($dom, $type) {
/* Return records for $dom or:
FALSE if no record is found or errors */
$user = username();
$value = array();
$records = dns_get_record($dom,DNS_TXT);
if ($records === FALSE) {
syslog(LOG_ERR, "$user: Error: DNS: error in query.");
return FALSE;
}
$count = 0;
if (isset($records[0]['entries']))
foreach ( $records as $record ) {
$ok = FALSE;
switch ($type) {
/* I don't check validity of record name, only value... */
case 'DKIM':
if ( substr( $record['entries'][0], 0, 8 ) === 'v=DKIM1;' )
$ok = TRUE;
break;
case 'SPF':
if ( substr( $record['entries'][0], 0, 7 ) === 'v=spf1 ' )
$ok = TRUE;
break;
case 'DMARC':
if ( substr( $record['entries'][0], 0, 8 ) === 'v=DMARC1' )
$ok = TRUE;
break;
default:
syslog(LOG_ALERT, "$user: Alert: DNS: invalid record type specified.");
return FALSE;
}
if ( $ok ) {
$count ++;
$value[] = $record['entries'][0];
}
}
else return FALSE;
if ( $count == 0 ) return FALSE;
else return $value;
}
function thisRecord($dom,$type,$sel,&$recordfound = FALSE) {
/* Read record specifically for DKIM */
// $sel = <selclass><sep><hashtag>
$username = username();
switch ( $type ) {
case 'DKIM':
if ( $recordfound = dns_get_record($sel.'._domainkey.'.$dom,DNS_TXT) )
if ( substr( $recordfound[0]['txt'], 0, 7 ) === 'v=DKIM1' )
return $recordfound[0]['txt'];
else syslog(LOG_WARNING, $username.": Warn: DNS: <$dom> for selector <$sel> has an invalid DKIM record");
else syslog(LOG_WARNING, $username.": Warn: DNS: <$dom> doesn't have a DKIM record for selector <$sel>.");
return FALSE;
}
}
function is_own($dom, $nameservers) {
$ns = dns_get_record($dom,DNS_NS);
foreach ( $ns as $name )
if ( in_array($name['target'],$nameservers) )
return TRUE;
return FALSE;
}
function dns_pardom_get_record (&$dom,$type,$strictmode) {
/* Find first record on parent dom of at least second level */
/* Return the record and the associated subdomain */
/* Really not used for DKIM... */
// $selector = <selclass><sep><hashtag>
if (! ($occurrence = strstr($dom, '.')) )
return FALSE;
switch ( $type ) {
/* case 'DKIM':
$recordname = $selector . "._domainkey.$dom";
break;
*/
case 'DMARC':
$recordname = "_dmarc.$dom";
break;
default:
return FALSE;
}
if ( $record = readRecord($recordname, $type) )
return $record;
if ($strictmode) return FALSE;
if ( $dom == orgDom($dom) ) return FALSE;
else {
$dom = substr($occurrence,1);
return dns_pardom_get_record ( $dom, $type, $strictmode );
}
}
function dns_getMX ($dom, &$err) {
/* Return TRUE if $dom has not null MX record */
$err = NULL;
$return = getmxrr ( $dom, $mx );
if ( $return ) {
if ( in_array('.',$mx) ) {
$err = "DNS: <$dom> has null MX record.";
$return = FALSE;
}
else $err = "DNS: <$dom> has valid MX records.";
}
else $err = "DNS: <$dom> doesn't have any MX record!";
syslog(LOG_INFO, username().": Info: $err");
// $return = TRUE; // ***** -- >> Remember to remove this line! << -- *****
return $return;
}
function remove_dkim_dns($drv_del,$ds,$delay_dn,$dom,$sel,&$err) {
/* Unlucky function title. Really is a *Delay delete* for the selector */
$username=username();
switch ( $drv_del ) {
case 'mysql':
$db = parse_ini_file('db.conf', true);
if (! isset($db['port']) ) $db['port'] = ini_get("mysqli.default_port");
$mysql = mysqlconn($db['host'], $db['user'], $db['pass'], $db['name'], $db['port'], $err);
if ( $mysql )
if (! mysql_delayed_delete($mysql,$db['table'],$sel,$dom,$err) )
return FALSE;
return TRUE;
case 'ldap':
if (! ldap_delayed_delete($ds,$delay_dn,$sel,$dom,$err) ) {
syslog(LOG_ERR, $username.": Error: I can't delay delete <$sel>");
return FALSE;
}
return TRUE;
default:
syslog(LOG_ALERT, $username.": Alert: Unknown driver <$drv_del>. Won't delete DKIM record of <$dom>.");
return FALSE;
}
}
function nsupdate($data, &$err, $k='') {
// run DNS update
if (version_compare(PHP_VERSION, '7.0.0') < 0)
$tmpfile = uniqid('nsupdate-') . '.txt';
else
$tmpfile = 'nsupdate-' . bin2hex(random_bytes(4)) . '.txt';
$username = username();
if (! file_exists('/usr/bin/nsupdate') ) {
$err = 'DNS: nsupdate doesn\'t exist.';
syslog(LOG_ALERT, $username.": Alert: $err");
return FALSE;
}
if (!empty($k)) {
if (!file_exists($k)) {
$err = sprintf('DNS: nsupdate key file <%s> not found.',$k);
syslog(LOG_ALERT, $username.": Alert: $err");
return FALSE;
}
$bin = escapeshellcmd("/usr/bin/nsupdate -k $k");
}
else
$bin = escapeshellcmd('/usr/bin/nsupdate');
if ( file_exists($tmpfile) )
if ( unlink ($tmpfile) )
syslog(LOG_INFO, $username.': Info: DNS: nsupdate tmp file already present. I deleted it.');
if ( file_put_contents($tmpfile, $data) === FALSE ) {
$err = 'DNS: Can\'t write tmp file for nsupdate.';
syslog(LOG_ALERT, $username.": Alert: $err");
return FALSE;
}
exec("$bin $tmpfile 2>&1", $ret, $status);
if ($status !== 0) {
$err = "DNS: Update failed with code <$status>. File <$tmpfile> preserved for evidences.";
if (! empty($ret) )
$err .= ' Reason: <'.implode(' - ',$ret).'>.';
syslog(LOG_ALERT, "$username: Alert: $err");
return FALSE;
}
else
$err = 'DNS: Operation successfull.';
if (! empty($ret) )
$err .= ' Details: <'.implode(' - ',$ret).'>.';
//if ( substr_compare($ret, 'update failed', 0, 13) == 0 ) {
// $err = "DNS: Changing DNS failed with status <$ret>.";
// syslog(LOG_ALERT, "$username: Error: $err");
// return FALSE;
//}
if ( unlink ($tmpfile) )
syslog(LOG_INFO, $username.': Info: DNS: nsupdate tmp file successfully deleted after nsupdate call.');
syslog(LOG_INFO,"$username: Info: $err");
return TRUE;
}
function updatezone($key, $servers, $action, $record, $TTL, &$errors, $zone=NULL) {
$errors = NULL;
if ( !( ($action == 'add') OR ($action == 'delete') ) ) {
$errors = 'Update action must be "add" or "delete", not "'.$action.'".';
return FALSE;
}
if (is_array($servers))
$ret = TRUE;
else {
$errors = 'No nameservers given for nsupdate';
return FALSE;
}
$username = username();
if (! isset($record['value']) )
$record['value'] = '';
foreach ( $servers as $type => $server ) {
$data = NULL;
syslog(LOG_INFO, "$username: Info: DNS: Preparing to $action record {$record['type']} <{$record['dom']}> on $type server $server.");
if ( !is_null($zone) )
$data = "zone $zone\n";
$data .= <<<EOF
server $server
prereq {$record['prereq']}
update $action {$record['dom']} $TTL {$record['type']} {$record['value']}
send
quit
EOF;
if ( !nsupdate($data, $err, $key) )
$ret = FALSE;
$errors .= $err." Server: $server.\r\n";
}
return $ret;
}
/* Mysql class */
function mysqlconn($dbhost, $dbuser, $pwd, $db, $dbport,&$err) {
$user = username();
$err = FALSE;
$mysqli = new mysqli($dbhost, $dbuser, $pwd, $db, $dbport);
if ($mysqli->connect_error) {
$err = "MySQL: Could not connect to MySQL server <$dbhost> on DB <$db> as user <$dbuser>. Reason: ".
$mysqli->connect_error.' (' . $mysqli->connect_errno . ')';
syslog (LOG_EMERG, $user.': Emerg: '.$err);
return FALSE;
}
syslog (LOG_INFO, $user.': Info: MySQL: Successfully connected to MySQL server ' . $mysqli->host_info . " on DB <$db> as user <$dbuser>.");
return $mysqli;
}
function mysqladd($mysqli,$value,$table,&$err) {
$user = username();
$query= sprintf("INSERT INTO `$table` ( `value` ) VALUES ( '%s' )" ,$value);
if ($mysqli->query($query) === TRUE) {
$err = "MySQL: <$value> successfully added to table <$table>";
syslog(LOG_INFO, $user.": Info: $err");
return TRUE;
}
else {
$err = "MySQL: Unable to add <$value> to table <$table>. Reason: ".$mysqli->error;
syslog(LOG_ERR, "$user: Error: $err");
}
return FALSE;
}
function mysqldel($mysqli,$value,$table,&$err) {
$user = username();
$query= sprintf("DELETE FROM `$table` WHERE `value`='%s'" ,$value);
if ($mysqli->query($query) === TRUE) {
$err = "MySQL: <$value> successfully deleted from table <$table>";
syslog(LOG_INFO, $user.": Info: $err");
return TRUE;
}
else {
$err = "MySQL: Unable to delete <$value> from table <$table>. Reason: ".$mysqli->error;
syslog(LOG_ERR, "$user: Error: $err");
}
return FALSE;
}
function mysql_delayed_delete($mysql,$table,$sel,$dom,&$err) {
/* Insert old key in the delayed delete db */
// $sel = <selclass><sep><hashtag>
$oldDKIMrecord = $sel.'._domainkey.'.$dom;
if ( mysqladd($mysql,$oldDKIMrecord,$table,$err) )
return TRUE;
else
return FALSE;
}
function mysql_isDelayedRecord($db, $record) {
/* Return TRUE if the DNS record is in delayed deleted state */
/* $record contains the name of the record, not the value */
$user = username();
$table = $db['table'];
/* Looking for record's values */
$query = sprintf("SELECT `value` FROM `$table` WHERE `value` = '%s'" ,$record);
// connect
if (! isset($db['port']) ) $db['port'] = ini_get("mysqli.default_port");
$mysqli = mysqlconn($db['host'], $db['user'], $db['pass'], $db['name'], $db['port'], $err);
if ( !$mysqli )
return FALSE;
if ($res = $mysqli->query($query)) {
switch ($res->num_rows > 1 ? '2':$res->num_rows) {
case 0:
$res->close();
$mysqli->close();
syslog(LOG_INFO, "$user: Info: LDAP: The record <$record> is currently active.");
return FALSE;
case 1:
syslog(LOG_INFO, "$user: Info: LDAP: The record <$record> is delayed deleted.");
$res->close();
$mysqli->close();
return TRUE;
case 2:
syslog(LOG_ERR, "$user: Error: MySQL: It seems that <$record> is duplicated in DB.");
$res->close();
$mysqli->close();
return FALSE;
default:
syslog(LOG_ERR, "$user: Error: MySQL: some error during query: ".$mysqli->error);
}
}
$res->close();
$mysqli->close();
return FALSE;
}
function mysql_deleteOldRecord($db, $nsupdateconf, $mydate) {
/* Delete record based on his MySQL timestamp value */
/* We assume the timezone is managed by MySQL Engine */
/* $mydate can have DST comment, anyway is ignored
during query */
$records = array();
$user = username();
$table = $db['table'];
/* Looking for record's values */
$query = sprintf("SELECT `value` FROM `$table` WHERE `date` < '%s'" ,$mydate);
// connect
if (! isset($db['port']) ) $db['port'] = ini_get("mysqli.default_port");
$mysqli = mysqlconn($db['host'], $db['user'], $db['pass'], $db['name'], $db['port'], $err);
if ( !$mysqli )
return FALSE;
if ($res = $mysqli->query($query))
while ($row = $res->fetch_assoc())
$records[] = $row['value'];
else {
syslog(LOG_WARNING, "$user: Warn: MySQL: Unable to find delayed deleted records. Reason: ".$mysqli->error);
return TRUE;
}
$res->free();
$nr = count($records);
syslog (LOG_INFO, "$user: Info: $nr records delayed deleted before $mydate found.");
/* Real delete */
$ret = TRUE;
$retM= FALSE;
for ($i=0; $i<$nr; $i++) {
if ( $retD = updatezone($nsupdateconf['key'], $nsupdateconf['name'], 'delete',
array('dom' => $records[$i], 'prereq' => "yxdomain {$records[$i]}", 'type' => 'TXT'), '', $err) )
if ( $retM = mysqldel($mysqli,$records[$i],$table,$err) )
syslog (LOG_INFO, $user.': Info: record <'. $records[$i].'> deleted at all successfully.');
else syslog(LOG_ERR, $user.': Error: <'. $records[$i].'> deleted only from DNS and not from MySQL!');
else syslog(LOG_ERR, $user.': Error: Can\'t delete <'.$records[$i].'> Reason: '.$err);
$ret = $ret && $retD && $retM;
}
/* Return operation status */
return $ret;
}
/* High level class */
function getSelclass ($selclasses,$sel) {