1 /+
2 MIT License
3 Copyright (c) 2020 Andrea Manzini
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18 SOFTWARE.
19 +/
20 
21 module gauthenticator;
22 
23 import std.digest.hmac : HMAC;
24 import std.digest.sha : SHA1,toHexString;
25 import std.bitmanip : nativeToBigEndian,bigEndianToNative;
26 import std.format : format;
27 
28 // code adapted from https://github.com/tilaklodha/google-authenticator
29 
30 /// HMAC-based One Time Password(HOTP)
31 public string getHOTPToken(const string secret, const ulong interval)
32 {
33     //secret is a base32 encoded string. Converts to a byte array
34     auto key = base32decode(secret);
35     //Signing the value using HMAC-SHA1 Algorithm
36     auto hm = HMAC!SHA1(key);
37     hm.put(nativeToBigEndian(interval));
38     ubyte[20] sha1sum = hm.finish();
39 	// We're going to use a subset of the generated hash.
40 	// Using the last nibble (half-byte) to choose the index to start from.
41 	// This number is always appropriate as it's maximum decimal 15, the hash will
42 	// have the maximum index 19 (20 bytes of SHA1) and we need 4 bytes.    
43     const int offset = (sha1sum[19] & 15);
44     ubyte[4] h = sha1sum[offset .. offset + 4];
45 	//Ignore most significant bits as per RFC 4226.
46 	//Takes division from one million to generate a remainder less than < 7 digits    
47     const uint h12 = (bigEndianToNative!uint(h) & 0x7fffffff) % 1_000_000;
48     return format("%06d",h12);
49 }
50 
51 /// Time-based One Time Password(TOTP)
52 public string getTOTPToken(const string secret)
53 {
54     //The TOTP token is just a HOTP token seeded with every 30 seconds.
55     import std.datetime : Clock;
56     immutable ulong interval = Clock.currTime().toUnixTime() / 30;
57     return getHOTPToken(secret, interval);
58 }
59 
60 //RFC 4648 base32 implementation
61 private ubyte[] base32decode(const string message)
62 {
63     int buffer = 0;
64     int bitsLeft = 0;
65     ubyte[] result;
66     for (int i = 0; i < message.length; i++)
67     {
68         int ch = message[i];
69         if (ch == '=')
70             break;
71         if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-')
72         {
73             continue;
74         }
75         buffer = buffer << 5;
76 
77         // Deal with commonly mistyped characters
78         if (ch == '0')
79         {
80             ch = 'O';
81         }
82         else if (ch == '1')
83         {
84             ch = 'L';
85         }
86         else if (ch == '8')
87         {
88             ch = 'B';
89         }
90 
91         // Look up one base32 digit
92         if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
93         {
94             ch = (ch & 0x1F) - 1;
95         }
96         else if (ch >= '2' && ch <= '7')
97         {
98             ch -= ('2' - 26);
99         }
100 
101         buffer |= ch;
102         bitsLeft += 5;
103         if (bitsLeft >= 8)
104         {
105             const c = (buffer >> (bitsLeft - 8));
106             result ~= cast(byte)(c & 0xff);
107             bitsLeft -= 8;
108         }
109 
110     }
111     return result;
112 
113 }
114 //test for base32 decoder
115 unittest
116 {
117     auto expected = cast(byte[])("FOOBAR");
118     auto message = base32decode("IZHU6QSBKI");
119     assert(message == expected);
120     expected = cast(byte[])("12345test");
121     message = base32decode("GEZDGNBVORSXG5A=");
122     assert(message == expected);
123 }
124 
125 // test for SHA1 func
126 unittest
127 {
128     SHA1 hash;
129     hash.start();
130     auto data = cast(ubyte[])"abc";
131     hash.put(data);
132     ubyte[20] result = hash.finish();
133     assert(toHexString(result) == "A9993E364706816ABA3E25717850C26C9CD0D89D");
134 }
135 
136 //final test for OTP functionality (with a fixed time)
137 unittest
138 {
139     auto secret = "dummySECRETdummy";
140     auto interval = ulong(50_780_342);  // D allows underscore in numbers to improve readability
141     const otp = "971294";
142     assert(otp == getHOTPToken(secret, interval));
143 }