eb79a677d1e878bbff163fb83696a2bf331b6b2c
[freeradius.git] / src / modules / rlm_otp / otp_hotp.c
1 /*
2  * otp_hotp.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 2005 TRI-D Systems, Inc.
20  */
21
22 #include <openssl/hmac.h>
23
24 #include "otp.h"
25
26 static const char rcsid[] = "$Id$";
27
28
29 /*
30  * This implements HOTP per draft-mraihi-oath-hmac-otp-04.txt, for Digit = 6.
31  *
32  * The HOTP algorithm is:
33  * 1. HS = HMAC-SHA-1(K, C)
34  *    Take the SHA-1 HMAC of the key (K) and counter (C).
35  * 2. S = DT(HS)
36  *    Take the "Dynamic Truncation" of the HMAC.
37  * 3. HOTP = StToNum(S) % 10^Digit
38  *    Take the modulus of S as a bigendian integer.
39  *
40  * Returns 0 on success, -1 on failure.  output is the ASCII HOTP on success.
41  */
42 int
43 otp_hotp_mac(const unsigned char counter[8], unsigned char output[7],
44              const unsigned char keyblock[OTP_MAX_KEY_LEN], size_t key_len,
45              const char *log_prefix)
46 {
47   unsigned char hmac[EVP_MAX_MD_SIZE];  /* >=20 */
48   int hmac_len = 0;
49   uint32_t dbc;         /* "dynamic binary code" from HOTP draft */
50
51   /* 1. hmac */
52   if (!HMAC(EVP_sha1(), keyblock, key_len, counter, 8, hmac, &hmac_len) ||
53       hmac_len != 20) {
54     otp_log(OTP_LOG_ERR, "%s: %s: HMAC failed", log_prefix, __func__);
55     return -1;
56   }
57
58   /* 2. the truncate step is unnecessarily complex */
59   {
60     int offset;
61
62     offset = hmac[19] & 0x0F;
63     /* we can't just cast hmac[offset] because of alignment and endianness */
64     dbc = (hmac[offset] & 0x7F) << 24 |
65           hmac[offset + 1]      << 16 |
66           hmac[offset + 2]      << 8  |
67           hmac[offset + 3];
68   }
69
70   /* 3. int conversion and modulus (as string) */
71   (void) sprintf(output, "%06lu", dbc % 1000000L);
72
73   return 0;
74 }