otp_authenticate(): malloc raw_state before using it
[freeradius.git] / src / modules / rlm_otp / otp_rlm.c
1 /*
2  * otp_rlm.c
3  * $Id$
4  *
5  *   This program is free software; you can redistribute it and/or modify
6  *   it under the terms of the GNU General Public License as published by
7  *   the Free Software Foundation; either version 2 of the License, or
8  *   (at your option) any later version.
9  *
10  *   This program is distributed in the hope that it will be useful,
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *   GNU General Public License for more details.
14  *
15  *   You should have received a copy of the GNU General Public License
16  *   along with this program; if not, write to the Free Software
17  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  * Copyright 2000,2001,2002  The FreeRADIUS server project
20  * Copyright 2001,2002  Google, Inc.
21  * Copyright 2005,2006 TRI-D Systems, Inc.
22  */
23
24 /*
25  * STRONG WARNING SECTION:
26  *
27  * ANSI X9.9 has been withdrawn as a standard, due to the weakness of DES.
28  * An attacker can learn the token's secret by observing two
29  * challenge/response pairs.  See ANSI document X9 TG-24-1999
30  * <URL:http://www.x9.org/docs/TG24_1999.pdf>.
31  *
32  * Please read the accompanying docs.
33  */
34
35
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42 #include <time.h>
43 #include <netinet/in.h> /* htonl(), ntohl() */
44
45 #include "otp.h"
46 #ifdef FREERADIUS
47 #include <freeradius-devel/modules.h>
48 #endif
49
50 static const char rcsid[] = "$Id$";
51
52 /* Global data */
53 static unsigned char hmac_key[16];      /* to protect State attribute  */
54 static int ninstance = 0;               /* #instances, for global init */
55
56 /* A mapping of configuration file names to internal variables. */
57 static const CONF_PARSER module_config[] = {
58   { "pwdfile", PW_TYPE_STRING_PTR, offsetof(otp_option_t, pwdfile),
59     NULL, OTP_PWDFILE },
60   { "lsmd_rp", PW_TYPE_STRING_PTR, offsetof(otp_option_t, lsmd_rp),
61     NULL, OTP_LSMD_RP },
62   { "challenge_prompt", PW_TYPE_STRING_PTR,offsetof(otp_option_t, chal_prompt),
63     NULL, OTP_CHALLENGE_PROMPT },
64   { "challenge_length", PW_TYPE_INTEGER, offsetof(otp_option_t, chal_len),
65     NULL, "6" },
66   { "challenge_delay", PW_TYPE_INTEGER, offsetof(otp_option_t, chal_delay),
67     NULL, "30" },
68   { "softfail", PW_TYPE_INTEGER, offsetof(otp_option_t, softfail),
69     NULL, "5" },
70   { "hardfail", PW_TYPE_INTEGER, offsetof(otp_option_t, hardfail),
71     NULL, "0" },
72   { "allow_sync", PW_TYPE_BOOLEAN, offsetof(otp_option_t, allow_sync),
73     NULL, "yes" },
74   { "fast_sync", PW_TYPE_BOOLEAN, offsetof(otp_option_t, fast_sync),
75     NULL, "yes" },
76   { "allow_async", PW_TYPE_BOOLEAN, offsetof(otp_option_t, allow_async),
77     NULL, "no" },
78   { "challenge_req", PW_TYPE_STRING_PTR, offsetof(otp_option_t, chal_req),
79     NULL, OTP_CHALLENGE_REQ },
80   { "resync_req", PW_TYPE_STRING_PTR, offsetof(otp_option_t, resync_req),
81     NULL, OTP_RESYNC_REQ },
82   { "prepend_pin", PW_TYPE_BOOLEAN, offsetof(otp_option_t, prepend_pin),
83     NULL, "yes" },
84   { "ewindow_size", PW_TYPE_INTEGER, offsetof(otp_option_t, ewindow_size),
85     NULL, "0" },
86   { "rwindow_size", PW_TYPE_INTEGER, offsetof(otp_option_t, rwindow_size),
87     NULL, "0" },
88   { "rwindow_delay", PW_TYPE_INTEGER, offsetof(otp_option_t, rwindow_delay),
89     NULL, "60" },
90   { "mschapv2_mppe", PW_TYPE_INTEGER,
91     offsetof(otp_option_t, mschapv2_mppe_policy), NULL, "2" },
92   { "mschapv2_mppe_bits", PW_TYPE_INTEGER,
93     offsetof(otp_option_t, mschapv2_mppe_types), NULL, "2" },
94   { "mschap_mppe", PW_TYPE_INTEGER,
95     offsetof(otp_option_t, mschap_mppe_policy), NULL, "2" },
96   { "mschap_mppe_bits", PW_TYPE_INTEGER,
97     offsetof(otp_option_t, mschap_mppe_types), NULL, "2" },
98
99   { "debug", PW_TYPE_BOOLEAN, offsetof(otp_option_t, debug),
100     NULL, "no" },
101
102   { NULL, -1, 0, NULL, NULL }           /* end the list */
103 };
104
105
106 /* transform otp_pw_valid() return code into an rlm return code */
107 static int
108 otprc2rlmrc(int rc)
109 {
110   switch (rc) {
111     case OTP_RC_OK:                     return RLM_MODULE_OK;
112     case OTP_RC_USER_UNKNOWN:           return RLM_MODULE_REJECT;
113     case OTP_RC_AUTHINFO_UNAVAIL:       return RLM_MODULE_REJECT;
114     case OTP_RC_AUTH_ERR:               return RLM_MODULE_REJECT;
115     case OTP_RC_MAXTRIES:               return RLM_MODULE_USERLOCK;
116     case OTP_RC_SERVICE_ERR:            return RLM_MODULE_FAIL;
117     default:                            return RLM_MODULE_FAIL;
118   }
119 }
120
121
122 /* per-instance initialization */
123 static int
124 otp_instantiate(CONF_SECTION *conf, void **instance)
125 {
126   const char *log_prefix = OTP_MODULE_NAME;
127   otp_option_t *opt;
128   char *p;
129
130   /* Set up a storage area for instance data. */
131   opt = rad_malloc(sizeof(*opt));
132   (void) memset(opt, 0, sizeof(*opt));
133
134   /* If the configuration parameters can't be parsed, then fail. */
135   if (cf_section_parse(conf, opt, module_config) < 0) {
136     free(opt);
137     return -1;
138   }
139
140   /* Onetime initialization. */
141   if (!ninstance) {
142     /* Generate a random key, used to protect the State attribute. */
143     if (otp_get_random(-1, hmac_key, sizeof(hmac_key), log_prefix) == -1) {
144       otp_log(OTP_LOG_ERR, "%s: %s: failed to obtain random data for hmac_key",
145               log_prefix, __func__);
146       free(opt);
147       return -1;
148     }
149
150     /* Initialize the passcode encoding/checking functions. */
151     otp_pwe_init();
152
153     /*
154      * Don't do this again.
155      * Only the main thread instantiates and detaches instances,
156      * so this does not need mutex protection.
157      */
158     ninstance++;
159   }
160
161   /* Verify ranges for those vars that are limited. */
162   if ((opt->chal_len < 5) || (opt->chal_len > OTP_MAX_CHALLENGE_LEN)) {
163     opt->chal_len = 6;
164     otp_log(OTP_LOG_ERR,
165             "%s: %s: invalid challenge_length, range 5-%d, using default of 6",
166             log_prefix, __func__, OTP_MAX_CHALLENGE_LEN);
167   }
168
169   /* Enforce a single "%" sequence, which must be "%s" */
170   p = strchr(opt->chal_prompt, '%');
171   if ((p == NULL) || (p != strrchr(opt->chal_prompt, '%')) ||
172       strncmp(p,"%s",2)) {
173     free(opt->chal_prompt);
174     opt->chal_prompt = strdup(OTP_CHALLENGE_PROMPT);
175     otp_log(OTP_LOG_ERR,
176             "%s: %s: invalid challenge_prompt, using default of \"%s\"",
177             log_prefix, __func__, OTP_CHALLENGE_PROMPT);
178   }
179
180   if (opt->softfail < 0) {
181     opt->softfail = 5;
182     otp_log(OTP_LOG_ERR, "%s: %s: softfail must be at least 1 "
183                          "(or 0 == infinite), using default of 5",
184             log_prefix, __func__);
185   }
186
187   if (opt->hardfail < 0) {
188     opt->hardfail = 0;
189     otp_log(OTP_LOG_ERR, "%s: %s: hardfail must be at least 1 "
190                          "(or 0 == infinite), using default of 0",
191             log_prefix, __func__);
192   }
193
194   if (!opt->hardfail && opt->hardfail <= opt->softfail) {
195     /*
196      * This is noise if the admin leaves softfail alone, so it gets
197      * the default value of 5, and sets hardfail <= to that ... but
198      * in practice that will never happen.  Anyway, it is easily
199      * overcome with a softfail setting of 0.
200      *
201      * This is because we can't tell the difference between a default
202      * [softfail] value and an admin-configured one.
203      */
204     otp_log(OTP_LOG_ERR, "%s: %s: hardfail (%d) is less than softfail (%d), "
205                          "effectively disabling softfail",
206             log_prefix, __func__, opt->hardfail, opt->softfail);
207   }
208
209   if (opt->fast_sync && !opt->allow_sync) {
210     opt->fast_sync = 0;
211     otp_log(OTP_LOG_ERR, "%s: %s: fast_sync is yes, but allow_sync is no; "
212                          "disabling fast_sync",
213             log_prefix, __func__);
214   }
215
216   if (!opt->allow_sync && !opt->allow_async) {
217     otp_log(OTP_LOG_ERR,
218             "%s: %s: at least one of {allow_async, allow_sync} must be set",
219             log_prefix, __func__);
220     free(opt);
221     return -1;
222   }
223
224   if ((opt->ewindow_size > OTP_MAX_EWINDOW_SIZE) ||
225     (opt->ewindow_size < 0)) {
226     opt->ewindow_size = 0;
227     otp_log(OTP_LOG_ERR, "%s: %s: max ewindow_size is %d, using default of 0",
228             log_prefix, __func__, OTP_MAX_EWINDOW_SIZE);
229   }
230
231   if (opt->rwindow_size && (opt->rwindow_size < opt->ewindow_size)) {
232     opt->rwindow_size = 0;
233     otp_log(OTP_LOG_ERR, "%s: %s: rwindow_size must be at least as large as "
234                          "ewindow_size, using default of 0",
235             log_prefix, __func__);
236   }
237
238   if (opt->rwindow_size && !opt->rwindow_delay) {
239     opt->rwindow_size = 0;
240     otp_log(OTP_LOG_ERR, "%s: %s: rwindow_size is non-zero, "
241                          "but rwindow_delay is zero; disabling rwindow",
242             log_prefix, __func__);
243   }
244
245   if ((opt->mschapv2_mppe_policy > 2) || (opt->mschapv2_mppe_policy < 0)) {
246     opt->mschapv2_mppe_policy = 2;
247     otp_log(OTP_LOG_ERR,
248             "%s: %s: invalid value for mschapv2_mppe, using default of 2",
249             log_prefix, __func__);
250   }
251
252   if ((opt->mschapv2_mppe_types > 2) || (opt->mschapv2_mppe_types < 0)) {
253     opt->mschapv2_mppe_types = 2;
254     otp_log(OTP_LOG_ERR,
255             "%s: %s: invalid value for mschapv2_mppe_bits, using default of 2",
256             log_prefix, __func__);
257   }
258
259   if ((opt->mschap_mppe_policy > 2) || (opt->mschap_mppe_policy < 0)) {
260     opt->mschap_mppe_policy = 2;
261     otp_log(OTP_LOG_ERR,
262             "%s: %s: invalid value for mschap_mppe, using default of 2",
263             log_prefix, __func__);
264   }
265
266   if (opt->mschap_mppe_types != 2) {
267     opt->mschap_mppe_types = 2;
268     otp_log(OTP_LOG_ERR,
269             "%s: %s: invalid value for mschap_mppe_bits, using default of 2",
270             log_prefix, __func__);
271   }
272
273   /* set the instance name (for use with authorize()) */
274   opt->name = cf_section_name2(conf);
275   if (!opt->name)
276     opt->name = cf_section_name1(conf);
277   if (!opt->name) {
278     otp_log(OTP_LOG_CRIT, "%s: %s: no instance name (this can't happen)",
279             log_prefix, __func__);
280     free(opt);
281     return -1;
282   }
283
284   /* set debug opt for portable debug output (see DEBUG definition) */
285   if (debug_flag)
286     opt->debug = 1;
287
288   *instance = opt;
289   return 0;
290 }
291
292
293 /* Generate a challenge to be presented to the user. */
294 static int
295 otp_authorize(void *instance, REQUEST *request)
296 {
297   otp_option_t *inst = (otp_option_t *) instance;
298   const char *log_prefix = OTP_MODULE_NAME;
299
300   char challenge[OTP_MAX_CHALLENGE_LEN + 1];    /* +1 for '\0' terminator */
301   char *state;
302   int auth_type_found;
303   int32_t sflags = 0; /* flags for state */
304
305   struct otp_pwe_cmp_t data = {
306     .request            = request,
307     .inst               = inst,
308     .returned_vps       = NULL
309   };
310
311   /* Early exit if Auth-Type != inst->name */
312   {
313     VALUE_PAIR *vp;
314
315     auth_type_found = 0;
316     if ((vp = pairfind(request->config_items, PW_AUTHTYPE)) != NULL) {
317       auth_type_found = 1;
318       if (strcmp(vp->vp_strvalue, inst->name))
319         return RLM_MODULE_NOOP;
320     }
321   }
322
323   /* The State attribute will be present if this is a response. */
324   if (pairfind(request->packet->vps, PW_STATE) != NULL) {
325     DEBUG("rlm_otp: autz: Found response to Access-Challenge");
326     return RLM_MODULE_OK;
327   }
328
329   /* User-Name attribute required. */
330   if (!request->username) {
331     otp_log(OTP_LOG_AUTH,
332             "%s: %s: Attribute \"User-Name\" required for authentication.",
333             log_prefix, __func__);
334     return RLM_MODULE_INVALID;
335   }
336
337   if ((data.pwattr = otp_pwe_present(request, log_prefix)) == 0) {
338     otp_log(OTP_LOG_AUTH, "%s: %s: Attribute \"User-Password\" "
339                           "or equivalent required for authentication.",
340             log_prefix, __func__);
341     return RLM_MODULE_INVALID;
342   }
343
344   /* fast_sync mode (challenge only if requested) */
345   if (inst->fast_sync) {
346     if ((!otp_pwe_cmp(&data, inst->resync_req, log_prefix) &&
347         /* Set a bit indicating resync */ (sflags |= htonl(1))) ||
348         !otp_pwe_cmp(&data, inst->chal_req, log_prefix)) {
349       /*
350        * Generate a challenge if requested.  Note that we do this
351        * even if configuration doesn't allow async mode.
352        */
353       DEBUG("rlm_otp: autz: fast_sync challenge requested");
354       goto gen_challenge;
355
356     } else {
357       /* Otherwise, this is the token sync response. */
358       if (!auth_type_found)
359         pairadd(&request->config_items, pairmake("Auth-Type", "otp", T_OP_EQ));
360         return RLM_MODULE_OK;
361
362     }
363   } /* if (fast_sync && card supports sync mode) */
364
365 gen_challenge:
366   /* Set the resync bit by default if the user can't choose. */
367   if (!inst->fast_sync)
368     sflags |= htonl(1);
369
370   /* Generate a random challenge. */
371   if (otp_async_challenge(-1, challenge, inst->chal_len, log_prefix) == -1) {
372     otp_log(OTP_LOG_ERR, "%s: %s: failed to obtain random challenge",
373             log_prefix, __func__);
374     return RLM_MODULE_FAIL;
375   }
376
377   /*
378    * Create the State attribute, which will be returned to us along with
379    * the response.  We will need this to verify the response.  It must
380    * be hmac protected to prevent insertion of arbitrary State by an
381    * inside attacker.  If we won't actually use the State (server config
382    * doesn't allow async), we just use a trivial State.  We always create
383    * at least a trivial State, so otp_authorize() can quickly pass on to
384    * otp_authenticate().
385    */
386   if (inst->allow_async) {
387     int32_t now = htonl(time(NULL));    /* low-order 32 bits on LP64 */
388
389     if (otp_gen_state(&state, NULL, challenge, inst->chal_len, sflags,
390                       now, hmac_key) != 0) {
391       otp_log(OTP_LOG_ERR, "%s: %s: failed to generate state",
392               log_prefix, __func__);
393       return RLM_MODULE_FAIL;
394     }
395   } else {
396     state = rad_malloc(5);
397     /* a non-NUL byte, so that Cisco (see otp_gen_state()) returns it */
398     (void) sprintf(state, "0x01");
399   }
400   pairadd(&request->reply->vps, pairmake("State", state, T_OP_EQ));
401   free(state);
402
403   /* Add the challenge to the reply. */
404   {
405     char *u_challenge;  /* challenge with addt'l presentation text */
406
407     u_challenge = rad_malloc(strlen(inst->chal_prompt) +
408                              OTP_MAX_CHALLENGE_LEN + 1);
409     (void) sprintf(u_challenge, inst->chal_prompt, challenge);
410     pairadd(&request->reply->vps,
411             pairmake("Reply-Message", u_challenge, T_OP_EQ));
412     free(u_challenge);
413   }
414
415   /*
416    * Mark the packet as an Access-Challenge packet.
417    * The server will take care of sending it to the user.
418    */
419   request->reply->code = PW_ACCESS_CHALLENGE;
420   DEBUG("rlm_otp: Sending Access-Challenge.");
421
422   /* TODO: support config-specific auth-type */
423   if (!auth_type_found)
424     pairadd(&request->config_items, pairmake("Auth-Type", "otp", T_OP_EQ));
425   return RLM_MODULE_HANDLED;
426 }
427
428
429 /* Verify the response entered by the user. */
430 static int
431 otp_authenticate(void *instance, REQUEST *request)
432 {
433   otp_option_t *inst = (otp_option_t *) instance;
434   const char *log_prefix = OTP_MODULE_NAME;
435
436   char *username;
437   int rc;
438   int resync = 0;       /* resync flag for async mode */
439
440   unsigned char challenge[OTP_MAX_CHALLENGE_LEN];       /* cf. authorize() */
441   VALUE_PAIR *add_vps = NULL;
442
443   struct otp_pwe_cmp_t data = {
444     .request            = request,
445     .inst               = inst,
446     .returned_vps       = &add_vps
447   };
448
449   challenge[0] = '\0';  /* initialize for otp_pw_valid() */
450
451   /* User-Name attribute required. */
452   if (!request->username) {
453     otp_log(OTP_LOG_AUTH,
454             "%s: %s: Attribute \"User-Name\" required for authentication.",
455             log_prefix, __func__);
456     return RLM_MODULE_INVALID;
457   }
458   username = request->username->vp_strvalue;
459
460   if ((data.pwattr = otp_pwe_present(request, log_prefix)) == 0) {
461     otp_log(OTP_LOG_AUTH, "%s: %s: Attribute \"User-Password\" "
462                           "or equivalent required for authentication.",
463             log_prefix, __func__);
464     return RLM_MODULE_INVALID;
465   }
466
467   /* Add a message to the auth log. */
468   pairadd(&request->packet->vps, pairmake("Module-Failure-Message",
469                                           OTP_MODULE_NAME, T_OP_EQ));
470   pairadd(&request->packet->vps, pairmake("Module-Success-Message",
471                                           OTP_MODULE_NAME, T_OP_EQ));
472
473   /* Retrieve the challenge (from State attribute). */
474   {
475     VALUE_PAIR  *vp;
476     unsigned char       *state;
477     unsigned char       *raw_state;
478     unsigned char       *rad_state;
479     int32_t             sflags = 0;     /* state flags           */
480     int32_t             then;           /* state timestamp       */
481     int                 e_length;       /* expected State length */
482
483     if ((vp = pairfind(request->packet->vps, PW_STATE)) != NULL) {
484       /* set expected State length */
485       if (inst->allow_async)
486         e_length = inst->chal_len * 2 + 8 + 8 + 32; /* see otp_gen_state() */
487       else
488         e_length = 1;
489
490       if (vp->length != e_length) {
491         otp_log(OTP_LOG_AUTH, "%s: %s: bad state for [%s]: length",
492                 log_prefix, __func__, username);
493         return RLM_MODULE_INVALID;
494       }
495
496       if (inst->allow_async) {
497         /*
498          * Verify the state.
499          */
500
501         rad_state = rad_malloc(e_length + 1);
502         raw_state = rad_malloc(e_length / 2);
503
504         /* ASCII decode */
505         (void) memcpy(rad_state, vp->vp_strvalue, vp->length);
506         rad_state[e_length] = '\0';
507         (void) otp_keystring2keyblock(rad_state, raw_state);
508         free(rad_state);
509         
510         /* extract data from State */
511         (void) memcpy(challenge, raw_state, inst->chal_len);
512         (void) memcpy(&sflags, raw_state + inst->chal_len, 4);
513         (void) memcpy(&then, raw_state + inst->chal_len + 4, 4);
514         free(raw_state);
515
516         /* generate new state from returned input data */
517         if (otp_gen_state(NULL, &state, challenge, inst->chal_len,
518                           sflags, then, hmac_key) != 0) {
519           otp_log(OTP_LOG_ERR, "%s: %s: failed to generate state",
520                   log_prefix, __func__);
521           return RLM_MODULE_FAIL;
522         }
523         /* compare generated state against returned state to verify hmac */
524         if (memcmp(state, vp->vp_strvalue, vp->length)) {
525           otp_log(OTP_LOG_AUTH, "%s: %s: bad state for [%s]: hmac",
526                   log_prefix, __func__, username);
527           free(state);
528           return RLM_MODULE_REJECT;
529         }
530         free(state);
531
532         /* State is valid, but check expiry. */
533         then = ntohl(then);
534         if (time(NULL) - then > inst->chal_delay) {
535           otp_log(OTP_LOG_AUTH, "%s: %s: bad state for [%s]: expired",
536                   log_prefix, __func__, username);
537           return RLM_MODULE_REJECT;
538         }
539         resync = ntohl(sflags) & 1;
540       } /* if (State should have been protected) */
541     } /* if (State present) */
542   } /* code block */
543
544   /* do it */
545   rc = otprc2rlmrc(otp_pw_valid(username, challenge, NULL, resync, inst,
546                                 otp_pwe_cmp, &data, log_prefix));
547
548   /* Handle any vps returned from otp_pwe_cmp(). */
549   if (rc == RLM_MODULE_OK) {
550     pairadd(&request->reply->vps, add_vps);
551   } else {
552     pairfree(&add_vps);
553   }
554   return rc;
555 }
556
557
558 /* per-instance destruction */
559 static int
560 otp_detach(void *instance)
561 {
562   otp_option_t *inst = (otp_option_t *) instance;
563
564   free(inst->pwdfile);
565   free(inst->lsmd_rp);
566   free(inst->chal_prompt);
567   free(inst->chal_req);
568   free(inst->resync_req);
569   free(instance);
570   /*
571    * Only the main thread instantiates and detaches instances,
572    * so this does not need mutex protection.
573    */
574   if (--ninstance == 0)
575     memset(hmac_key, 0, sizeof(hmac_key));
576
577   return 0;
578 }
579
580
581 /*
582  *      If the module needs to temporarily modify it's instantiation
583  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
584  *      The server will then take care of ensuring that the module
585  *      is single-threaded.
586  */
587 module_t rlm_otp = {
588   RLM_MODULE_INIT,
589   "otp",
590   RLM_TYPE_THREAD_SAFE,         /* type */
591   otp_instantiate,              /* instantiation */
592   otp_detach,                   /* detach */
593   {
594     otp_authenticate,           /* authentication */
595     otp_authorize,              /* authorization */
596     NULL,                       /* preaccounting */
597     NULL,                       /* accounting */
598     NULL,                       /* checksimul */
599     NULL,                       /* pre-proxy */
600     NULL,                       /* post-proxy */
601     NULL                        /* post-auth */
602   },
603 };