tidying: CCSS macro
[exim.git] / src / src / auths / cyrus_sasl.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) University of Cambridge 1995 - 2018 */
6 /* See the file NOTICE for conditions of use and distribution. */
7
8 /* This code was originally contributed by Matthew Byng-Maddick */
9
10 /* Copyright (c) A L Digital 2004 */
11
12 /* A generic (mechanism independent) Cyrus SASL authenticator. */
13
14
15 #include "../exim.h"
16
17
18 /* We can't just compile this code and allow the library mechanism to omit the
19 functions if they are not wanted, because we need to have the Cyrus SASL header
20 available for compiling. Therefore, compile these functions only if
21 AUTH_CYRUS_SASL is defined. However, some compilers don't like compiling empty
22 modules, so keep them happy with a dummy when skipping the rest. Make it
23 reference itself to stop picky compilers complaining that it is unused, and put
24 in a dummy argument to stop even pickier compilers complaining about infinite
25 loops. */
26
27 #ifndef AUTH_CYRUS_SASL
28 static void dummy(int x);
29 static void dummy2(int x) { dummy(x-1); }
30 static void dummy(int x) { dummy2(x-1); }
31 #else
32
33
34 #include <sasl/sasl.h>
35 #include "cyrus_sasl.h"
36
37 /* Options specific to the cyrus_sasl authentication mechanism. */
38
39 optionlist auth_cyrus_sasl_options[] = {
40   { "server_hostname",      opt_stringptr,
41       (void *)(offsetof(auth_cyrus_sasl_options_block, server_hostname)) },
42   { "server_mech",          opt_stringptr,
43       (void *)(offsetof(auth_cyrus_sasl_options_block, server_mech)) },
44   { "server_realm",         opt_stringptr,
45       (void *)(offsetof(auth_cyrus_sasl_options_block, server_realm)) },
46   { "server_service",       opt_stringptr,
47       (void *)(offsetof(auth_cyrus_sasl_options_block, server_service)) }
48 };
49
50 /* Size of the options list. An extern variable has to be used so that its
51 address can appear in the tables drtables.c. */
52
53 int auth_cyrus_sasl_options_count =
54   sizeof(auth_cyrus_sasl_options)/sizeof(optionlist);
55
56 /* Default private options block for the cyrus_sasl authentication method. */
57
58 auth_cyrus_sasl_options_block auth_cyrus_sasl_option_defaults = {
59   US"smtp",         /* server_service */
60   US"$primary_hostname", /* server_hostname */
61   NULL,             /* server_realm */
62   NULL              /* server_mech */
63 };
64
65
66 #ifdef MACRO_PREDEF
67
68 /* Dummy values */
69 void auth_cyrus_sasl_init(auth_instance *ablock) {}
70 int auth_cyrus_sasl_server(auth_instance *ablock, uschar *data) {return 0;}
71 int auth_cyrus_sasl_client(auth_instance *ablock, void * sx,
72   int timeout, uschar *buffer, int buffsize) {return 0;}
73 void auth_cyrus_sasl_version_report(FILE *f) {}
74
75 #else   /*!MACRO_PREDEF*/
76
77
78
79
80 /*************************************************
81 *          Initialization entry point            *
82 *************************************************/
83
84 /* Called for each instance, after its options have been read, to
85 enable consistency checks to be done, or anything else that needs
86 to be set up. */
87
88
89 /* Auxiliary function, passed in data to sasl_server_init(). */
90
91 static int
92 mysasl_config(void *context, const char *plugin_name, const char *option,
93       const char **result, unsigned int *len)
94 {
95 if (context && !strcmp(option, "mech_list"))
96   {
97   *result = context;
98   if (len) *len = strlen(*result);
99   return SASL_OK;
100   }
101 return SASL_FAIL;
102 }
103
104 /* Here's the real function */
105
106 void
107 auth_cyrus_sasl_init(auth_instance *ablock)
108 {
109 auth_cyrus_sasl_options_block *ob =
110   (auth_cyrus_sasl_options_block *)(ablock->options_block);
111 const uschar *list, *listptr, *buffer;
112 int rc, i;
113 unsigned int len;
114 rmark rs_point;
115 uschar *expanded_hostname;
116 char *realm_expanded;
117
118 sasl_conn_t *conn;
119 sasl_callback_t cbs[] = {
120   {SASL_CB_GETOPT, NULL, NULL },
121   {SASL_CB_LIST_END, NULL, NULL}};
122
123 /* default the mechanism to our "public name" */
124
125 if (!ob->server_mech) ob->server_mech = string_copy(ablock->public_name);
126
127 if (!(expanded_hostname = expand_string(ob->server_hostname)))
128   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator:  "
129       "couldn't expand server_hostname [%s]: %s",
130       ablock->name, ob->server_hostname, expand_string_message);
131
132 realm_expanded = NULL;
133 if (  ob->server_realm
134    && !(realm_expanded = CS expand_string(ob->server_realm)))
135   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator:  "
136       "couldn't expand server_realm [%s]: %s",
137       ablock->name, ob->server_realm, expand_string_message);
138
139 /* we're going to initialise the library to check that there is an
140 authenticator of type whatever mechanism we're using */
141
142 cbs[0].proc = (int(*)(void)) &mysasl_config;
143 cbs[0].context = ob->server_mech;
144
145 if ((rc = sasl_server_init(cbs, "exim")) != SASL_OK)
146   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator:  "
147       "couldn't initialise Cyrus SASL library.", ablock->name);
148
149 if ((rc = sasl_server_new(CS ob->server_service, CS expanded_hostname,
150                    realm_expanded, NULL, NULL, NULL, 0, &conn)) != SASL_OK)
151   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator:  "
152       "couldn't initialise Cyrus SASL server connection.", ablock->name);
153
154 if ((rc = sasl_listmech(conn, NULL, "", ":", "", CCSS &list, &len, &i)) != SASL_OK)
155   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator:  "
156       "couldn't get Cyrus SASL mechanism list.", ablock->name);
157
158 i = ':';
159 listptr = list;
160
161 HDEBUG(D_auth)
162   {
163   debug_printf("Initialised Cyrus SASL service=\"%s\" fqdn=\"%s\" realm=\"%s\"\n",
164       ob->server_service, expanded_hostname, realm_expanded);
165   debug_printf("Cyrus SASL knows mechanisms: %s\n", list);
166   }
167
168 /* the store_get / store_reset mechanism is hierarchical
169  the hierarchy is stored for us behind our back. This point
170  creates a hierarchy point for this function.  */
171
172 rs_point = store_mark();
173
174 /* loop until either we get to the end of the list, or we match the
175 public name of this authenticator */
176
177 while (  (buffer = string_nextinlist(&listptr, &i, NULL, 0))
178       && strcmpic(buffer,ob->server_mech) );
179
180 if (!buffer)
181   log_write(0, LOG_PANIC_DIE|LOG_CONFIG_FOR, "%s authenticator:  "
182       "Cyrus SASL doesn't know about mechanism %s.", ablock->name, ob->server_mech);
183
184 store_reset(rs_point);
185
186 HDEBUG(D_auth) debug_printf("Cyrus SASL driver %s: %s initialised\n", ablock->name, ablock->public_name);
187
188 /* make sure that if we get here then we're allowed to advertise. */
189 ablock->server = TRUE;
190
191 sasl_dispose(&conn);
192 sasl_done();
193 }
194
195 /*************************************************
196 *             Server entry point                 *
197 *************************************************/
198
199 /* For interface, see auths/README */
200
201 /* note, we don't care too much about memory allocation in this, because this is entirely
202 within a shortlived child */
203
204 int
205 auth_cyrus_sasl_server(auth_instance *ablock, uschar *data)
206 {
207 auth_cyrus_sasl_options_block *ob =
208   (auth_cyrus_sasl_options_block *)(ablock->options_block);
209 uschar *output, *out2, *input, *clear, *hname;
210 uschar *debug = NULL;   /* Stops compiler complaining */
211 sasl_callback_t cbs[] = {{SASL_CB_LIST_END, NULL, NULL}};
212 sasl_conn_t *conn;
213 char * realm_expanded = NULL;
214 int rc, firsttime = 1, clen, *negotiated_ssf_ptr = NULL, negotiated_ssf;
215 unsigned int inlen, outlen;
216
217 input = data;
218 inlen = Ustrlen(data);
219
220 HDEBUG(D_auth) debug = string_copy(data);
221
222 hname = expand_string(ob->server_hostname);
223 if (hname && ob->server_realm)
224   realm_expanded = CS expand_string(ob->server_realm);
225 if (!hname  ||  !realm_expanded  && ob->server_realm)
226   {
227   auth_defer_msg = expand_string_message;
228   return DEFER;
229   }
230
231 if (inlen)
232   {
233   if ((clen = b64decode(input, &clear)) < 0)
234     return BAD64;
235   input = clear;
236   inlen = clen;
237   }
238
239 if ((rc = sasl_server_init(cbs, "exim")) != SASL_OK)
240   {
241   auth_defer_msg = US"couldn't initialise Cyrus SASL library";
242   return DEFER;
243   }
244
245 rc = sasl_server_new(CS ob->server_service, CS hname, realm_expanded, NULL,
246   NULL, NULL, 0, &conn);
247
248 HDEBUG(D_auth)
249   debug_printf("Initialised Cyrus SASL server connection; service=\"%s\" fqdn=\"%s\" realm=\"%s\"\n",
250       ob->server_service, hname, realm_expanded);
251
252 if (rc != SASL_OK )
253   {
254   auth_defer_msg = US"couldn't initialise Cyrus SASL connection";
255   sasl_done();
256   return DEFER;
257   }
258
259 if (tls_in.cipher)
260   {
261   if ((rc = sasl_setprop(conn, SASL_SSF_EXTERNAL, (sasl_ssf_t *) &tls_in.bits)) != SASL_OK)
262     {
263     HDEBUG(D_auth) debug_printf("Cyrus SASL EXTERNAL SSF set %d failed: %s\n",
264         tls_in.bits, sasl_errstring(rc, NULL, NULL));
265     auth_defer_msg = US"couldn't set Cyrus SASL EXTERNAL SSF";
266     sasl_done();
267     return DEFER;
268     }
269   else
270     HDEBUG(D_auth) debug_printf("Cyrus SASL set EXTERNAL SSF to %d\n", tls_in.bits);
271
272   /*XXX Set channel-binding here with sasl_channel_binding_t / SASL_CHANNEL_BINDING
273   Unclear what the "name" element does though, ditto the "critical" flag. */
274   }
275 else
276   HDEBUG(D_auth) debug_printf("Cyrus SASL: no TLS, no EXTERNAL SSF set\n");
277
278 /* So sasl_setprop() documents non-shorted IPv6 addresses which is incredibly
279 annoying; looking at cyrus-imapd-2.3.x source, the IP address is constructed
280 with their iptostring() function, which just wraps
281 getnameinfo(..., NI_NUMERICHOST|NI_NUMERICSERV), which is equivalent to the
282 inet_ntop which we wrap in our host_ntoa() function.
283
284 So the docs are too strict and we shouldn't worry about :: contractions. */
285
286 /* Set properties for remote and local host-ip;port */
287 for (int i = 0; i < 2; ++i)
288   {
289   int propnum;
290   const uschar * label;
291   uschar * address_port;
292   const char *s_err;
293   socklen_t sslen;
294
295   if (i)
296     {
297     propnum = SASL_IPREMOTEPORT;
298     label = CUS"peer";
299     address_port = string_sprintf("%s;%d",
300                                   sender_host_address, sender_host_port);
301     }
302   else
303     {
304     propnum = SASL_IPLOCALPORT;
305     label = CUS"local";
306     address_port = string_sprintf("%s;%d", interface_address, interface_port);
307     }
308
309   if ((rc = sasl_setprop(conn, propnum, address_port)) != SASL_OK)
310     {
311     HDEBUG(D_auth)
312       {
313       s_err = sasl_errdetail(conn);
314       debug_printf("Failed to set %s SASL property: [%d] %s\n",
315           label, rc, s_err ? s_err : "<unknown reason>");
316       }
317     break;
318     }
319   HDEBUG(D_auth) debug_printf("Cyrus SASL set %s hostport to: %s\n",
320       label, address_port);
321   }
322
323 for (rc = SASL_CONTINUE; rc == SASL_CONTINUE; )
324   {
325   if (firsttime)
326     {
327     firsttime = 0;
328     HDEBUG(D_auth) debug_printf("Calling sasl_server_start(%s,\"%s\")\n", ob->server_mech, debug);
329     rc = sasl_server_start(conn, CS ob->server_mech, inlen ? CS input : NULL, inlen,
330            CCSS &output, &outlen);
331     }
332   else
333     {
334     /* make sure that we have a null-terminated string */
335     out2 = string_copyn(output, outlen);
336
337     if ((rc = auth_get_data(&input, out2, outlen)) != OK)
338       {
339       /* we couldn't get the data, so free up the library before
340       returning whatever error we get */
341       sasl_dispose(&conn);
342       sasl_done();
343       return rc;
344       }
345     inlen = Ustrlen(input);
346
347     HDEBUG(D_auth) debug = string_copy(input);
348     if (inlen)
349       {
350       if ((clen = b64decode(input, &clear)) < 0)
351        {
352        sasl_dispose(&conn);
353        sasl_done();
354        return BAD64;
355        }
356       input = clear;
357       inlen = clen;
358       }
359
360     HDEBUG(D_auth) debug_printf("Calling sasl_server_step(\"%s\")\n", debug);
361     rc = sasl_server_step(conn, CS input, inlen, CCSS &output, &outlen);
362     }
363
364   if (rc == SASL_BADPROT)
365     {
366     sasl_dispose(&conn);
367     sasl_done();
368     return UNEXPECTED;
369     }
370   if (rc == SASL_CONTINUE)
371     continue;
372
373   /* Get the username and copy it into $auth1 and $1. The former is now the
374   preferred variable; the latter is the original variable. */
375
376   if ((sasl_getprop(conn, SASL_USERNAME, (const void **)(&out2))) != SASL_OK)
377     {
378     HDEBUG(D_auth)
379       debug_printf("Cyrus SASL library will not tell us the username: %s\n",
380           sasl_errstring(rc, NULL, NULL));
381     log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
382        "Cyrus SASL username fetch problem: %s", ablock->name, ob->server_mech,
383        sasl_errstring(rc, NULL, NULL));
384     sasl_dispose(&conn);
385     sasl_done();
386     return FAIL;
387     }
388   auth_vars[0] = expand_nstring[1] = string_copy(out2);
389   expand_nlength[1] = Ustrlen(out2);
390   expand_nmax = 1;
391
392   switch (rc)
393     {
394     case SASL_FAIL: case SASL_BUFOVER: case SASL_BADMAC: case SASL_BADAUTH:
395     case SASL_NOAUTHZ: case SASL_ENCRYPT: case SASL_EXPIRED:
396     case SASL_DISABLED: case SASL_NOUSER:
397       /* these are considered permanent failure codes */
398       HDEBUG(D_auth)
399         debug_printf("Cyrus SASL permanent failure %d (%s)\n", rc, sasl_errstring(rc, NULL, NULL));
400       log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
401          "Cyrus SASL permanent failure: %s", ablock->name, ob->server_mech,
402          sasl_errstring(rc, NULL, NULL));
403       sasl_dispose(&conn);
404       sasl_done();
405       return FAIL;
406
407     case SASL_NOMECH:
408       /* this is a temporary failure, because the mechanism is not
409       available for this user. If it wasn't available at all, we
410       shouldn't have got here in the first place...  */
411
412       HDEBUG(D_auth)
413         debug_printf("Cyrus SASL temporary failure %d (%s)\n", rc, sasl_errstring(rc, NULL, NULL));
414       auth_defer_msg =
415           string_sprintf("Cyrus SASL: mechanism %s not available", ob->server_mech);
416       sasl_dispose(&conn);
417       sasl_done();
418       return DEFER;
419
420     case SASL_OK:
421       HDEBUG(D_auth)
422         debug_printf("Cyrus SASL %s authentication succeeded for %s\n",
423             ob->server_mech, auth_vars[0]);
424
425       if ((rc = sasl_getprop(conn, SASL_SSF, (const void **)(&negotiated_ssf_ptr)))!= SASL_OK)
426         {
427         HDEBUG(D_auth)
428           debug_printf("Cyrus SASL library will not tell us the SSF: %s\n",
429               sasl_errstring(rc, NULL, NULL));
430         log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
431             "Cyrus SASL SSF value not available: %s", ablock->name, ob->server_mech,
432             sasl_errstring(rc, NULL, NULL));
433         sasl_dispose(&conn);
434         sasl_done();
435         return FAIL;
436         }
437       negotiated_ssf = *negotiated_ssf_ptr;
438       HDEBUG(D_auth)
439         debug_printf("Cyrus SASL %s negotiated SSF: %d\n", ob->server_mech, negotiated_ssf);
440       if (negotiated_ssf > 0)
441         {
442         HDEBUG(D_auth)
443           debug_printf("Exim does not implement SASL wrapping (needed for SSF %d).\n", negotiated_ssf);
444         log_write(0, LOG_REJECT, "%s authenticator (%s):\n  "
445             "Cyrus SASL SSF %d not supported by Exim", ablock->name, ob->server_mech, negotiated_ssf);
446         sasl_dispose(&conn);
447         sasl_done();
448         return FAIL;
449         }
450
451       /* close down the connection, freeing up library's memory */
452       sasl_dispose(&conn);
453       sasl_done();
454
455       /* Expand server_condition as an authorization check */
456       return auth_check_serv_cond(ablock);
457
458     default:
459       /* Anything else is a temporary failure, and we'll let SASL print out
460        * the error string for us
461        */
462       HDEBUG(D_auth)
463         debug_printf("Cyrus SASL temporary failure %d (%s)\n", rc, sasl_errstring(rc, NULL, NULL));
464       auth_defer_msg =
465           string_sprintf("Cyrus SASL: %s", sasl_errstring(rc, NULL, NULL));
466       sasl_dispose(&conn);
467       sasl_done();
468       return DEFER;
469     }
470   }
471 /* NOTREACHED */
472 return 0;  /* Stop compiler complaints */
473 }
474
475 /*************************************************
476 *                Diagnostic API                  *
477 *************************************************/
478
479 void
480 auth_cyrus_sasl_version_report(FILE *f)
481 {
482 const char *implementation, *version;
483 sasl_version_info(&implementation, &version, NULL, NULL, NULL, NULL);
484 fprintf(f, "Library version: Cyrus SASL: Compile: %d.%d.%d\n"
485            "                             Runtime: %s [%s]\n",
486         SASL_VERSION_MAJOR, SASL_VERSION_MINOR, SASL_VERSION_STEP,
487         version, implementation);
488 }
489
490 /*************************************************
491 *              Client entry point                *
492 *************************************************/
493
494 /* For interface, see auths/README */
495
496 int
497 auth_cyrus_sasl_client(
498   auth_instance *ablock,                 /* authenticator block */
499   void * sx,                             /* connexction */
500   int timeout,                           /* command timeout */
501   uschar *buffer,                        /* for reading response */
502   int buffsize)                          /* size of buffer */
503 {
504 /* We don't support clients (yet) in this implementation of cyrus_sasl */
505 return FAIL;
506 }
507
508 #endif   /*!MACRO_PREDEF*/
509 #endif  /* AUTH_CYRUS_SASL */
510
511 /* End of cyrus_sasl.c */