generate State as ASCII to workaround Cisco bug
[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     (void) sprintf(state, "0x00");
398   }
399   pairadd(&request->reply->vps, pairmake("State", state, T_OP_EQ));
400   free(state);
401
402   /* Add the challenge to the reply. */
403   {
404     char *u_challenge;  /* challenge with addt'l presentation text */
405
406     u_challenge = rad_malloc(strlen(inst->chal_prompt) +
407                              OTP_MAX_CHALLENGE_LEN + 1);
408     (void) sprintf(u_challenge, inst->chal_prompt, challenge);
409     pairadd(&request->reply->vps,
410             pairmake("Reply-Message", u_challenge, T_OP_EQ));
411     free(u_challenge);
412   }
413
414   /*
415    * Mark the packet as an Access-Challenge packet.
416    * The server will take care of sending it to the user.
417    */
418   request->reply->code = PW_ACCESS_CHALLENGE;
419   DEBUG("rlm_otp: Sending Access-Challenge.");
420
421   /* TODO: support config-specific auth-type */
422   if (!auth_type_found)
423     pairadd(&request->config_items, pairmake("Auth-Type", "otp", T_OP_EQ));
424   return RLM_MODULE_HANDLED;
425 }
426
427
428 /* Verify the response entered by the user. */
429 static int
430 otp_authenticate(void *instance, REQUEST *request)
431 {
432   otp_option_t *inst = (otp_option_t *) instance;
433   const char *log_prefix = OTP_MODULE_NAME;
434
435   char *username;
436   int rc;
437   int resync = 0;       /* resync flag for async mode */
438
439   unsigned char challenge[OTP_MAX_CHALLENGE_LEN];       /* cf. authorize() */
440   VALUE_PAIR *add_vps = NULL;
441
442   struct otp_pwe_cmp_t data = {
443     .request            = request,
444     .inst               = inst,
445     .returned_vps       = &add_vps
446   };
447
448   challenge[0] = '\0';  /* initialize for otp_pw_valid() */
449
450   /* User-Name attribute required. */
451   if (!request->username) {
452     otp_log(OTP_LOG_AUTH,
453             "%s: %s: Attribute \"User-Name\" required for authentication.",
454             log_prefix, __func__);
455     return RLM_MODULE_INVALID;
456   }
457   username = request->username->vp_strvalue;
458
459   if ((data.pwattr = otp_pwe_present(request, log_prefix)) == 0) {
460     otp_log(OTP_LOG_AUTH, "%s: %s: Attribute \"User-Password\" "
461                           "or equivalent required for authentication.",
462             log_prefix, __func__);
463     return RLM_MODULE_INVALID;
464   }
465
466   /* Add a message to the auth log. */
467   pairadd(&request->packet->vps, pairmake("Module-Failure-Message",
468                                           OTP_MODULE_NAME, T_OP_EQ));
469   pairadd(&request->packet->vps, pairmake("Module-Success-Message",
470                                           OTP_MODULE_NAME, T_OP_EQ));
471
472   /* Retrieve the challenge (from State attribute). */
473   {
474     VALUE_PAIR  *vp;
475     unsigned char       *state;
476     unsigned char       *raw_state;
477     unsigned char       *rad_state;
478     int32_t             sflags = 0;     /* state flags           */
479     int32_t             then;           /* state timestamp       */
480     int                 e_length;       /* expected State length */
481
482     if ((vp = pairfind(request->packet->vps, PW_STATE)) != NULL) {
483       /* set expected State length */
484       if (inst->allow_async)
485         e_length += inst->chal_len * 2 + 8 + 8 + 32; /* see otp_gen_state() */
486       else
487         e_length = 1;
488
489       if (vp->length != e_length) {
490         otp_log(OTP_LOG_AUTH, "%s: %s: bad state for [%s]: length",
491                 log_prefix, __func__, username);
492         return RLM_MODULE_INVALID;
493       }
494
495       if (inst->allow_async) {
496         /*
497          * Verify the state.
498          */
499
500         /* ASCII decode */
501         rad_state = rad_malloc(e_length + 1);
502         (void) memcpy(rad_state, vp->vp_strvalue, vp->length);
503         rad_state[e_length] = '\0';
504         (void) otp_keystring2keyblock(rad_state, raw_state);
505         free(rad_state);
506         
507         /* extract data from State */
508         raw_state = rad_malloc(e_length / 2);
509         (void) memcpy(challenge, raw_state, inst->chal_len);
510         (void) memcpy(&sflags, raw_state + inst->chal_len, 4);
511         (void) memcpy(&then, raw_state + inst->chal_len + 4, 4);
512         free(raw_state);
513
514         /* generate new state from returned input data */
515         if (otp_gen_state(NULL, &state, challenge, inst->chal_len,
516                           sflags, then, hmac_key) != 0) {
517           otp_log(OTP_LOG_ERR, "%s: %s: failed to generate state",
518                   log_prefix, __func__);
519           return RLM_MODULE_FAIL;
520         }
521         /* compare generated state against returned state to verify hmac */
522         if (memcmp(state, vp->vp_strvalue, vp->length)) {
523           otp_log(OTP_LOG_AUTH, "%s: %s: bad state for [%s]: hmac",
524                   log_prefix, __func__, username);
525           free(state);
526           return RLM_MODULE_REJECT;
527         }
528         free(state);
529
530         /* State is valid, but check expiry. */
531         then = ntohl(then);
532         if (time(NULL) - then > inst->chal_delay) {
533           otp_log(OTP_LOG_AUTH, "%s: %s: bad state for [%s]: expired",
534                   log_prefix, __func__, username);
535           return RLM_MODULE_REJECT;
536         }
537         resync = ntohl(sflags) & 1;
538       } /* if (State should have been protected) */
539     } /* if (State present) */
540   } /* code block */
541
542   /* do it */
543   rc = otprc2rlmrc(otp_pw_valid(username, challenge, NULL, resync, inst,
544                                 otp_pwe_cmp, &data, log_prefix));
545
546   /* Handle any vps returned from otp_pwe_cmp(). */
547   if (rc == RLM_MODULE_OK) {
548     pairadd(&request->reply->vps, add_vps);
549   } else {
550     pairfree(&add_vps);
551   }
552   return rc;
553 }
554
555
556 /* per-instance destruction */
557 static int
558 otp_detach(void *instance)
559 {
560   otp_option_t *inst = (otp_option_t *) instance;
561
562   free(inst->pwdfile);
563   free(inst->lsmd_rp);
564   free(inst->chal_prompt);
565   free(inst->chal_req);
566   free(inst->resync_req);
567   free(instance);
568   /*
569    * Only the main thread instantiates and detaches instances,
570    * so this does not need mutex protection.
571    */
572   if (--ninstance == 0)
573     memset(hmac_key, 0, sizeof(hmac_key));
574
575   return 0;
576 }
577
578
579 /*
580  *      If the module needs to temporarily modify it's instantiation
581  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
582  *      The server will then take care of ensuring that the module
583  *      is single-threaded.
584  */
585 module_t rlm_otp = {
586   RLM_MODULE_INIT,
587   "otp",
588   RLM_TYPE_THREAD_SAFE,         /* type */
589   otp_instantiate,              /* instantiation */
590   otp_detach,                   /* detach */
591   {
592     otp_authenticate,           /* authentication */
593     otp_authorize,              /* authorization */
594     NULL,                       /* preaccounting */
595     NULL,                       /* accounting */
596     NULL,                       /* checksimul */
597     NULL,                       /* pre-proxy */
598     NULL,                       /* post-proxy */
599     NULL                        /* post-auth */
600   },
601 };