Merge pull request #2 from shtylman/master

complete rework of api and code cleanup
This commit is contained in:
Guy Halford-Thompson 2012-06-04 05:19:09 -07:00
commit 209e7020e8
8 changed files with 447 additions and 1110 deletions

7
.gitignore vendored
View File

@ -1,6 +1 @@
# OS generated files #
######################
.DS_Store
ehthumbs.db
Icon
Thumbs.db
node_modules

22
LICENSE Normal file
View File

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 Guy Halford-Thompson <guy@cach.me>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

312
Readme.md
View File

@ -1,260 +1,130 @@
# Node One Time Password library
Simple to use, fast, and with zero dependencies. The Node One Time Password library is fully compliant with [HOTP](http://tools.ietf.org/html/rfc4226) (counter based one time passwords) and [TOTP](http://tools.ietf.org/html/rfc6238) (time based one time passwords). It was designed to be used in conjunction with the [Google Authenticator](http://code.google.com/p/google-authenticator/) which has free apps for iOS, Android and BlackBerry.
Simple to use, fast, and with zero dependencies. The Node One Time Password library is fully compliant with [HOTP](http://tools.ietf.org/html/rfc4226) (counter based one time passwords) and [TOTP](http://tools.ietf.org/html/rfc6238) (time based one time passwords). It can be used in conjunction with the [Google Authenticator](http://code.google.com/p/google-authenticator/) which has free apps for iOS, Android and BlackBerry.
# Installation
Via npm
$ npm install notp
Or... since there are no dependencies, you can simply download the files in ./lib and then just require as normal
$ require('./lib/nopt');
```
npm install notp
```
# Usage
IMPORTANT: The NOTP library accepts ASCII strings as keys, but the Google Authenticator app uses base32 encoded strings. If you wish to use this library in conjunction with the Google Authenticator app, then you need to convert the keys to base32 before entering them into the Google Authenticator app. NOTP provides helper functions for this.
```javascript
var notp = require('notp');
var notp = require('notp'),
args = {};
//.... some initial login code, that receives the user details and TOTP / HOTP token
//.... some initial login code, that receives the TOTP / HTOP
// token from the user
args.K = 'TOTP key for user... could be stored in DB';
args.P = 'User supplied TOTP value';
var key = 'secret key for user... could be stored in DB';
var token = 'user supplied one time use token';
// Check TOTP is correct
notp.checkTOTP(
args,
function(err) { console.log('Oops, an error occured ' + err); },
function(login, sync) {
if(login) {
console.log('Token valid, sync value is ' + sync);
} else {
console.log('Token invalid');
}
}
);
// Check TOTP is correct (HOTP if hotp pass type)
var login = notp.totp.verify(token, key);
// invalid token if login is null
if (!login) {
return console.log('Token invalid');
}
// valid token
console.log('Token valid, sync value is %s', login.delta);
```
## Google Authenticator
[Google authenticator](https://code.google.com/p/google-authenticator/) requires that keys be base32 encoded before being used. This includes manual entry into the app as well as preparing a QR code URI.
To base32 encode a utf8 key you can use the `thirty-two` module.
```javascript
var base32 = require('thirty-two');
var key = 'secret key for the user';
// encoded will be the secret key, base32 encoded
var encoded = base32.encode(key);
// to create a URI for a qr code (change totp to hotp is using hotp)
var uri = 'otpauth://totp/somelabel?secret=' + encoded;
```
Note: If your label has spaces or other invalid uri characters you will need to encode it accordingly using `encodeURIComponent` More details about the uri key format can be found on the [google auth wiki](https://code.google.com/p/google-authenticator/wiki/KeyUriFormat)
# API
##notp.checkHOTP(args, err, cb)
##hotp.verify(token, key, opt)
Check a One Time Password based on a counter.
Check a counter based one time password for validity.
First argument of callback is true if password check is successful,
or false if check fails.
Returns null if token is not valid for given key and options.
Second argument is the time step difference between the client and
the server. This argument is only passed if the password check is
successful.
Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server.
Arguments:
### opt
**window**
> The allowable margin for the counter. The function will check `window` codes in the future against the provided token.
> i.e. if `window = 100` and `counter = 5` all tokens between 5 and 105 will be checked against the supplied token
> Default - 50
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
**counter**
> Counter value. This should be stored by the application on a per user basis. It is up to the application to track and increment this value as needed. It is also up to the application to increment this value if there is a skew between the client and server (`delta`)
P - Passcode to validate.
##totp.verify(token, key, opt)
W - The allowable margin for the counter. The function will check
W codes in the future against the provided passcode. Note,
it is the calling applications responsibility to keep track of
W and increment it for each password check, and also to adjust
it accordingly in the case where the client and server become
out of sync (second argument returns non zero).
E.g. if W = 100, and C = 5, this function will check the psscode
against all One Time Passcodes between 5 and 105.
Check a time based one time password for validity
Default - 50
Returns null if token is not valid for given key and options.
C - Counter value. This should be stored by the application, must
be user specific, and be incremented for each request.
Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server.
### opt
**window**
> The allowable margin for the counter. The function will check `window` codes in the future against the provided token.
> i.e. if `window = 5` and `counter = 1000` all tokens between 995 and 1005 will be checked against the supplied token
> Default - 6
**Example**
**time**
> The time step of the counter. This must be the same for every request and is used to calculate C.
> Default - 30
notp.checkHOTP(
{
K : 'USER SPECIFIC KEY', // Should be ASCII string
P : 'USER SUPPLIED PASSCODE'
},
function(err) { console.log('Ooops ' + err); },
function(res, w) {
if(res) {
console.log('Check was successful, counter is out of sync by ' + w + ' steps');
} else {
console.log('Check was unsuccesful');
}
}
);
##hotp.gen(key, opt)
##notp.checkTOTP(args, err, cb)
Return a counter based one time password
### opt
**counter**
> Counter value. This should be stored by the application, must be user specific, and be incremented for each request.
Check a One Time Password based on a timer.
##totp.gen(key, opt)
First argument of callback is true if password check is successful,
or false if check fails.
Return a time based one time password
Second argument is the time step difference between the client and
the server. This argument is only passed if the password check is
successful.
### opt
**time**
> The time step of the counter. This must be the same for every request and is used to calculate C.
> Default - 30
Arguments:
# Migrating from 1.x to 2.x
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
## Removed
The `encBase32` and `decBase32` methods have been removed. If you wish to encode/decode base32 you should install a module to do so. We recommend the `thirty-two` npm module.
P - Passcode to validate.
## Changed
W - The allowable margin for the counter. The function will check
W codes either side of the provided counter. Note,
it is the calling applications responsibility to keep track of
W and increment it for each password check, and also to adjust
it accordingly in the case where the client and server become
out of sync (second argument returns non zero).
E.g. if W = 5, and C = 1000, this function will check the psscode
against all One Time Passcodes between 995 and 1005.
All of the APIs have been changed to return values directly instead of using callbacks. This reflects the fact that the functions are actually synchronous and perform no I/O.
Default - 6
Some of the required arguments to the functions have also been removed from the `args` parameter and are passed as separate function parameters. See the above API docs for details.
T - The time step of the counter. This must be the same for
every request and is used to calculat C.
* `notp.checkHOTP(args, err, cb)` -> `notp.hotp.verify(token, key, opt)`
* `notp.checkTOTP(args, err, cb)` -> `notp.totp.verify(token, key, opt)`
* `notp.getHOTP(args, err, cb)` -> `notp.gotp.gen(key, opt)`
* `notp.getTOTP(args, err, cb)` -> `notp.totp.gen(key, opt)`
Default - 30
## Args
The argument names have also changed to better describe the purpose of the argument.
**Example**
notp.checkTOTP(
{
K : 'USER SPECIFIC KEY', // Should be ASCII string
P : 'USER SUPPLIED PASSCODE'
},
function(err) { console.log('Ooops ' + err); },
function(res, w) {
if(res) {
console.log('Check was successful, counter is out of sync by ' + w + ' steps');
} else {
console.log('Check was unsuccesful');
}
}
);
##notp.getHOTP(args, err, cb)
Generate a counter based One Time Password
First argument of callback is the value of the One Time Password
Arguments:
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
C - Counter value. This should be stored by the application, must
be user specific, and be incremented for each request.
**Example**
notp.getHOTP(
{
K : 'USER SPECIFIC KEY', // Should be ASCII string
C : 5 // COUNTER VALUE
},
function(err) { console.log('Ooops ' + err); },
function(res) {
console.log('HOTP for supplied K and C values is ' + res);
}
);
##notp.getTOTP(args, err, cb)
NOTE: Base32 encoding and decoding provided by [Nibbler](http://www.tumuski.com/2010/04/nibbler) library
Gennerate a time based One Time Password
First argument of callback is the value of the One Time Password
Arguments:
args
K - Key for the one time password. This should be unique and secret for
every user as it is the seed used to calculate the HMAC
T - The time step of the counter. This must be the same for
every request and is used to calculat C.
Default - 30
**Example**
notp.getTOTP(
{
K : 'USER SPECIFIC KEY' // Should be ASCII string
},
function(err) { console.log('Ooops ' + err); },
function(res) {
console.log('TOTP for supplied K and C values is ' + res);
}
);
##notp.encBase32(str)
Helper function to convert a string to a base32 encoded string
Arguments:
str - String to encode
Returns: Base 32 encoded string
**Example**
var StringForGoogleAuthenticator = notp.encBase32('USER SPECIFIC KEY');
##notp.decBase32(b32)
Helper function to convert a base32 encoded string to an ascii string
Arguments:
b32 - String to decode
Returns: ASCII string
**Example**
var str = notp.decBase32('BASE32 ENCODED STRING');
# Developers
To run the tests, make sure you have [expresso](https://github.com/visionmedia/expresso) installed, and run it from the base directory. You should see some warnings when running the TOTP tests, this is normal and is a result of overriding the time settings. If anyone can come up with a better way of running the TOTP tests please let me know.
## License
(The MIT License)
Copyright (c) 2011 Guy Halford-Thompson &lt;guy@cach.me&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* `K` -> no longer in args/opt but passed directly as a function argument
* `P` -> no longer in args/opt but passed directly as a function argument
* `W` -> `window`
* `C` -> `counter`
* `T` -> `time`

223
index.js
View File

@ -1 +1,222 @@
module.exports = require('./lib/notp');
var crypto = require('crypto');
var hotp = {};
/**
* Generate a counter based One Time Password
*
* @return {String} the one time password
*
* Arguments:
*
* args
* key - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* counter - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
hotp.gen = function(key, opt) {
var key = key || '';
var counter = opt.counter || 0;
var p = 6;
// Create the byte array
var b = new Buffer(intToBytes(counter));
var hmac = crypto.createHmac('SHA1', new Buffer(key));
// Update the HMAC witht he byte array
var digest = hmac.update(b).digest('hex');
// Get byte array
var h = hexToBytes(digest);
// Truncate
var offset = h[19] & 0xf;
var v = (h[offset] & 0x7f) << 24 |
(h[offset + 1] & 0xff) << 16 |
(h[offset + 2] & 0xff) << 8 |
(h[offset + 3] & 0xff);
v = v + '';
return v.substr(v.length - p, p);
};
/**
* Check a One Time Password based on a counter.
*
* @return {Object} null if failure, { delta: # } on success
* delta is the time step difference between the client and the server
*
* Arguments:
*
* args
* key - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* token - Passcode to validate.
*
* window - The allowable margin for the counter. The function will check
* W codes in the future against the provided passcode. Note,
* it is the calling applications responsibility to keep track of
* W and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero).
* E.g. if W = 100, and C = 5, this function will check the psscode
* against all One Time Passcodes between 5 and 105.
*
* Default - 50
*
* counter - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
hotp.verify = function(token, key, opt) {
var window = opt.window || 50;
var counter = opt.counter || 0;
// Now loop through from C to C + W to determine if there is
// a correct code
for(var i = counter; i <= counter + window; ++i) {
opt.counter = i;
if(this.gen(key, opt) === token) {
// We have found a matching code, trigger callback
// and pass offset
return { delta: i - counter };
}
}
// If we get to here then no codes have matched, return false
return false;
};
var totp = {};
/**
* Generate a time based One Time Password
*
* @return {String} the one time password
*
* Arguments:
*
* args
* key - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* time - The time step of the counter. This must be the same for
* every request and is used to calculat C.
*
* Default - 30
*
*/
totp.gen = function(key, opt) {
var time = opt.time || 30;
var _t = new Date().getTime();;
// Time has been overwritten.
if(opt._t) {
console.log('#####################################');
console.log('# NOTE: TOTP TIME VARIABLE HAS BEEN #');
console.log('# OVERWRITTEN. THIS SHOULD ONLY BE #');
console.log('# USED FOR TEST PURPOSES. #');
console.log('#####################################');
_t = opt._t;
}
// Determine the value of the counter, C
// This is the number of time steps in seconds since T0
opt.counter = Math.floor((_t / 1000) / time);
return hotp.gen(key, opt);
};
/**
* Check a One Time Password based on a timer.
*
* @return {Object} null if failure, { delta: # } on success
* delta is the time step difference between the client and the server
*
* Arguments:
*
* args
* key - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* token - Passcode to validate.
*
* window - The allowable margin for the counter. The function will check
* W codes either side of the provided counter. Note,
* it is the calling applications responsibility to keep track of
* W and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero).
* E.g. if W = 5, and C = 1000, this function will check the psscode
* against all One Time Passcodes between 995 and 1005.
*
* Default - 6
*
* time - The time step of the counter. This must be the same for
* every request and is used to calculate C.
*
* Default - 30
*
*/
totp.verify = function(token, key, opt) {
var time = opt.time || 30;
var _t = new Date().getTime();
// Time has been overwritten.
if(opt._t) {
console.log('#####################################');
console.log('# NOTE: TOTP TIME VARIABLE HAS BEEN #');
console.log('# OVERWRITTEN. THIS SHOULD ONLY BE #');
console.log('# USED FOR TEST PURPOSES. #');
console.log('#####################################');
_t = opt._t;
}
// Determine the value of the counter, C
// This is the number of time steps in seconds since T0
opt.counter = Math.floor((_t / 1000) / time);
return hotp.verify(token, key, opt);
};
module.exports.hotp = hotp;
module.exports.totp = totp;
/**
* convert an integer to a byte array
* @param {Integer} num
* @return {Array} bytes
*/
var intToBytes = function(num) {
var bytes = [];
for(var i=7 ; i>=0 ; --i) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
};
/**
* convert a hex value to a byte array
* @param {String} hex string of hex to convert to a byte array
* @return {Array} bytes
*/
var hexToBytes = function(hex) {
var bytes = [];
for(var c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.substr(c, 2), 16));
}
return bytes;
};

View File

@ -1,216 +0,0 @@
/*
Copyright (c) 2010 Thomas Peri
http://www.tumuski.com/
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true,
eqeqeq: true, plusplus: true, regexp: true, newcap: true, immed: true */
// (good parts minus bitwise and strict, plus white.)
/**
* Nibbler - Multi-Base Encoder
*
* version 2010-04-07
*
* Options:
* dataBits: The number of bits in each character of unencoded data.
* codeBits: The number of bits in each character of encoded data.
* keyString: The characters that correspond to each value when encoded.
* pad (optional): The character to pad the end of encoded output.
* arrayData (optional): If truthy, unencoded data is an array instead of a string.
*
* Example:
*
* var base64_8bit = new Nibbler({
* dataBits: 8,
* codeBits: 6,
* keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
* pad: '='
* });
* base64_8bit.encode("Hello, World!"); // returns "SGVsbG8sIFdvcmxkIQ=="
* base64_8bit.decode("SGVsbG8sIFdvcmxkIQ=="); // returns "Hello, World!"
*
* var base64_7bit = new Nibbler({
* dataBits: 7,
* codeBits: 6,
* keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
* pad: '='
* });
* base64_7bit.encode("Hello, World!"); // returns "kZdmzesQV9/LZkQg=="
* base64_7bit.decode("kZdmzesQV9/LZkQg=="); // returns "Hello, World!"
*
*/
var Nibbler = function (options) {
var construct,
// options
pad, dataBits, codeBits, keyString, arrayData,
// private instance variables
mask, group, max,
// private methods
gcd, translate,
// public methods
encode, decode;
// pseudo-constructor
construct = function () {
var i, mag, prev;
// options
pad = options.pad || '';
dataBits = options.dataBits;
codeBits = options.codeBits;
keyString = options.keyString;
arrayData = options.arrayData;
// bitmasks
mag = Math.max(dataBits, codeBits);
prev = 0;
mask = [];
for (i = 0; i < mag; i += 1) {
mask.push(prev);
prev += prev + 1;
}
max = prev;
// ouput code characters in multiples of this number
group = dataBits / gcd(dataBits, codeBits);
};
// greatest common divisor
gcd = function (a, b) {
var t;
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
return a;
};
// the re-coder
translate = function (input, bitsIn, bitsOut, decoding) {
var i, len, chr, byteIn,
buffer, size, output,
write;
// append a byte to the output
write = function (n) {
if (!decoding) {
output.push(keyString.charAt(n));
} else if (arrayData) {
output.push(n);
} else {
output.push(String.fromCharCode(n));
}
};
buffer = 0;
size = 0;
output = [];
len = input.length;
for (i = 0; i < len; i += 1) {
// the new size the buffer will be after adding these bits
size += bitsIn;
// read a character
if (decoding) {
// decode it
chr = input.charAt(i);
byteIn = keyString.indexOf(chr);
if (chr === pad) {
break;
} else if (byteIn < 0) {
throw 'the character "' + chr + '" is not a member of ' + keyString;
}
} else {
if (arrayData) {
byteIn = input[i];
} else {
byteIn = input.charCodeAt(i);
}
if ((byteIn | max) !== max) {
throw byteIn + " is outside the range 0-" + max;
}
}
// shift the buffer to the left and add the new bits
buffer = (buffer << bitsIn) | byteIn;
// as long as there's enough in the buffer for another output...
while (size >= bitsOut) {
// the new size the buffer will be after an output
size -= bitsOut;
// output the part that lies to the left of that number of bits
// by shifting the them to the right
write(buffer >> size);
// remove the bits we wrote from the buffer
// by applying a mask with the new size
buffer &= mask[size];
}
}
// If we're encoding and there's input left over, pad the output.
// Otherwise, leave the extra bits off, 'cause they themselves are padding
if (!decoding && size > 0) {
// flush the buffer
write(buffer << (bitsOut - size));
// add padding keyString for the remainder of the group
len = output.length % group;
for (i = 0; i < len; i += 1) {
output.push(pad);
}
}
// string!
return (arrayData && decoding) ? output : output.join('');
};
/**
* Encode. Input and output are strings.
*/
encode = function (input) {
return translate(input, dataBits, codeBits, false);
};
/**
* Decode. Input and output are strings.
*/
decode = function (input) {
return translate(input, codeBits, dataBits, true);
};
this.encode = encode;
this.decode = decode;
construct();
};
// For nodejs
module.exports = Nibbler;

View File

@ -1,376 +0,0 @@
/*
* Requires
*/
var crypto = require('crypto'),
base32 = require('./external/nibbler');
/*
* Export module as new Notp instance
*/
module.exports = new Notp();
/*
* Constructor function.
*
* Builds th base32 object
*/
function Notp() {
base32 = new base32(
{
dataBits: 8,
codeBits: 5,
keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
pad: '='
}
);
}
/*
* Check a One Time Password based on a counter.
*
* First argument of callback is true if password check is successful,
* or false if check fails.
*
* Second argument is the time step difference between the client and
* the server. This argument is only passed if the password check is
* successful.
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* P - Passcode to validate.
*
* W - The allowable margin for the counter. The function will check
* W codes in the future against the provided passcode. Note,
* it is the calling applications responsibility to keep track of
* W and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero).
* E.g. if W = 100, and C = 5, this function will check the psscode
* against all One Time Passcodes between 5 and 105.
*
* Default - 50
*
* C - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
Notp.prototype.checkHOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
i,
K = args.K || "",
W = args.W || 50,
C = args.C || 0,
P = args.P || "";
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
// Now loop through from C to C + W to determine if there is
// a correct code
for(i = C; i <= C+W; i++) {
if(this._calcHMAC(K,i) === P) {
// We have found a matching code, trigger callback
// and pass offset
cb(true, i - C);
return;
}
}
// If we get to here then no codes have matched, return false
cb(false);
return;
};
/*
* Check a One Time Password based on a timer.
*
* First argument of callback is true if password check is successful,
* or false if check fails.
*
* Second argument is the time step difference between the client and
* the server. This argument is only passed if the password check is
* successful.
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* P - Passcode to validate.
*
* W - The allowable margin for the counter. The function will check
* W codes either side of the provided counter. Note,
* it is the calling applications responsibility to keep track of
* W and increment it for each password check, and also to adjust
* it accordingly in the case where the client and server become
* out of sync (second argument returns non zero).
* E.g. if W = 5, and C = 1000, this function will check the psscode
* against all One Time Passcodes between 995 and 1005.
*
* Default - 6
*
* T - The time step of the counter. This must be the same for
* every request and is used to calculat C.
*
* Default - 30
*
*/
Notp.prototype.checkTOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
C,i,
K = args.K || "",
W = args.W || 6,
T = args.T || 30,
P = args.P || "",
_t;
if(args._t) {
// Time has been overwritten.
console.log('#####################################');
console.log('# NOTE: TOTP TIME VARIABLE HAS BEEN #');
console.log('# OVERWRITTEN. THIS SHOULD ONLY BE #');
console.log('# USED FOR TEST PURPOSES. #');
console.log('#####################################');
_t = args._t;
} else {
_t = new Date().getTime();
}
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
// Determine the value of the counter, C
// This is the number of time steps in seconds since T0
C = Math.floor((_t / 1000) / T);
// Now loop through from C - W to C + W and check to see
// if we have a valid code in that time line
for(i = C-W; i <= C+W; i++) {
if(this._calcHMAC(K,i) === P) {
// We have found a matching code, trigger callback
// and pass offset
cb(true, i-C);
return;
}
}
// If we get to here then no codes have matched, return false
cb(false);
return;
};
/*
* Gennerate a counter based One Time Password
*
* First argument of callback is the value of the One Time Password
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* C - Counter value. This should be stored by the application, must
* be user specific, and be incremented for each request.
*
*/
Notp.prototype.getHOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
i,
K = args.K || "",
C = args.C || 0,
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
cb(this._calcHMAC(K,C));
};
/*
* Gennerate a time based One Time Password
*
* First argument of callback is the value of the One Time Password
*
* Arguments:
*
* args
* K - Key for the one time password. This should be unique and secret for
* every user as it is the seed used to calculate the HMAC
*
* T - The time step of the counter. This must be the same for
* every request and is used to calculat C.
*
* Default - 30
*
*/
Notp.prototype.getTOTP = function(args, err, cb) {
var hmac,
digest,
offset, h, v, p = 6, b,
C,i,
K = args.K || "",
T = args.T || 30,
_t;
if(args._t) {
// Time has been overwritten.
console.log('#####################################');
console.log('# NOTE: TOTP TIME VARIABLE HAS BEEN #');
console.log('# OVERWRITTEN. THIS SHOULD ONLY BE #');
console.log('# USED FOR TEST PURPOSES. #');
console.log('#####################################');
_t = args._t;
} else {
_t = new Date().getTime();
}
// Initiate the HMAC
hmac = crypto.createHmac('SHA1', new Buffer(K))
// Determine the value of the counter, C
// This is the number of time steps in seconds since T0
C = Math.floor((_t / 1000) / T);
cb(this._calcHMAC(K,C));
};
/*
* Helper function to convert a string to a base32 encoded string
*
* Arguments:
*
* str - String to encode
*
* Returns: Base 32 encoded string
*/
Notp.prototype.encBase32 = function(str) {
return base32.encode(str);
};
/*
* Helper function to convert a base32 encoded string to an ascii string
*
* Arguments:
*
* b32 - String to decode
*
* Returns: ASCII string
*/
Notp.prototype.decBase32 = function(b32) {
return base32.decode(b32);
};
/******************************************************************
* NOTE: Any functions below this line are private and therefore *
* may change without providing backwards compatibility with *
* previous versions. You should not call the functions below *
* directly. *
*******************************************************************/
/*
* Private functon to calculate an HMAC.
*
* Arguments
*
* K - Key value
* C - Counter value
*
* Returns - truncated HMAC
*/
Notp.prototype._calcHMAC = function(K, C) {
var hmac = crypto.createHmac('SHA1', new Buffer(K)),
digest,
offset, h, v, p = 6, b;
// Create the byte array
b = new Buffer(this._intToBytes(C)),
// Update the HMAC witht he byte array
hmac.update(b);
// Diget the HMAC
digest = hmac.digest('hex');
// Get byte array
h = this._hexToBytes(digest);
// Truncate
offset = h[19] & 0xf;
v = (h[offset] & 0x7f) << 24 | (h[offset + 1] & 0xff) << 16 | (h[offset + 2] & 0xff) << 8 | (h[offset + 3] & 0xff);
v = "" + v;
v = v.substr(v.length - p, p);
return v;
};
/*
* Private function to convert an integer to a byte array
*
* Arguments
*
* num - Integer
*
* Returns - byte array
*/
Notp.prototype._intToBytes = function(num) {
var bytes = [],
i;
for(i=7;i>=0;i--) {
bytes[i] = num & (255);
num = num >> 8;
}
return bytes;
};
/*
* Private function to convert a hex value to a byte array
*
* Arguments
*
* hex - Hex value
*
* Returns - byte array
*/
Notp.prototype._hexToBytes = function(hex) {
for(var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
};

View File

@ -13,7 +13,7 @@
"test": "expresso"
},
"engines": {
"node": "~v0.4.10"
"node": ">= v0.4.10"
},
"dependencies": {},
"devDependencies": {

View File

@ -1,22 +1,18 @@
var notp = require('..');
/*
* Notp test suite
*/
var notp = require('../lib/notp');
/*
* Test HOTP. Uses test values from RFC 4226
* Test HOTtoken. Uses test values from RFcounter 4226
*
*
* The following test data uses the ASCII string
* The following test data uses the AScounterII string
* "12345678901234567890" for the secret:
*
* Secret = 0x3132333435363738393031323334353637383930
*
* Table 1 details for each count, the intermediate HMAC value.
* Table 1 details for each count, the intermediate HMAcounter value.
*
* Count Hexadecimal HMAC-SHA-1(secret, count)
* counterount Hexadecimal HMAcounter-SHA-1(secret, count)
* 0 cc93cf18508d94934c64b65d8ba7667fb7cde4b0
* 1 75a48a19d4cbe100644e8ac1397eea747a2d33ab
* 2 0bacb7fa082fef30782211938bc1c5e70416ff44
@ -29,10 +25,10 @@ var notp = require('../lib/notp');
* 9 1637409809a679dc698207310c8c7fc07290d9e5
*
* Table 2 details for each count the truncated values (both in
* hexadecimal and decimal) and then the HOTP value.
* hexadecimal and decimal) and then the HOTtoken value.
*
* Truncated
* Count Hexadecimal Decimal HOTP
* counterount Hexadecimal Decimal HOTtoken
* 0 4c93cf18 1284755224 755224
* 1 41397eea 1094287082 287082
* 2 82fef30 137359152 359152
@ -48,331 +44,156 @@ var notp = require('../lib/notp');
* see http://tools.ietf.org/html/rfc4226
*/
exports.testHOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
},
HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
var key = '12345678901234567890';
var opt = {
window : 0,
};
var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
// counterheck for failure
opt.counter = 0;
assert.ok(!notp.hotp.verify('WILL NOT PASS', key, opt), 'Should not pass');
// Check for failure
args.C = 0;
args.P = 'WILLNOTPASS';
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass');
n++;
}
);
// Check for passes
// counterheck for passes
for(i=0;i<HOTP.length;i++) {
args.C = i;
args.P = HOTP[i];
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
}
opt.counter = i;
var res = notp.hotp.verify(HOTP[i], key, opt);
beforeExit(function() {
assert.equal(HOTP.length + 1, n, 'All tests should have been run');
});
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
}
};
/*
* Test TOTP using test vectors from TOTP RFC.
* Test TOTtoken using test vectors from TOTtoken RFcounter.
*
* see http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.txt
*/
exports.testTOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
};
exports.testTOTtoken = function(beforeExit, assert) {
var key = '12345678901234567890';
var opt = {
window : 0,
};
// counterheck for failure
opt.time = 0;
var token = 'windowILLNOTtokenASS';
assert.ok(!notp.totp.verify(token, key, opt), 'Should not pass');
// Check for failure
args.T = 0;
args.P = 'WILLNOTPASS';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass');
n++;
}
);
// counterheck for test vector at 59s
opt._t = 59*1000;
var token = '287082';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
// Check for test vector at 59s
args._t = 59*1000;
args.P = '287082';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
// counterheck for test vector at 1234567890
opt._t = 1234567890*1000;
var token = '005924';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
// Check for test vector at 1234567890
args._t = 1234567890*1000;
args.P = '005924';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
// counterheck for test vector at 1111111109
opt._t = 1111111109*1000;
var token = '081804';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
// Check for test vector at 1111111109
args._t = 1111111109*1000;
args.P = '081804';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
// Check for test vector at 2000000000
args._t = 2000000000*1000;
args.P = '279037';
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass');
assert.eql(w, 0, 'Should be in sync');
n++;
}
);
beforeExit(function() {
assert.equal(5, n, 'All tests should have been run');
});
// counterheck for test vector at 2000000000
opt._t = 2000000000*1000;
var token = '279037';
var res = notp.totp.verify(token, key, opt);
assert.ok(res, 'Should pass');
assert.eql(res.delta, 0, 'Should be in sync');
};
/*
* Check for codes that are out of sync
* We are going to use a value of C = 1 and test against
* a code for C = 9
* counterheck for codes that are out of sync
* windowe are going to use a value of counter = 1 and test against
* a code for counter = 9
*/
exports.testHOTPOutOfSync = function(beforeExit, assert) {
var n = 0,
args = {
K : '12345678901234567890',
P : '520489',
C : 1
};
var key = '12345678901234567890';
var token = '520489';
// Check that the test should fail for W < 8
args.W = 7;
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass for value of W < 8');
n++;
}
);
var opt = {
counter : 1
};
// Check that the test should pass for W >= 9
args.W = 8;
notp.checkHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass for value of W >= 9');
n++;
}
);
// counterheck that the test should fail for window < 8
opt.window = 7;
assert.ok(!notp.hotp.verify(token, key, opt), 'Should not pass for value of window < 8');
beforeExit(function() {
assert.equal(2, n, 'All tests should have been run');
});
// counterheck that the test should pass for window >= 9
opt.window = 8;
assert.ok(notp.hotp.verify(token, key, opt), 'Should pass for value of window >= 9');
};
/*
* Check for codes that are out of sync
* We are going to use a value of T = 1999999909 (91s behind 2000000000)
* counterheck for codes that are out of sync
* windowe are going to use a value of T = 1999999909 (91s behind 2000000000)
*/
exports.testTOTPOutOfSync = function(beforeExit, assert) {
var n = 0,
args = {
K : '12345678901234567890',
P : '279037',
_t : 1999999909*1000
};
var key = '12345678901234567890';
var token = '279037';
// Check that the test should fail for W < 2
args.W = 2;
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, false, 'Should not pass for value of W < 3');
n++;
}
);
var opt = {
_t : 1999999909*1000
};
// Check that the test should pass for W >= 3
args.W = 3;
notp.checkTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, true, 'Should pass for value of W >= 3');
n++;
}
);
// counterheck that the test should fail for window < 2
opt.window = 2;
assert.ok(!notp.totp.verify(token, key, opt), 'Should not pass for value of window < 3');
beforeExit(function() {
assert.equal(2, n, 'All tests should have been run');
});
// counterheck that the test should pass for window >= 3
opt.window = 3;
assert.ok(notp.totp.verify(token, key, opt), 'Should pass for value of window >= 3');
};
/*
* Test getHOTP function. Uses same test values as for checkHOTP
*/
exports.testGetHOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
},
HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
exports.hotp_gen = function(beforeExit, assert) {
var key = '12345678901234567890';
var opt = {
window : 0,
};
// Check for passes
var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'];
// counterheck for passes
for(i=0;i<HOTP.length;i++) {
args.C = i;
notp.getHOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret) {
assert.eql(ret, HOTP[i], 'HTOP value should be correct');
n++;
}
);
opt.counter = i;
assert.eql(notp.hotp.gen(key, opt), HOTP[i], 'HOTP value should be correct');
}
beforeExit(function() {
assert.equal(HOTP.length, n, 'All tests should have been run');
});
};
/*
* Test getTOTP function. Uses same test values as for checkTOTP
*/
exports.testGetTOTP = function(beforeExit, assert) {
var n = 0,
args = {
W : 0,
K : '12345678901234567890'
};
exports.totp_gen = function(beforeExit, assert) {
var key = '12345678901234567890';
var opt = {
window : 0,
};
// Check for test vector at 59s
args._t = 59*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '287082', 'TOTP values should match');
n++;
}
);
// counterheck for test vector at 59s
opt._t = 59*1000;
assert.eql(notp.totp.gen(key, opt), '287082', 'TOTtoken values should match');
// Check for test vector at 1234567890
args._t = 1234567890*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '005924', 'TOTP values should match');
n++;
}
);
// counterheck for test vector at 1234567890
opt._t = 1234567890*1000;
assert.eql(notp.totp.gen(key, opt), '005924', 'TOTtoken values should match');
// Check for test vector at 1111111109
args._t = 1111111109*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '081804', 'TOTP values should match');
n++;
}
);
// counterheck for test vector at 1111111109
opt._t = 1111111109*1000;
assert.eql(notp.totp.gen(key, opt), '081804', 'TOTtoken values should match');
// Check for test vector at 2000000000
args._t = 2000000000*1000;
notp.getTOTP(args,
function(err) {
assert.eql(true, false, err);
},
function(ret, w) {
assert.eql(ret, '279037', 'TOTP values should match');
n++;
}
);
beforeExit(function() {
assert.equal(4, n, 'All tests should have been run');
});
// counterheck for test vector at 2000000000
opt._t = 2000000000*1000;
assert.eql(notp.totp.gen(key, opt), '279037', 'TOTtoken values should match');
};
/*
* Test encode to base32
*/
exports.testEncodeToBase32 = function(beforeExit, assert) {
assert.eql(notp.encBase32('12345678901234567890'), 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
};
/*
* Test decode base32
*/
exports.testDecodeFromBase32 = function(beforeExit, assert) {
assert.eql(notp.decBase32('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'), '12345678901234567890');
};