summaryrefslogtreecommitdiff
path: root/usr.sbin/smtpd/lka.c
blob: d721e5f7c317c906ecc5187a275f593c272ca3b5 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
/*	$OpenBSD: lka.c,v 1.223 2018/12/11 11:29:44 gilles Exp $	*/

/*
 * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
 * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org>
 * Copyright (c) 2012 Eric Faurot <eric@faurot.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/tree.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/uio.h>

#include <netinet/in.h>

#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <event.h>
#include <imsg.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <pwd.h>
#include <resolv.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "smtpd.h"
#include "log.h"
#include "ssl.h"

static void lka_imsg(struct mproc *, struct imsg *);
static void lka_shutdown(void);
static void lka_sig_handler(int, short, void *);
static int lka_authenticate(const char *, const char *, const char *);
static int lka_credentials(const char *, const char *, char *, size_t);
static int lka_userinfo(const char *, const char *, struct userinfo *);
static int lka_addrname(const char *, const struct sockaddr *,
    struct addrname *);
static int lka_mailaddrmap(const char *, const char *, const struct mailaddr *);
static int lka_X509_verify(struct ca_vrfy_req_msg *, const char *, const char *);
static void lka_certificate_verify(enum imsg_type, struct ca_vrfy_req_msg *);
static void lka_certificate_verify_resume(enum imsg_type, struct ca_vrfy_req_msg *);

static void
lka_imsg(struct mproc *p, struct imsg *imsg)
{
	struct table		*table;
	int			 ret;
	struct pki		*pki;
	struct iovec		iov[2];
	static struct ca_vrfy_req_msg	*req_ca_vrfy = NULL;
	struct ca_vrfy_req_msg		*req_ca_vrfy_chain;
	struct ca_cert_req_msg		*req_ca_cert;
	struct ca_cert_resp_msg		 resp_ca_cert;
	struct sockaddr_storage	 ss;
	struct userinfo		 userinfo;
	struct addrname		 addrname;
	struct envelope		 evp;
	struct mailaddr		 maddr;
	struct msg		 m;
	union lookup		 lk;
	char			 buf[LINE_MAX];
	const char		*tablename, *username, *password, *label, *procname;
	uint64_t		 reqid;
	int			 v;
	time_t			 tm;
	const char		*rdns;
	const char		*command, *response;
	const char		*ciphers;
	const char		*address;
	const char		*heloname;
	struct sockaddr_storage	ss_src, ss_dest;
	int                      filter_response;
	int                      filter_phase;
	const char              *filter_param;
	uint32_t		 msgid;
	uint64_t		 evpid;
	size_t			 msgsz;
	int			 ok;
	int			 fcrdns;

	if (imsg == NULL)
		lka_shutdown();

	switch (imsg->hdr.type) {

	case IMSG_GETADDRINFO:
	case IMSG_GETNAMEINFO:
		resolver_dispatch_request(p, imsg);
		return;

	case IMSG_CERT_INIT:
	case IMSG_CERT_CERTIFICATE:
	case IMSG_CERT_VERIFY:
		cert_dispatch_request(p, imsg);
		return;

	case IMSG_MTA_DNS_HOST:
	case IMSG_MTA_DNS_MX:
	case IMSG_MTA_DNS_MX_PREFERENCE:
		dns_imsg(p, imsg);
		return;

	case IMSG_SMTP_CHECK_SENDER:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_get_string(&m, &username);
		m_get_mailaddr(&m, &maddr);
		m_end(&m);

		ret = lka_mailaddrmap(tablename, username, &maddr);

		m_create(p, IMSG_SMTP_CHECK_SENDER, 0, 0, -1);
		m_add_id(p, reqid);
		m_add_int(p, ret);
		m_close(p);
		return;

	case IMSG_SMTP_EXPAND_RCPT:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_envelope(&m, &evp);
		m_end(&m);
		lka_session(reqid, &evp);
		return;

	case IMSG_SMTP_LOOKUP_HELO:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_get_sockaddr(&m, (struct sockaddr *)&ss);
		m_end(&m);

		ret = lka_addrname(tablename, (struct sockaddr*)&ss,
		    &addrname);

		m_create(p, IMSG_SMTP_LOOKUP_HELO, 0, 0, -1);
		m_add_id(p, reqid);
		m_add_int(p, ret);
		if (ret == LKA_OK)
			m_add_string(p, addrname.name);
		m_close(p);
		return;

	case IMSG_SMTP_TLS_INIT:
	case IMSG_MTA_TLS_INIT:
		req_ca_cert = imsg->data;
		resp_ca_cert.reqid = req_ca_cert->reqid;

		xlowercase(buf, req_ca_cert->name, sizeof(buf));
		log_debug("debug: lka: looking up pki \"%s\"", buf);
		pki = dict_get(env->sc_pki_dict, buf);
		if (pki == NULL)
			if (req_ca_cert->fallback)
				pki = dict_get(env->sc_pki_dict, "*");
		if (pki == NULL) {
			resp_ca_cert.status = CA_FAIL;
			m_compose(p, imsg->hdr.type, 0, 0, -1, &resp_ca_cert,
			    sizeof(resp_ca_cert));
			return;
		}
		resp_ca_cert.status = CA_OK;
		resp_ca_cert.cert_len = pki->pki_cert_len;
		(void)strlcpy(resp_ca_cert.name, pki->pki_name, sizeof resp_ca_cert.name);
		iov[0].iov_base = &resp_ca_cert;
		iov[0].iov_len = sizeof(resp_ca_cert);
		iov[1].iov_base = pki->pki_cert;
		iov[1].iov_len = pki->pki_cert_len;
		m_composev(p, imsg->hdr.type, 0, 0, -1, iov, nitems(iov));
		return;

	case IMSG_SMTP_TLS_VERIFY_CERT:
	case IMSG_MTA_TLS_VERIFY_CERT:
		req_ca_vrfy = xmemdup(imsg->data, sizeof *req_ca_vrfy);
		req_ca_vrfy->cert = xmemdup((char *)imsg->data +
		    sizeof *req_ca_vrfy, req_ca_vrfy->cert_len);
		req_ca_vrfy->chain_cert = xcalloc(req_ca_vrfy->n_chain,
		    sizeof (unsigned char *));
		req_ca_vrfy->chain_cert_len = xcalloc(req_ca_vrfy->n_chain,
		    sizeof (off_t));
		return;

	case IMSG_SMTP_TLS_VERIFY_CHAIN:
	case IMSG_MTA_TLS_VERIFY_CHAIN:
		if (req_ca_vrfy == NULL)
			fatalx("lka:ca_vrfy: chain without a certificate");
		req_ca_vrfy_chain = imsg->data;
		req_ca_vrfy->chain_cert[req_ca_vrfy->chain_offset] = xmemdup((char *)imsg->data +
		    sizeof *req_ca_vrfy_chain, req_ca_vrfy_chain->cert_len);
		req_ca_vrfy->chain_cert_len[req_ca_vrfy->chain_offset] = req_ca_vrfy_chain->cert_len;
		req_ca_vrfy->chain_offset++;
		return;

	case IMSG_SMTP_TLS_VERIFY:
	case IMSG_MTA_TLS_VERIFY:
		if (req_ca_vrfy == NULL)
			fatalx("lka:ca_vrfy: verify without a certificate");
		lka_certificate_verify(imsg->hdr.type, req_ca_vrfy);
		req_ca_vrfy = NULL;
		return;

	case IMSG_SMTP_AUTHENTICATE:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_get_string(&m, &username);
		m_get_string(&m, &password);
		m_end(&m);

		if (!tablename[0]) {
			m_create(p_parent, IMSG_LKA_AUTHENTICATE,
			    0, 0, -1);
			m_add_id(p_parent, reqid);
			m_add_string(p_parent, username);
			m_add_string(p_parent, password);
			m_close(p_parent);
			return;
		}

		ret = lka_authenticate(tablename, username, password);

		m_create(p, IMSG_SMTP_AUTHENTICATE, 0, 0, -1);
		m_add_id(p, reqid);
		m_add_int(p, ret);
		m_close(p);
		return;

	case IMSG_MDA_LOOKUP_USERINFO:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_get_string(&m, &username);
		m_end(&m);

		ret = lka_userinfo(tablename, username, &userinfo);

		m_create(p, IMSG_MDA_LOOKUP_USERINFO, 0, 0, -1);
		m_add_id(p, reqid);
		m_add_int(p, ret);
		if (ret == LKA_OK)
			m_add_data(p, &userinfo, sizeof(userinfo));
		m_close(p);
		return;

	case IMSG_MTA_LOOKUP_CREDENTIALS:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_get_string(&m, &label);
		m_end(&m);

		lka_credentials(tablename, label, buf, sizeof(buf));

		m_create(p, IMSG_MTA_LOOKUP_CREDENTIALS, 0, 0, -1);
		m_add_id(p, reqid);
		m_add_string(p, buf);
		m_close(p);
		return;

	case IMSG_MTA_LOOKUP_SOURCE:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_end(&m);

		table = table_find(env, tablename, NULL);

		m_create(p, IMSG_MTA_LOOKUP_SOURCE, 0, 0, -1);
		m_add_id(p, reqid);

		if (table == NULL) {
			log_warn("warn: source address table %s missing",
			    tablename);
			m_add_int(p, LKA_TEMPFAIL);
		}
		else {
			ret = table_fetch(table, NULL, K_SOURCE, &lk);
			if (ret == -1)
				m_add_int(p, LKA_TEMPFAIL);
			else if (ret == 0)
				m_add_int(p, LKA_PERMFAIL);
			else {
				m_add_int(p, LKA_OK);
				m_add_sockaddr(p,
				    (struct sockaddr *)&lk.source.addr);
			}
		}
		m_close(p);
		return;

	case IMSG_MTA_LOOKUP_HELO:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_get_sockaddr(&m, (struct sockaddr *)&ss);
		m_end(&m);

		ret = lka_addrname(tablename, (struct sockaddr*)&ss,
		    &addrname);

		m_create(p, IMSG_MTA_LOOKUP_HELO, 0, 0, -1);
		m_add_id(p, reqid);
		m_add_int(p, ret);
		if (ret == LKA_OK)
			m_add_string(p, addrname.name);
		m_close(p);
		return;

	case IMSG_MTA_LOOKUP_SMARTHOST:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_string(&m, &tablename);
		m_end(&m);

		table = table_find(env, tablename, NULL);

		m_create(p, IMSG_MTA_LOOKUP_SMARTHOST, 0, 0, -1);
		m_add_id(p, reqid);

		if (table == NULL) {
			log_warn("warn: smarthost table %s missing", tablename);
			m_add_int(p, LKA_TEMPFAIL);
		}
		else {
			ret = table_fetch(table, NULL, K_RELAYHOST, &lk);
			if (ret == -1)
				m_add_int(p, LKA_TEMPFAIL);
			else if (ret == 0)
				m_add_int(p, LKA_PERMFAIL);
			else {
				m_add_int(p, LKA_OK);
				m_add_string(p, lk.relayhost);
			}
		}
		m_close(p);
		return;

	case IMSG_CONF_START:
		return;

	case IMSG_CONF_END:
		if (tracing & TRACE_TABLES)
			table_dump_all(env);

		/* fork & exec tables that need it */
		table_open_all(env);

		/* revoke proc & exec */
		if (pledge("stdio rpath inet dns getpw recvfd sendfd",
			NULL) == -1)
			err(1, "pledge");

		/* Start fulfilling requests */
		mproc_enable(p_pony);
		return;

	case IMSG_LKA_OPEN_FORWARD:
		lka_session_forward_reply(imsg->data, imsg->fd);
		return;

	case IMSG_LKA_AUTHENTICATE:
		imsg->hdr.type = IMSG_SMTP_AUTHENTICATE;
		m_forward(p_pony, imsg);
		return;

	case IMSG_CTL_VERBOSE:
		m_msg(&m, imsg);
		m_get_int(&m, &v);
		m_end(&m);
		log_trace_verbose(v);
		return;

	case IMSG_CTL_PROFILE:
		m_msg(&m, imsg);
		m_get_int(&m, &v);
		m_end(&m);
		profiling = v;
		return;

	case IMSG_CTL_UPDATE_TABLE:
		ret = 0;
		table = table_find(env, imsg->data, NULL);
		if (table == NULL) {
			log_warnx("warn: Lookup table not found: "
			    "\"%s\"", (char *)imsg->data);
		} else 
			ret = table_update(table);

		m_compose(p_control,
		    (ret == 1) ? IMSG_CTL_OK : IMSG_CTL_FAIL,
		    imsg->hdr.peerid, 0, -1, NULL, 0);
		return;

	case IMSG_LKA_PROCESSOR_FORK:
		m_msg(&m, imsg);
		m_get_string(&m, &procname);
		m_end(&m);

		lka_proc_forked(procname, imsg->fd);
		return;


	case IMSG_SMTP_REPORT_LINK_CONNECT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &rdns);
		m_get_int(&m, &fcrdns);
		m_get_sockaddr(&m, (struct sockaddr *)&ss_src);
		m_get_sockaddr(&m, (struct sockaddr *)&ss_dest);
		m_end(&m);

		lka_report_smtp_link_connect("smtp-in", tm, reqid, rdns, fcrdns, &ss_src, &ss_dest);
		return;

	case IMSG_SMTP_REPORT_LINK_DISCONNECT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_end(&m);

		lka_report_smtp_link_disconnect("smtp-in", tm, reqid);
		return;

	case IMSG_SMTP_REPORT_LINK_IDENTIFY:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &heloname);
		m_end(&m);

		lka_report_smtp_link_identify("smtp-in", tm, reqid, heloname);
		return;

	case IMSG_SMTP_REPORT_LINK_TLS:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &ciphers);
		m_end(&m);

		lka_report_smtp_link_tls("smtp-in", tm, reqid, ciphers);
		return;

	case IMSG_SMTP_REPORT_TX_BEGIN:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_end(&m);

		lka_report_smtp_tx_begin("smtp-in", tm, reqid, msgid);
		return;

	case IMSG_SMTP_REPORT_TX_MAIL:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_string(&m, &address);
		m_get_int(&m, &ok);
		m_end(&m);

		lka_report_smtp_tx_mail("smtp-in", tm, reqid, msgid, address, ok);
		return;

	case IMSG_SMTP_REPORT_TX_RCPT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_string(&m, &address);
		m_get_int(&m, &ok);
		m_end(&m);

		lka_report_smtp_tx_rcpt("smtp-in", tm, reqid, msgid, address, ok);
		return;

	case IMSG_SMTP_REPORT_TX_ENVELOPE:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_id(&m, &evpid);
		m_end(&m);

		lka_report_smtp_tx_envelope("smtp-in", tm, reqid, msgid, evpid);
		return;

	case IMSG_SMTP_REPORT_TX_COMMIT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_size(&m, &msgsz);
		m_end(&m);

		lka_report_smtp_tx_commit("smtp-in", tm, reqid, msgid, msgsz);
		return;

	case IMSG_SMTP_REPORT_TX_ROLLBACK:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_end(&m);

		lka_report_smtp_tx_rollback("smtp-in", tm, reqid, msgid);
		return;

	case IMSG_SMTP_REPORT_PROTOCOL_CLIENT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &command);
		m_end(&m);

		lka_report_smtp_protocol_client("smtp-in", tm, reqid, command);
		return;

	case IMSG_SMTP_REPORT_PROTOCOL_SERVER:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &response);
		m_end(&m);

		lka_report_smtp_protocol_server("smtp-in", tm, reqid, response);
		return;

	case IMSG_SMTP_REPORT_FILTER_RESPONSE:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_int(&m, &filter_phase);
		m_get_int(&m, &filter_response);
		m_get_string(&m, &filter_param);
		m_end(&m);

		lka_report_smtp_filter_response("smtp-in", tm, reqid,
		    filter_phase, filter_response, filter_param);
		return;

	case IMSG_MTA_REPORT_LINK_CONNECT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &rdns);
		m_get_int(&m, &fcrdns);
		m_get_sockaddr(&m, (struct sockaddr *)&ss_src);
		m_get_sockaddr(&m, (struct sockaddr *)&ss_dest);
		m_end(&m);

		lka_report_smtp_link_connect("smtp-out", tm, reqid, rdns, fcrdns, &ss_src, &ss_dest);
		return;

	case IMSG_MTA_REPORT_LINK_DISCONNECT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_end(&m);

		lka_report_smtp_link_disconnect("smtp-out", tm, reqid);
		return;

	case IMSG_MTA_REPORT_LINK_IDENTIFY:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &heloname);
		m_end(&m);

		lka_report_smtp_link_identify("smtp-out", tm, reqid, heloname);
		return;

	case IMSG_MTA_REPORT_LINK_TLS:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &ciphers);
		m_end(&m);

		lka_report_smtp_link_tls("smtp-out", tm, reqid, ciphers);
		return;

	case IMSG_MTA_REPORT_TX_BEGIN:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_end(&m);

		lka_report_smtp_tx_begin("smtp-out", tm, reqid, msgid);
		return;

	case IMSG_MTA_REPORT_TX_MAIL:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_string(&m, &address);
		m_get_int(&m, &ok);
		m_end(&m);

		lka_report_smtp_tx_mail("smtp-out", tm, reqid, msgid, address, ok);
		return;

	case IMSG_MTA_REPORT_TX_RCPT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_string(&m, &address);
		m_get_int(&m, &ok);
		m_end(&m);

		lka_report_smtp_tx_rcpt("smtp-out", tm, reqid, msgid, address, ok);
		return;

	case IMSG_MTA_REPORT_TX_ENVELOPE:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_id(&m, &evpid);
		m_end(&m);

		lka_report_smtp_tx_envelope("smtp-out", tm, reqid, msgid, evpid);
		return;

	case IMSG_MTA_REPORT_TX_COMMIT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_get_size(&m, &msgsz);
		m_end(&m);

		lka_report_smtp_tx_commit("smtp-out", tm, reqid, msgid, msgsz);
		return;

	case IMSG_MTA_REPORT_TX_ROLLBACK:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_u32(&m, &msgid);
		m_end(&m);

		lka_report_smtp_tx_rollback("smtp-out", tm, reqid, msgid);
		return;

	case IMSG_MTA_REPORT_PROTOCOL_CLIENT:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &command);
		m_end(&m);

		lka_report_smtp_protocol_client("smtp-out", tm, reqid, command);
		return;

	case IMSG_MTA_REPORT_PROTOCOL_SERVER:
		m_msg(&m, imsg);
		m_get_time(&m, &tm);
		m_get_id(&m, &reqid);
		m_get_string(&m, &response);
		m_end(&m);

		lka_report_smtp_protocol_server("smtp-out", tm, reqid, response);
		return;


	case IMSG_SMTP_FILTER_PROTOCOL:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_int(&m, &filter_phase);
		m_get_string(&m, &filter_param);
		m_end(&m);

		lka_filter_protocol(reqid, filter_phase, filter_param);
		return;

	case IMSG_SMTP_FILTER_BEGIN:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_get_sockaddr(&m, (struct sockaddr *)&ss_src);
		m_get_sockaddr(&m, (struct sockaddr *)&ss_dest);
		m_get_string(&m, &rdns);
		m_get_int(&m, &fcrdns);
		m_end(&m);

		lka_filter_begin(reqid, &ss_src, &ss_dest, rdns, fcrdns);
		return;

	case IMSG_SMTP_FILTER_END:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_end(&m);

		lka_filter_end(reqid);
		return;

	case IMSG_SMTP_FILTER_DATA_BEGIN:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_end(&m);

		lka_filter_data_begin(reqid);
		return;

	case IMSG_SMTP_FILTER_DATA_END:
		m_msg(&m, imsg);
		m_get_id(&m, &reqid);
		m_end(&m);

		lka_filter_data_end(reqid);
		return;

	}

	errx(1, "lka_imsg: unexpected %s imsg", imsg_to_str(imsg->hdr.type));
}

