1 #include "mailfront.h"
2 #include <string.h>
3 #include <cvm/facts.h>
4 #include <cvm/sasl.h>
5 #include <stdlib.h>
6 
7 static RESPONSE(authfail, 421, "4.3.0 Failed to initialize AUTH");
8 static RESPONSE(auth_already, 503, "5.5.1 You are already authenticated.");
9 static RESPONSE(authenticated, 235, "2.7.0 Authentication succeeded.");
10 
11 static struct sasl_auth saslauth = { .prefix = "334 " };
12 
13 static str auth_caps;
14 static int require_tls;
15 
enabled(void)16 static int enabled(void)
17 {
18   return (sasl_mechanisms != 0)
19     && (!require_tls
20 	|| (session_getnum("tls_state", 0) > 0));
21 }
22 
cmd_AUTH(str * param)23 static int cmd_AUTH(str* param)
24 {
25   int i;
26   if (session_getnum("authenticated", 0))
27     return respond(&resp_auth_already);
28   if ((i = sasl_auth1(&saslauth, param)) != 0) {
29     const char* msg = sasl_auth_msg(&i);
30     return respond_line(i, 1, msg, strlen(msg));
31   }
32   else {
33     session_setnum("authenticated", 1);
34     session_delstr("helo_domain");
35     session_setstr("auth_user", cvm_fact_username);
36     session_setnum("auth_uid", cvm_fact_userid);
37     session_setnum("auth_gid", cvm_fact_groupid);
38     if (cvm_fact_realname != 0)
39       session_setstr("auth_realname", cvm_fact_realname);
40     if (cvm_fact_domain != 0)
41       session_setstr("auth_domain", cvm_fact_domain);
42     if (cvm_fact_mailbox != 0)
43       session_setstr("auth_mailbox", cvm_fact_mailbox);
44     respond(&resp_authenticated);
45   }
46   return 1;
47 }
48 
49 static struct command commands[] = {
50   { "AUTH", .fn_enabled = enabled, .fn_hasparam = cmd_AUTH },
51   { .name = 0 }
52 };
53 
init(void)54 static const response* init(void)
55 {
56   require_tls = getenv("AUTH_REQUIRES_TLS") != 0;
57 
58   if (!sasl_auth_init(&saslauth))
59     return &resp_authfail;
60 
61   if (sasl_mechanisms != 0) {
62     switch (sasl_auth_caps(&auth_caps)) {
63     case 0: break;
64     case 1: break;
65     default:
66       return &resp_authfail;
67     }
68   }
69 
70   return 0;
71 }
72 
helo(str * hostname,str * capabilities)73 static const response* helo(str* hostname, str* capabilities)
74 {
75   if (enabled())
76     if (!str_cat(capabilities, &auth_caps)
77 	|| !str_catc(capabilities, '\n'))
78       return &resp_oom;
79   return 0;
80   (void)hostname;
81 }
82 
83 struct plugin plugin = {
84   .version = PLUGIN_VERSION,
85   .flags = 0,
86   .commands = commands,
87   .init = init,
88   .helo = helo,
89 };
90