static void
lka_sig_handler(int sig, short event, void *p)
{
	int status;
	pid_t pid;

	switch (sig) {
	case SIGCHLD:
		do {
			pid = waitpid(-1, &status, WNOHANG);
		} while (pid > 0 || (pid == -1 && errno == EINTR));
		break;
	default:
		fatalx("lka_sig_handler: unexpected signal");
	}
}

void
lka_shutdown(void)
{
	log_debug("debug: lookup agent exiting");
	_exit(0);
}

int
lka(void)
{
	struct passwd	*pw;
	struct event	 ev_sigchld;

	purge_config(PURGE_LISTENERS);

	if ((pw = getpwnam(SMTPD_USER)) == NULL)
		fatalx("unknown user " SMTPD_USER);

	config_process(PROC_LKA);

	if (initgroups(pw->pw_name, pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		fatal("lka: cannot drop privileges");

	imsg_callback = lka_imsg;
	event_init();

	signal_set(&ev_sigchld, SIGCHLD, lka_sig_handler, NULL);
	signal_add(&ev_sigchld, NULL);
	signal(SIGINT, SIG_IGN);
	signal(SIGTERM, SIG_IGN);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGHUP, SIG_IGN);

	config_peer(PROC_PARENT);
	config_peer(PROC_QUEUE);
	config_peer(PROC_CONTROL);
	config_peer(PROC_PONY);

	/* Ignore them until we get our config */
	mproc_disable(p_pony);

	/* proc & exec will be revoked before serving requests */
	if (pledge("stdio rpath inet dns getpw recvfd sendfd proc exec", NULL) == -1)
		err(1, "pledge");

	event_dispatch();
	fatalx("exited event loop");

	return (0);
}

static int
lka_authenticate(const char *tablename, const char *user, const char *password)
{
	struct table		*table;
	union lookup		 lk;

	log_debug("debug: lka: authenticating for %s:%s", tablename, user);
	table = table_find(env, tablename, NULL);
	if (table == NULL) {
		log_warnx("warn: could not find table %s needed for authentication",
		    tablename);
		return (LKA_TEMPFAIL);
	}

	switch (table_lookup(table, NULL, user, K_CREDENTIALS, &lk)) {
	case -1:
		log_warnx("warn: user credentials lookup fail for %s:%s",
		    tablename, user);
		return (LKA_TEMPFAIL);
	case 0:
		return (LKA_PERMFAIL);
	default:
		if (crypt_checkpass(password, lk.creds.password) == 0)
			return (LKA_OK);
		return (LKA_PERMFAIL);
	}
}

static int
lka_credentials(const char *tablename, const char *label, char *dst, size_t sz)
{
	struct table		*table;
	union lookup		 lk;
	char			*buf;
	int			 buflen, r;

	table = table_find(env, tablename, NULL);
	if (table == NULL) {
		log_warnx("warn: credentials table %s missing", tablename);
		return (LKA_TEMPFAIL);
	}

	dst[0] = '\0';

	switch (table_lookup(table, NULL, label, K_CREDENTIALS, &lk)) {
	case -1:
		log_warnx("warn: credentials lookup fail for %s:%s",
		    tablename, label);
		return (LKA_TEMPFAIL);
	case 0:
		log_warnx("warn: credentials not found for %s:%s",
		    tablename, label);
		return (LKA_PERMFAIL);
	default:
		if ((buflen = asprintf(&buf, "%c%s%c%s", '\0',
		    lk.creds.username, '\0', lk.creds.password)) == -1) {
			log_warn("warn");
			return (LKA_TEMPFAIL);
		}

		r = base64_encode((unsigned char *)buf, buflen, dst, sz);
		free(buf);

		if (r == -1) {
			log_warnx("warn: credentials parse error for %s:%s",
			    tablename, label);
			return (LKA_TEMPFAIL);
		}
		return (LKA_OK);
	}
}

static int
lka_userinfo(const char *tablename, const char *username, struct userinfo *res)
{
	struct table	*table;
	union lookup	 lk;

	log_debug("debug: lka: userinfo %s:%s", tablename, username);
	table = table_find(env, tablename, NULL);
	if (table == NULL) {
		log_warnx("warn: cannot find user table %s", tablename);
		return (LKA_TEMPFAIL);
	}

	switch (table_lookup(table, NULL, username, K_USERINFO, &lk)) {
	case -1:
		log_warnx("warn: failure during userinfo lookup %s:%s",
		    tablename, username);
		return (LKA_TEMPFAIL);
	case 0:
		return (LKA_PERMFAIL);
	default:
		*res = lk.userinfo;
		return (LKA_OK);
	}
}

static int
lka_addrname(const char *tablename, const struct sockaddr *sa,
    struct addrname *res)
{
	struct table	*table;
	union lookup	 lk;
	const char	*source;

	source = sa_to_text(sa);

	log_debug("debug: lka: helo %s:%s", tablename, source);
	table = table_find(env, tablename, NULL);
	if (table == NULL) {
		log_warnx("warn: cannot find helo table %s", tablename);
		return (LKA_TEMPFAIL);
	}

	switch (table_lookup(table, NULL, source, K_ADDRNAME, &lk)) {
	case -1:
		log_warnx("warn: failure during helo lookup %s:%s",
		    tablename, source);
		return (LKA_TEMPFAIL);
	case 0:
		return (LKA_PERMFAIL);
	default:
		*res = lk.addrname;
		return (LKA_OK);
	}
}

static int
lka_mailaddrmap(const char *tablename, const char *username, const struct mailaddr *maddr)
{
	struct table	       *table;
	struct maddrnode       *mn;
	union lookup		lk;
	int			found;

	log_debug("debug: lka: mailaddrmap %s:%s", tablename, username);
	table = table_find(env, tablename, NULL);
	if (table == NULL) {
		log_warnx("warn: cannot find mailaddrmap table %s", tablename);
		return (LKA_TEMPFAIL);
	}

	switch (table_lookup(table, NULL, username, K_MAILADDRMAP, &lk)) {
	case -1:
		log_warnx("warn: failure during mailaddrmap lookup %s:%s",
		    tablename, username);
		return (LKA_TEMPFAIL);
	case 0:
		return (LKA_PERMFAIL);
	default:
		found = 0;
		TAILQ_FOREACH(mn, &lk.maddrmap->queue, entries) {
			if (!mailaddr_match(maddr, &mn->mailaddr))
				continue;
			found = 1;
			break;
		}
		maddrmap_free(lk.maddrmap);
		if (found)
			return (LKA_OK);
		return (LKA_PERMFAIL);
	}
	return (LKA_OK);
}

static int
lka_X509_verify(struct ca_vrfy_req_msg *vrfy,
    const char *CAfile, const char *CRLfile)
{
	X509			*x509;
	X509			*x509_tmp;
	STACK_OF(X509)		*x509_chain;
	const unsigned char    	*d2i;
	size_t			i;
	int			ret = 0;
	const char		*errstr;

	x509 = NULL;
	x509_tmp = NULL;
	x509_chain = NULL;

	d2i = vrfy->cert;
	if (d2i_X509(&x509, &d2i, vrfy->cert_len) == NULL) {
		x509 = NULL;
		goto end;
	}

	if (vrfy->n_chain) {
		x509_chain = sk_X509_new_null();
		for (i = 0; i < vrfy->n_chain; ++i) {
			d2i = vrfy->chain_cert[i];
			if (d2i_X509(&x509_tmp, &d2i, vrfy->chain_cert_len[i]) == NULL)
				goto end;
			sk_X509_insert(x509_chain, x509_tmp, i);
			x509_tmp = NULL;
		}
	}
	if (!ca_X509_verify(x509, x509_chain, CAfile, NULL, &errstr))
		log_debug("debug: lka: X509 verify: %s", errstr);
	else
		ret = 1;

end:
	X509_free(x509);
	X509_free(x509_tmp);
	if (x509_chain)
		sk_X509_pop_free(x509_chain, X509_free);

	return ret;
}

static void
lka_certificate_verify(enum imsg_type type, struct ca_vrfy_req_msg *req)
{
	lka_certificate_verify_resume(type, req);
}

static void
lka_certificate_verify_resume(enum imsg_type type, struct ca_vrfy_req_msg *req)
{
	struct ca_vrfy_resp_msg		resp;
	struct ca		       *sca;
	const char		       *cafile;
	size_t				i;

	resp.reqid = req->reqid;
	sca = dict_get(env->sc_ca_dict, req->name);
	if (sca == NULL)
		if (req->fallback)
			sca = dict_get(env->sc_ca_dict, "*");
	cafile = sca ? sca->ca_cert_file : CA_FILE;

	if (sca == NULL && !req->fallback)
		resp.status = CA_FAIL;
	else if (!lka_X509_verify(req, cafile, NULL))
		resp.status = CA_FAIL;
	else
		resp.status = CA_OK;

	m_compose(p_pony, type, 0, 0, -1, &resp,
	    sizeof resp);

	for (i = 0; i < req->n_chain; ++i)
		free(req->chain_cert[i]);
	free(req->chain_cert);
	free(req->chain_cert_len);
	free(req->cert);
	free(req);
}