From 9f68f20826c1f4e636138ac4a34253ceca03de98 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Thu, 31 May 2012 18:54:35 -0400 Subject: [PATCH 01/18] use package `thirty-two` for base32 encoding/decoding --- lib/external/nibbler.js | 216 ---------------------------------------- lib/notp.js | 21 +--- package.json | 4 +- 3 files changed, 5 insertions(+), 236 deletions(-) delete mode 100644 lib/external/nibbler.js diff --git a/lib/external/nibbler.js b/lib/external/nibbler.js deleted file mode 100644 index 7e1277c..0000000 --- a/lib/external/nibbler.js +++ /dev/null @@ -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; diff --git a/lib/notp.js b/lib/notp.js index c053567..5ac87cd 100644 --- a/lib/notp.js +++ b/lib/notp.js @@ -1,9 +1,6 @@ -/* - * Requires - */ -var crypto = require('crypto'), - base32 = require('./external/nibbler'); +var crypto = require('crypto'); +var base32 = require('thirty-two'); /* @@ -11,21 +8,7 @@ var crypto = require('crypto'), */ module.exports = new Notp(); - -/* - * Constructor function. - * - * Builds th base32 object - */ function Notp() { - base32 = new base32( - { - dataBits: 8, - codeBits: 5, - keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', - pad: '=' - } - ); } diff --git a/package.json b/package.json index 22e63ab..659ff29 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,9 @@ "engines": { "node": "~v0.4.10" }, - "dependencies": {}, + "dependencies": { + "thirty-two": "0.0.1" + }, "devDependencies": { "expresso" : "0.9.0" } From 5221c05ac9575639ae13820c5e2f7c99aa373709 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Thu, 31 May 2012 18:55:14 -0400 Subject: [PATCH 02/18] support node >= 0.4.10 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 659ff29..243104b 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "test": "expresso" }, "engines": { - "node": "~v0.4.10" + "node": ">= v0.4.10" }, "dependencies": { "thirty-two": "0.0.1" From 190d29070c3cd1f73dd3443970f295969469d981 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Thu, 31 May 2012 18:57:41 -0400 Subject: [PATCH 03/18] remove Nopt `object` and just export directly --- lib/notp.js | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/lib/notp.js b/lib/notp.js index 5ac87cd..b415930 100644 --- a/lib/notp.js +++ b/lib/notp.js @@ -2,16 +2,6 @@ var crypto = require('crypto'); var base32 = require('thirty-two'); - -/* - * Export module as new Notp instance - */ -module.exports = new Notp(); - -function Notp() { -} - - /* * Check a One Time Password based on a counter. * @@ -45,7 +35,7 @@ function Notp() { * be user specific, and be incremented for each request. * */ -Notp.prototype.checkHOTP = function(args, err, cb) { +module.exports.checkHOTP = function(args, err, cb) { var hmac, digest, @@ -113,7 +103,7 @@ Notp.prototype.checkHOTP = function(args, err, cb) { * Default - 30 * */ -Notp.prototype.checkTOTP = function(args, err, cb) { +module.exports.checkTOTP = function(args, err, cb) { var hmac, digest, @@ -178,7 +168,7 @@ Notp.prototype.checkTOTP = function(args, err, cb) { * be user specific, and be incremented for each request. * */ -Notp.prototype.getHOTP = function(args, err, cb) { +module.exports.getHOTP = function(args, err, cb) { var hmac, digest, @@ -213,7 +203,7 @@ Notp.prototype.getHOTP = function(args, err, cb) { * Default - 30 * */ -Notp.prototype.getTOTP = function(args, err, cb) { +module.exports.getTOTP = function(args, err, cb) { var hmac, digest, offset, h, v, p = 6, b, @@ -255,7 +245,7 @@ Notp.prototype.getTOTP = function(args, err, cb) { * * Returns: Base 32 encoded string */ -Notp.prototype.encBase32 = function(str) { +module.exports.encBase32 = function(str) { return base32.encode(str); }; @@ -269,7 +259,7 @@ Notp.prototype.encBase32 = function(str) { * * Returns: ASCII string */ -Notp.prototype.decBase32 = function(b32) { +module.exports.decBase32 = function(b32) { return base32.decode(b32); }; @@ -292,7 +282,7 @@ Notp.prototype.decBase32 = function(b32) { * * Returns - truncated HMAC */ -Notp.prototype._calcHMAC = function(K, C) { +module.exports._calcHMAC = function(K, C) { var hmac = crypto.createHmac('SHA1', new Buffer(K)), digest, @@ -329,7 +319,7 @@ Notp.prototype._calcHMAC = function(K, C) { * * Returns - byte array */ -Notp.prototype._intToBytes = function(num) { +module.exports._intToBytes = function(num) { var bytes = [], i; @@ -351,7 +341,7 @@ Notp.prototype._intToBytes = function(num) { * * Returns - byte array */ -Notp.prototype._hexToBytes = function(hex) { +module.exports._hexToBytes = function(hex) { for(var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; From 4475c95ecba7cf4caadfe19e9247a9fed50a794e Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Thu, 31 May 2012 19:03:58 -0400 Subject: [PATCH 04/18] remove `err` argument from functions It was never used and is not really the node.js way to do things. --- lib/notp.js | 8 ++++---- test/notp.js | 48 ------------------------------------------------ 2 files changed, 4 insertions(+), 52 deletions(-) diff --git a/lib/notp.js b/lib/notp.js index b415930..3a27690 100644 --- a/lib/notp.js +++ b/lib/notp.js @@ -35,7 +35,7 @@ var base32 = require('thirty-two'); * be user specific, and be incremented for each request. * */ -module.exports.checkHOTP = function(args, err, cb) { +module.exports.checkHOTP = function(args, cb) { var hmac, digest, @@ -103,7 +103,7 @@ module.exports.checkHOTP = function(args, err, cb) { * Default - 30 * */ -module.exports.checkTOTP = function(args, err, cb) { +module.exports.checkTOTP = function(args, cb) { var hmac, digest, @@ -168,7 +168,7 @@ module.exports.checkTOTP = function(args, err, cb) { * be user specific, and be incremented for each request. * */ -module.exports.getHOTP = function(args, err, cb) { +module.exports.getHOTP = function(args, cb) { var hmac, digest, @@ -203,7 +203,7 @@ module.exports.getHOTP = function(args, err, cb) { * Default - 30 * */ -module.exports.getTOTP = function(args, err, cb) { +module.exports.getTOTP = function(args, cb) { var hmac, digest, offset, h, v, p = 6, b, diff --git a/test/notp.js b/test/notp.js index 87aec47..896f08b 100644 --- a/test/notp.js +++ b/test/notp.js @@ -60,9 +60,6 @@ exports.testHOTP = function(beforeExit, assert) { 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++; @@ -74,9 +71,6 @@ exports.testHOTP = function(beforeExit, assert) { 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'); @@ -108,9 +102,6 @@ exports.testTOTP = function(beforeExit, assert) { 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++; @@ -121,9 +112,6 @@ exports.testTOTP = function(beforeExit, assert) { 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'); @@ -135,9 +123,6 @@ exports.testTOTP = function(beforeExit, assert) { 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'); @@ -149,9 +134,6 @@ exports.testTOTP = function(beforeExit, assert) { 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'); @@ -163,9 +145,6 @@ exports.testTOTP = function(beforeExit, assert) { 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'); @@ -196,9 +175,6 @@ exports.testHOTPOutOfSync = function(beforeExit, assert) { // 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++; @@ -208,9 +184,6 @@ exports.testHOTPOutOfSync = function(beforeExit, assert) { // 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++; @@ -239,9 +212,6 @@ exports.testTOTPOutOfSync = function(beforeExit, assert) { // 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++; @@ -251,9 +221,6 @@ exports.testTOTPOutOfSync = function(beforeExit, assert) { // 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++; @@ -281,9 +248,6 @@ exports.testGetHOTP = function(beforeExit, assert) { for(i=0;i Date: Thu, 31 May 2012 23:40:34 -0400 Subject: [PATCH 05/18] code cleanup - remove callbacks (functions are sync) - update tests for removed callbacks - minimize some code duplication --- lib/notp.js | 271 ++++++++++++++------------------------------------- test/notp.js | 229 ++++++++++--------------------------------- 2 files changed, 126 insertions(+), 374 deletions(-) diff --git a/lib/notp.js b/lib/notp.js index 3a27690..9cb69e2 100644 --- a/lib/notp.js +++ b/lib/notp.js @@ -1,16 +1,11 @@ var crypto = require('crypto'); -var base32 = require('thirty-two'); -/* +/** * 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. + * @return {Object} null if failure, { delta: # } on success + * delta is the time step difference between the client and the server * * Arguments: * @@ -35,48 +30,33 @@ var base32 = require('thirty-two'); * be user specific, and be incremented for each request. * */ -module.exports.checkHOTP = function(args, cb) { +module.exports.checkHOTP = function(args) { - 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)) + var W = args.W || 50; + var C = args.C || 0; + var P = args.P || ''; // 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) { + for(i = C; i <= C+W; ++i) { + args.C = i; + if(this.getHOTP(args) === P) { // We have found a matching code, trigger callback // and pass offset - cb(true, i - C); - return; + return { delta: i - C }; } } // If we get to here then no codes have matched, return false - cb(false); - return; - + return false; }; -/* +/** * 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. + * @return {Object} null if failure, { delta: # } on success + * delta is the time step difference between the client and the server * * Arguments: * @@ -103,60 +83,33 @@ module.exports.checkHOTP = function(args, cb) { * Default - 30 * */ -module.exports.checkTOTP = function(args, 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; +module.exports.checkTOTP = function(args) { + var T = args.T || 30; + var _t = new Date().getTime(); + // Time has been overwritten. 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); + args.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; + return module.exports.checkHOTP(args); }; -/* - * Gennerate a counter based One Time Password +/** + * Generate a counter based One Time Password * - * First argument of callback is the value of the One Time Password + * @return {String} the one time password * * Arguments: * @@ -168,28 +121,40 @@ module.exports.checkTOTP = function(args, cb) { * be user specific, and be incremented for each request. * */ -module.exports.getHOTP = function(args, cb) { +module.exports.getHOTP = function(args) { + var key = args.K || ''; + var counter = args.C || 0; - var hmac, - digest, - offset, h, v, p = 6, b, - i, - K = args.K || "", - C = args.C || 0, + var p = 6; + // Create the byte array + var b = new Buffer(intToBytes(counter)); - // Initiate the HMAC - hmac = crypto.createHmac('SHA1', new Buffer(K)) + var hmac = crypto.createHmac('SHA1', new Buffer(key)); - cb(this._calcHMAC(K,C)); + // 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); }; -/* - * Gennerate a time based One Time Password +/** + * Generate a time based One Time Password * - * First argument of callback is the value of the One Time Password + * @return {String} the one time password * * Arguments: * @@ -203,127 +168,37 @@ module.exports.getHOTP = function(args, cb) { * Default - 30 * */ -module.exports.getTOTP = function(args, cb) { - var hmac, - digest, - offset, h, v, p = 6, b, - C,i, - K = args.K || "", - T = args.T || 30, - _t; - +module.exports.getTOTP = function(args) { + var K = args.K || ''; + var T = args.T || 30; + var _t = new Date().getTime();; + // Time has been overwritten. 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); + args.C = Math.floor((_t / 1000) / T); - cb(this._calcHMAC(K,C)); + return this.getHOTP(args); }; - -/* - * Helper function to convert a string to a base32 encoded string - * - * Arguments: - * - * str - String to encode - * - * Returns: Base 32 encoded string +/** + * convert an integer to a byte array + * @param {Integer} num + * @return {Array} bytes */ -module.exports.encBase32 = function(str) { - return base32.encode(str); -}; +var intToBytes = function(num) { + var bytes = []; - -/* - * Helper function to convert a base32 encoded string to an ascii string - * - * Arguments: - * - * b32 - String to decode - * - * Returns: ASCII string - */ -module.exports.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 - */ -module.exports._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 - */ -module.exports._intToBytes = function(num) { - var bytes = [], - i; - - for(i=7;i>=0;i--) { + for(var i=7 ; i>=0 ; --i) { bytes[i] = num & (255); num = num >> 8; } @@ -332,18 +207,16 @@ module.exports._intToBytes = function(num) { }; -/* - * Private function to convert a hex value to a byte array - * - * Arguments - * - * hex - Hex value - * - * Returns - byte array +/** + * convert a hex value to a byte array + * @param {String} hex string of hex to convert to a byte array + * @return {Array} bytes */ -module.exports._hexToBytes = function(hex) { - for(var bytes = [], c = 0; c < hex.length; c += 2) - bytes.push(parseInt(hex.substr(c, 2), 16)); +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; }; diff --git a/test/notp.js b/test/notp.js index 896f08b..4656a70 100644 --- a/test/notp.js +++ b/test/notp.js @@ -1,9 +1,5 @@ -/* - * Notp test suite - */ - -var notp = require('../lib/notp'); +var notp = require('..'); /* * Test HOTP. Uses test values from RFC 4226 @@ -48,40 +44,26 @@ 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 args = { + W : 0, + K : '12345678901234567890' + }; + var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; // Check for failure args.C = 0; args.P = 'WILLNOTPASS'; - notp.checkHOTP(args, - function(ret, w) { - assert.eql(ret, false, 'Should not pass'); - n++; - } - ); + assert.ok(!notp.checkHOTP(args), 'Should not pass'); // Check for passes for(i=0;i= 9 args.W = 8; - notp.checkHOTP(args, - function(ret, w) { - assert.eql(ret, true, 'Should pass for value of W >= 9'); - n++; - } - ); - - beforeExit(function() { - assert.equal(2, n, 'All tests should have been run'); - }); + assert.ok(notp.checkHOTP(args), 'Should pass for value of W >= 9'); }; @@ -202,34 +146,19 @@ exports.testHOTPOutOfSync = function(beforeExit, assert) { */ exports.testTOTPOutOfSync = function(beforeExit, assert) { - var n = 0, - args = { - K : '12345678901234567890', - P : '279037', - _t : 1999999909*1000 - }; + var args = { + K : '12345678901234567890', + P : '279037', + _t : 1999999909*1000 + }; // Check that the test should fail for W < 2 args.W = 2; - notp.checkTOTP(args, - function(ret, w) { - assert.eql(ret, false, 'Should not pass for value of W < 3'); - n++; - } - ); + assert.ok(!notp.checkTOTP(args), 'Should not pass for value of W < 3'); // Check that the test should pass for W >= 3 args.W = 3; - notp.checkTOTP(args, - function(ret, w) { - assert.eql(ret, true, 'Should pass for value of W >= 3'); - n++; - } - ); - - beforeExit(function() { - assert.equal(2, n, 'All tests should have been run'); - }); + assert.ok(notp.checkTOTP(args), 'Should pass for value of W >= 3'); }; @@ -237,27 +166,18 @@ exports.testTOTPOutOfSync = function(beforeExit, assert) { * 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']; + var args = { + W : 0, + K : '12345678901234567890' + }; + + var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; // Check for passes for(i=0;i Date: Thu, 31 May 2012 23:48:03 -0400 Subject: [PATCH 06/18] update README api changes --- Readme.md | 175 ++++++++++++++++++++---------------------------------- 1 file changed, 66 insertions(+), 109 deletions(-) diff --git a/Readme.md b/Readme.md index 1f9164d..7996bfc 100644 --- a/Readme.md +++ b/Readme.md @@ -3,41 +3,38 @@ # 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. +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. - var notp = require('notp'), - args = {}; +```javascript +var notp = require('notp'); - //.... 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 args = {}; - // 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'); - } - } - ); +//.... 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'; + +// Check TOTP is correct +var login = notp.checkTOTP(args); + +// invalid token +if (!login) { + return console.log('Token invalid'); +} + +// valid token +console.log('Token valid, sync value is %s', login.delta); +``` # API -##notp.checkHOTP(args, err, cb) +##notp.checkHOTP(args) Check a One Time Password based on a counter. @@ -73,20 +70,21 @@ IMPORTANT: The NOTP library accepts ASCII strings as keys, but the Google Authen **Example** - 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'); - } - } - ); +```javascript +var opt = { + K : 'USER SPECIFIC KEY', // Should be ASCII string + P : 'USER SUPPLIED PASSCODE' +}; + +var res = notp.checkHOTP(opt); + +// not valid +if (!res) { + return console.log('invalid'); +} + +console.log('valid, counter is out of sync by %d steps', res.delta); +``` ##notp.checkTOTP(args, err, cb) @@ -127,20 +125,21 @@ IMPORTANT: The NOTP library accepts ASCII strings as keys, but the Google Authen **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'); - } - } - ); +```javascript +var opt = { + K : 'USER SPECIFIC KEY', // Should be ASCII string + P : 'USER SUPPLIED PASSCODE' +}; + +var res = notp.checkTOTP(opt); + +// not valid +if (!res) { + return console.log('invalid'); +} + +console.log('valid, counter is out of sync by %d steps', res.delta); +``` ##notp.getHOTP(args, err, cb) @@ -159,22 +158,16 @@ IMPORTANT: The NOTP library accepts ASCII strings as keys, but the Google Authen **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); - } - ); +```javascript +var token = notp.getHOTP({ + K : 'USER SPECIFIC KEY', // Should be ASCII string + C : 5 // COUNTER VALUE +}); +``` ##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 + Generate a time based One Time Password First argument of callback is the value of the One Time Password @@ -191,47 +184,11 @@ NOTE: Base32 encoding and decoding provided by [Nibbler](http://www.tumuski.com/ **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. - +```javascript +var token = notp.getTOTP({ + K : 'USER SPECIFIC KEY' // Should be ASCII string +}); +``` ## License From 3fd84e5a7e55eeb8862d261cf124162882da363e Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Thu, 31 May 2012 23:51:19 -0400 Subject: [PATCH 07/18] rename lib/nopt.js -> index.js simple project don't need lib folder --- index.js | 223 +++++++++++++++++++++++++++++++++++++++++++++++++++- lib/notp.js | 222 --------------------------------------------------- 2 files changed, 222 insertions(+), 223 deletions(-) delete mode 100644 lib/notp.js diff --git a/index.js b/index.js index 3a5dfc1..9cb69e2 100644 --- a/index.js +++ b/index.js @@ -1 +1,222 @@ -module.exports = require('./lib/notp'); + +var crypto = require('crypto'); + +/** + * 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 + * 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. + * + */ +module.exports.checkHOTP = function(args) { + + var W = args.W || 50; + var C = args.C || 0; + var P = args.P || ''; + + // Now loop through from C to C + W to determine if there is + // a correct code + for(i = C; i <= C+W; ++i) { + args.C = i; + if(this.getHOTP(args) === P) { + // We have found a matching code, trigger callback + // and pass offset + return { delta: i - C }; + } + } + + // If we get to here then no codes have matched, return false + return false; +}; + + +/** + * 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 + * 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 + * + */ +module.exports.checkTOTP = function(args) { + + var T = args.T || 30; + var _t = new Date().getTime(); + + // Time has been overwritten. + if(args._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 = args._t; + } + + // Determine the value of the counter, C + // This is the number of time steps in seconds since T0 + args.C = Math.floor((_t / 1000) / T); + + return module.exports.checkHOTP(args); +}; + + +/** + * Generate a counter based One Time Password + * + * @return {String} 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. + * + */ +module.exports.getHOTP = function(args) { + var key = args.K || ''; + var counter = args.C || 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); +}; + + +/** + * Generate a time based One Time Password + * + * @return {String} 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 + * + */ +module.exports.getTOTP = function(args) { + var K = args.K || ''; + var T = args.T || 30; + var _t = new Date().getTime();; + + // Time has been overwritten. + if(args._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 = args._t; + } + + // Determine the value of the counter, C + // This is the number of time steps in seconds since T0 + args.C = Math.floor((_t / 1000) / T); + + return this.getHOTP(args); +}; + +/** + * 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; +}; + diff --git a/lib/notp.js b/lib/notp.js deleted file mode 100644 index 9cb69e2..0000000 --- a/lib/notp.js +++ /dev/null @@ -1,222 +0,0 @@ - -var crypto = require('crypto'); - -/** - * 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 - * 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. - * - */ -module.exports.checkHOTP = function(args) { - - var W = args.W || 50; - var C = args.C || 0; - var P = args.P || ''; - - // Now loop through from C to C + W to determine if there is - // a correct code - for(i = C; i <= C+W; ++i) { - args.C = i; - if(this.getHOTP(args) === P) { - // We have found a matching code, trigger callback - // and pass offset - return { delta: i - C }; - } - } - - // If we get to here then no codes have matched, return false - return false; -}; - - -/** - * 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 - * 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 - * - */ -module.exports.checkTOTP = function(args) { - - var T = args.T || 30; - var _t = new Date().getTime(); - - // Time has been overwritten. - if(args._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 = args._t; - } - - // Determine the value of the counter, C - // This is the number of time steps in seconds since T0 - args.C = Math.floor((_t / 1000) / T); - - return module.exports.checkHOTP(args); -}; - - -/** - * Generate a counter based One Time Password - * - * @return {String} 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. - * - */ -module.exports.getHOTP = function(args) { - var key = args.K || ''; - var counter = args.C || 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); -}; - - -/** - * Generate a time based One Time Password - * - * @return {String} 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 - * - */ -module.exports.getTOTP = function(args) { - var K = args.K || ''; - var T = args.T || 30; - var _t = new Date().getTime();; - - // Time has been overwritten. - if(args._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 = args._t; - } - - // Determine the value of the counter, C - // This is the number of time steps in seconds since T0 - args.C = Math.floor((_t / 1000) / T); - - return this.getHOTP(args); -}; - -/** - * 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; -}; - From 9344bad00900efb303913f4987f639cb906c0df5 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Fri, 1 Jun 2012 00:04:21 -0400 Subject: [PATCH 08/18] rename arguments There is no need for single letter arguments, they just make reading the code more confusing. The spec uses them to avoid typing longer words all over the place but we don't have as much code to produce. - P -> token - W -> window - K -> key - C -> counter - T -> time --- Readme.md | 26 ++++----- index.js | 73 ++++++++++++------------- test/notp.js | 152 +++++++++++++++++++++++++-------------------------- 3 files changed, 123 insertions(+), 128 deletions(-) diff --git a/Readme.md b/Readme.md index 7996bfc..cdbd4a9 100644 --- a/Readme.md +++ b/Readme.md @@ -48,12 +48,12 @@ console.log('Token valid, sync value is %s', login.delta); Arguments: args - K - Key for the one time password. This should be unique and secret for + 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 - P - Passcode to validate. + token - Passcode to validate. - W - The allowable margin for the counter. The function will check + 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 @@ -64,7 +64,7 @@ console.log('Token valid, sync value is %s', login.delta); Default - 50 - C - Counter value. This should be stored by the application, must + counter - Counter value. This should be stored by the application, must be user specific, and be incremented for each request. @@ -101,12 +101,12 @@ console.log('valid, counter is out of sync by %d steps', res.delta); Arguments: args - K - Key for the one time password. This should be unique and secret for + 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 - P - Passcode to validate. + token - Passcode to validate. - W - The allowable margin for the counter. The function will check + 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 @@ -117,7 +117,7 @@ console.log('valid, counter is out of sync by %d steps', res.delta); Default - 6 - T - The time step of the counter. This must be the same for + time - The time step of the counter. This must be the same for every request and is used to calculat C. Default - 30 @@ -150,10 +150,10 @@ console.log('valid, counter is out of sync by %d steps', res.delta); Arguments: args - K - Key for the one time password. This should be unique and secret for + 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 - C - Counter value. This should be stored by the application, must + counter - Counter value. This should be stored by the application, must be user specific, and be incremented for each request. **Example** @@ -174,11 +174,11 @@ var token = notp.getHOTP({ Arguments: args - K - Key for the one time password. This should be unique and secret for + 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 - T - The time step of the counter. This must be the same for - every request and is used to calculat C. + time - The time step of the counter. This must be the same for + every request and is used to calculate C. Default - 30 diff --git a/index.js b/index.js index 9cb69e2..73ff375 100644 --- a/index.js +++ b/index.js @@ -10,12 +10,12 @@ var crypto = require('crypto'); * Arguments: * * args - * K - Key for the one time password. This should be unique and secret for + * 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 * - * P - Passcode to validate. + * token - Passcode to validate. * - * W - The allowable margin for the counter. The function will check + * 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 @@ -26,24 +26,24 @@ var crypto = require('crypto'); * * Default - 50 * - * C - Counter value. This should be stored by the application, must + * counter - Counter value. This should be stored by the application, must * be user specific, and be incremented for each request. * */ -module.exports.checkHOTP = function(args) { +module.exports.checkHOTP = function(opt) { - var W = args.W || 50; - var C = args.C || 0; - var P = args.P || ''; + var window = opt.window || 50; + var counter = opt.counter || 0; + var token = opt.token || ''; // Now loop through from C to C + W to determine if there is // a correct code - for(i = C; i <= C+W; ++i) { - args.C = i; - if(this.getHOTP(args) === P) { + for(var i = counter; i <= counter + window; ++i) { + opt.counter = i; + if(this.getHOTP(opt) === token) { // We have found a matching code, trigger callback // and pass offset - return { delta: i - C }; + return { delta: i - counter }; } } @@ -61,12 +61,12 @@ module.exports.checkHOTP = function(args) { * Arguments: * * args - * K - Key for the one time password. This should be unique and secret for + * 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 * - * P - Passcode to validate. + * token - Passcode to validate. * - * W - The allowable margin for the counter. The function will check + * 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 @@ -77,32 +77,32 @@ module.exports.checkHOTP = function(args) { * * Default - 6 * - * T - The time step of the counter. This must be the same for - * every request and is used to calculat C. + * time - The time step of the counter. This must be the same for + * every request and is used to calculate C. * * Default - 30 * */ -module.exports.checkTOTP = function(args) { +module.exports.checkTOTP = function(opt) { - var T = args.T || 30; + var time = opt.time || 30; var _t = new Date().getTime(); // Time has been overwritten. - if(args._t) { + 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 = args._t; + _t = opt._t; } // Determine the value of the counter, C // This is the number of time steps in seconds since T0 - args.C = Math.floor((_t / 1000) / T); + opt.counter = Math.floor((_t / 1000) / time); - return module.exports.checkHOTP(args); + return module.exports.checkHOTP(opt); }; @@ -114,16 +114,16 @@ module.exports.checkTOTP = function(args) { * Arguments: * * args - * K - Key for the one time password. This should be unique and secret for + * 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 * - * C - Counter value. This should be stored by the application, must + * counter - Counter value. This should be stored by the application, must * be user specific, and be incremented for each request. * */ -module.exports.getHOTP = function(args) { - var key = args.K || ''; - var counter = args.C || 0; +module.exports.getHOTP = function(opt) { + var key = opt.key || ''; + var counter = opt.counter || 0; var p = 6; @@ -159,35 +159,34 @@ module.exports.getHOTP = function(args) { * Arguments: * * args - * K - Key for the one time password. This should be unique and secret for + * 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 * - * T - The time step of the counter. This must be the same for + * time - The time step of the counter. This must be the same for * every request and is used to calculat C. * * Default - 30 * */ -module.exports.getTOTP = function(args) { - var K = args.K || ''; - var T = args.T || 30; +module.exports.getTOTP = function(opt) { + var time = opt.time || 30; var _t = new Date().getTime();; // Time has been overwritten. - if(args._t) { + 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 = args._t; + _t = opt._t; } // Determine the value of the counter, C // This is the number of time steps in seconds since T0 - args.C = Math.floor((_t / 1000) / T); + opt.counter = Math.floor((_t / 1000) / time); - return this.getHOTP(args); + return this.getHOTP(opt); }; /** diff --git a/test/notp.js b/test/notp.js index 4656a70..7931c5a 100644 --- a/test/notp.js +++ b/test/notp.js @@ -2,17 +2,17 @@ var notp = require('..'); /* - * 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 @@ -25,10 +25,10 @@ var notp = require('..'); * 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 @@ -45,20 +45,20 @@ var notp = require('..'); */ exports.testHOTP = function(beforeExit, assert) { var args = { - W : 0, - K : '12345678901234567890' + window : 0, + key : '12345678901234567890' }; var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; - // Check for failure - args.C = 0; - args.P = 'WILLNOTPASS'; + // counterheck for failure + args.counter = 0; + args.token = 'windowILLNOTtokenASS'; assert.ok(!notp.checkHOTP(args), 'Should not pass'); - // Check for passes + // counterheck for passes for(i=0;i= 9 - args.W = 8; - assert.ok(notp.checkHOTP(args), 'Should pass for value of W >= 9'); + // counterheck that the test should pass for window >= 9 + args.window = 8; + assert.ok(notp.checkHOTP(args), '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) { +exports.testTOTtokenOutOfSync = function(beforeExit, assert) { var args = { - K : '12345678901234567890', - P : '279037', + key : '12345678901234567890', + token : '279037', _t : 1999999909*1000 }; - // Check that the test should fail for W < 2 - args.W = 2; - assert.ok(!notp.checkTOTP(args), 'Should not pass for value of W < 3'); + // counterheck that the test should fail for window < 2 + args.window = 2; + assert.ok(!notp.checkTOTP(args), 'Should not pass for value of window < 3'); - // Check that the test should pass for W >= 3 - args.W = 3; - assert.ok(notp.checkTOTP(args), 'Should pass for value of W >= 3'); + // counterheck that the test should pass for window >= 3 + args.window = 3; + assert.ok(notp.checkTOTP(args), 'Should pass for value of window >= 3'); }; /* - * Test getHOTP function. Uses same test values as for checkHOTP + * Test getHOTtoken function. Uses same test values as for checkHOTtoken */ -exports.testGetHOTP = function(beforeExit, assert) { +exports.testGetHOTtoken = function(beforeExit, assert) { var args = { - W : 0, - K : '12345678901234567890' + window : 0, + key : '12345678901234567890' }; var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; - // Check for passes + // counterheck for passes for(i=0;i Date: Fri, 1 Jun 2012 00:06:43 -0400 Subject: [PATCH 09/18] remove `thirty-two` dependency The code does not use it, if a person wants to base32 encode, they can just install the package themselves and use it. --- package.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/package.json b/package.json index 243104b..acc57ce 100644 --- a/package.json +++ b/package.json @@ -15,9 +15,7 @@ "engines": { "node": ">= v0.4.10" }, - "dependencies": { - "thirty-two": "0.0.1" - }, + "dependencies": {} "devDependencies": { "expresso" : "0.9.0" } From 940938dd81ed30c454a5a6dc321fd61015627622 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Fri, 1 Jun 2012 00:07:29 -0400 Subject: [PATCH 10/18] package.json typo --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index acc57ce..49132ec 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "engines": { "node": ">= v0.4.10" }, - "dependencies": {} + "dependencies": {}, "devDependencies": { "expresso" : "0.9.0" } From e633d857fdf2ce2a4b7a403bca49521c434ea9fa Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Fri, 1 Jun 2012 00:08:40 -0400 Subject: [PATCH 11/18] update readme with new argument names --- Readme.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Readme.md b/Readme.md index cdbd4a9..cd7a824 100644 --- a/Readme.md +++ b/Readme.md @@ -18,8 +18,8 @@ var args = {}; //.... 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'; +args.key = 'TOTP key for user... could be stored in DB'; +args.token = 'User supplied TOTP value'; // Check TOTP is correct var login = notp.checkTOTP(args); @@ -72,8 +72,8 @@ console.log('Token valid, sync value is %s', login.delta); ```javascript var opt = { - K : 'USER SPECIFIC KEY', // Should be ASCII string - P : 'USER SUPPLIED PASSCODE' + key : 'USER SPECIFIC KEY', // Should be ASCII string + token : 'USER SUPPLIED PASSCODE' }; var res = notp.checkHOTP(opt); @@ -127,8 +127,8 @@ console.log('valid, counter is out of sync by %d steps', res.delta); ```javascript var opt = { - K : 'USER SPECIFIC KEY', // Should be ASCII string - P : 'USER SUPPLIED PASSCODE' + key : 'USER SPECIFIC KEY', // Should be ASCII string + token : 'USER SUPPLIED PASSCODE' }; var res = notp.checkTOTP(opt); @@ -160,8 +160,8 @@ console.log('valid, counter is out of sync by %d steps', res.delta); ```javascript var token = notp.getHOTP({ - K : 'USER SPECIFIC KEY', // Should be ASCII string - C : 5 // COUNTER VALUE + key : 'USER SPECIFIC KEY', // Should be ASCII string + token : 5 // COUNTER VALUE }); ``` @@ -186,7 +186,7 @@ var token = notp.getHOTP({ ```javascript var token = notp.getTOTP({ - K : 'USER SPECIFIC KEY' // Should be ASCII string + key : 'USER SPECIFIC KEY' // Should be ASCII string }); ``` From cfa2ecddb18d32019b8a3cef6ca5bcee1d22d30c Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Fri, 1 Jun 2012 00:33:55 -0400 Subject: [PATCH 12/18] rework api make two subobjects `hotp` and `totp` with gen and verify methods --- Readme.md | 64 ++++++------------ index.js | 181 ++++++++++++++++++++++++++------------------------- test/notp.js | 120 ++++++++++++++++------------------ 3 files changed, 168 insertions(+), 197 deletions(-) diff --git a/Readme.md b/Readme.md index cd7a824..55ecf50 100644 --- a/Readme.md +++ b/Readme.md @@ -14,15 +14,13 @@ IMPORTANT: The NOTP library accepts ASCII strings as keys, but the Google Authen ```javascript var notp = require('notp'); -var args = {}; - //.... some initial login code, that receives the TOTP / HTOP // token from the user -args.key = 'TOTP key for user... could be stored in DB'; -args.token = 'User supplied TOTP value'; +var key = 'TOTP key for user... could be stored in DB'; +var token = 'User supplied TOTP value'; // Check TOTP is correct -var login = notp.checkTOTP(args); +var login = notp.totp.verify(token, key); // invalid token if (!login) { @@ -34,7 +32,7 @@ console.log('Token valid, sync value is %s', login.delta); ``` # API -##notp.checkHOTP(args) +##hotp.verify(token, key, opt) Check a One Time Password based on a counter. @@ -47,12 +45,8 @@ console.log('Token valid, sync value is %s', login.delta); 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. + opt 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 @@ -71,12 +65,10 @@ console.log('Token valid, sync value is %s', login.delta); **Example** ```javascript -var opt = { - key : 'USER SPECIFIC KEY', // Should be ASCII string - token : 'USER SUPPLIED PASSCODE' -}; +var key = 'USER SPECIFIC KEY', // Should be ASCII string +var token = 'USER SUPPLIED PASSCODE' -var res = notp.checkHOTP(opt); +var res = notp.hotp.verify(token, key, opt); // not valid if (!res) { @@ -86,7 +78,7 @@ if (!res) { console.log('valid, counter is out of sync by %d steps', res.delta); ``` -##notp.checkTOTP(args, err, cb) +##totp.verify(token, key, opt) Check a One Time Password based on a timer. @@ -100,12 +92,7 @@ console.log('valid, counter is out of sync by %d steps', res.delta); 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. - + opt 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 @@ -126,12 +113,10 @@ console.log('valid, counter is out of sync by %d steps', res.delta); **Example** ```javascript -var opt = { - key : 'USER SPECIFIC KEY', // Should be ASCII string - token : 'USER SUPPLIED PASSCODE' -}; +var key = 'USER SPECIFIC KEY', // Should be ASCII string +var token = 'USER SUPPLIED PASSCODE' -var res = notp.checkTOTP(opt); +var res = notp.totp.verify(token, key, opt); // not valid if (!res) { @@ -141,7 +126,7 @@ if (!res) { console.log('valid, counter is out of sync by %d steps', res.delta); ``` -##notp.getHOTP(args, err, cb) +##hotp.gen(key, opt) Generate a counter based One Time Password @@ -149,23 +134,19 @@ console.log('valid, counter is out of sync by %d steps', res.delta); 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 - + opt counter - Counter value. This should be stored by the application, must be user specific, and be incremented for each request. **Example** ```javascript -var token = notp.getHOTP({ - key : 'USER SPECIFIC KEY', // Should be ASCII string - token : 5 // COUNTER VALUE +var token = notp.hotp.gen(key, { + counter : 5 // COUNTER VALUE }); ``` -##notp.getTOTP(args, err, cb) +##totp.gen(key, opt) Generate a time based One Time Password @@ -173,10 +154,7 @@ var token = notp.getHOTP({ 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 - + opt time - The time step of the counter. This must be the same for every request and is used to calculate C. @@ -185,9 +163,7 @@ var token = notp.getHOTP({ **Example** ```javascript -var token = notp.getTOTP({ - key : 'USER SPECIFIC KEY' // Should be ASCII string -}); +var token = notp.totp.gen(key); ``` ## License diff --git a/index.js b/index.js index 73ff375..a3ad53d 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,52 @@ 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. * @@ -30,17 +76,15 @@ var crypto = require('crypto'); * be user specific, and be incremented for each request. * */ -module.exports.checkHOTP = function(opt) { - +hotp.verify = function(token, key, opt) { var window = opt.window || 50; var counter = opt.counter || 0; - var token = opt.token || ''; // 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.getHOTP(opt) === token) { + if(this.gen(key, opt) === token) { // We have found a matching code, trigger callback // and pass offset return { delta: i - counter }; @@ -51,6 +95,45 @@ module.exports.checkHOTP = function(opt) { 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. @@ -83,8 +166,7 @@ module.exports.checkHOTP = function(opt) { * Default - 30 * */ -module.exports.checkTOTP = function(opt) { - +totp.verify = function(token, key, opt) { var time = opt.time || 30; var _t = new Date().getTime(); @@ -102,92 +184,11 @@ module.exports.checkTOTP = function(opt) { // This is the number of time steps in seconds since T0 opt.counter = Math.floor((_t / 1000) / time); - return module.exports.checkHOTP(opt); + return hotp.verify(token, key, opt); }; - -/** - * 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. - * - */ -module.exports.getHOTP = function(opt) { - var key = opt.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); -}; - - -/** - * 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 - * - */ -module.exports.getTOTP = function(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 this.getHOTP(opt); -}; +module.exports.hotp = hotp; +module.exports.totp = totp; /** * convert an integer to a byte array diff --git a/test/notp.js b/test/notp.js index 7931c5a..8843ab2 100644 --- a/test/notp.js +++ b/test/notp.js @@ -44,22 +44,20 @@ var notp = require('..'); * see http://tools.ietf.org/html/rfc4226 */ exports.testHOTP = function(beforeExit, assert) { - var args = { + var key = '12345678901234567890'; + var opt = { window : 0, - key : '12345678901234567890' }; var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; // counterheck for failure - args.counter = 0; - args.token = 'windowILLNOTtokenASS'; - assert.ok(!notp.checkHOTP(args), 'Should not pass'); + opt.counter = 0; + assert.ok(!notp.hotp.verify('WILL NOT PASS', key, opt), 'Should not pass'); // counterheck for passes for(i=0;i= 9 - args.window = 8; - assert.ok(notp.checkHOTP(args), 'Should pass for value of window >= 9'); + opt.window = 8; + assert.ok(notp.hotp.verify(token, key, opt), 'Should pass for value of window >= 9'); }; @@ -140,66 +139,61 @@ exports.testHOTPtokenOutOfSync = function(beforeExit, assert) { * counterheck for codes that are out of sync * windowe are going to use a value of T = 1999999909 (91s behind 2000000000) */ -exports.testTOTtokenOutOfSync = function(beforeExit, assert) { +exports.testTOTPOutOfSync = function(beforeExit, assert) { - var args = { - key : '12345678901234567890', - token : '279037', + var key = '12345678901234567890'; + var token = '279037'; + + var opt = { _t : 1999999909*1000 }; // counterheck that the test should fail for window < 2 - args.window = 2; - assert.ok(!notp.checkTOTP(args), 'Should not pass for value of window < 3'); + opt.window = 2; + assert.ok(!notp.totp.verify(token, key, opt), 'Should not pass for value of window < 3'); // counterheck that the test should pass for window >= 3 - args.window = 3; - assert.ok(notp.checkTOTP(args), 'Should pass for value of window >= 3'); + opt.window = 3; + assert.ok(notp.totp.verify(token, key, opt), 'Should pass for value of window >= 3'); }; -/* - * Test getHOTtoken function. Uses same test values as for checkHOTtoken - */ -exports.testGetHOTtoken = function(beforeExit, assert) { - var args = { +exports.hotp_gen = function(beforeExit, assert) { + var key = '12345678901234567890'; + var opt = { window : 0, - key : '12345678901234567890' }; var HOTP = ['755224', '287082','359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']; // counterheck for passes for(i=0;i Date: Fri, 1 Jun 2012 16:00:40 -0400 Subject: [PATCH 13/18] update .gitignore - add node_modules - remove other cruft --- .gitignore | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index efdba9c..3c3629e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1 @@ -# OS generated files # -###################### -.DS_Store -ehthumbs.db -Icon -Thumbs.db +node_modules From ad29941dab44a823b62655bf6c4f640ea8e9d67a Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Sun, 3 Jun 2012 15:57:43 -0400 Subject: [PATCH 14/18] add google auth example/details to readme Basic example on using `thirty-two` module to do base32 encoding and creating a barcode URI --- Readme.md | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/Readme.md b/Readme.md index 55ecf50..082cd1b 100644 --- a/Readme.md +++ b/Readme.md @@ -9,20 +9,18 @@ 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. - ```javascript var notp = require('notp'); -//.... some initial login code, that receives the TOTP / HTOP -// token from the user -var key = 'TOTP key for user... could be stored in DB'; -var token = 'User supplied TOTP value'; +//.... some initial login code, that receives the user details and TOTP / HOTP token -// Check TOTP is correct +var key = 'secret key for user... could be stored in DB'; +var token = 'user supplied one time use token'; + +// Check TOTP is correct (HOTP if hotp pass type) var login = notp.totp.verify(token, key); -// invalid token +// invalid token if login is null if (!login) { return console.log('Token invalid'); } @@ -31,6 +29,26 @@ if (!login) { 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 ##hotp.verify(token, key, opt) From 6c4ac1e94d7114f10ba14637310439fbf28661da Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Sun, 3 Jun 2012 18:01:30 -0400 Subject: [PATCH 15/18] cleanup README - move license section to separate file - remove examples, api documentation is enough for now --- LICENSE | 22 ++++++++++++++++ Readme.md | 76 ++----------------------------------------------------- 2 files changed, 24 insertions(+), 74 deletions(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f344640 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2011 Guy Halford-Thompson + +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. diff --git a/Readme.md b/Readme.md index 082cd1b..74c1e11 100644 --- a/Readme.md +++ b/Readme.md @@ -1,5 +1,5 @@ # 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 @@ -44,7 +44,7 @@ var key = 'secret key for the user'; 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'; +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) @@ -80,22 +80,6 @@ Note: If your label has spaces or other invalid uri characters you will need to be user specific, and be incremented for each request. -**Example** - -```javascript -var key = 'USER SPECIFIC KEY', // Should be ASCII string -var token = 'USER SUPPLIED PASSCODE' - -var res = notp.hotp.verify(token, key, opt); - -// not valid -if (!res) { - return console.log('invalid'); -} - -console.log('valid, counter is out of sync by %d steps', res.delta); -``` - ##totp.verify(token, key, opt) @@ -127,23 +111,6 @@ console.log('valid, counter is out of sync by %d steps', res.delta); Default - 30 - -**Example** - -```javascript -var key = 'USER SPECIFIC KEY', // Should be ASCII string -var token = 'USER SUPPLIED PASSCODE' - -var res = notp.totp.verify(token, key, opt); - -// not valid -if (!res) { - return console.log('invalid'); -} - -console.log('valid, counter is out of sync by %d steps', res.delta); -``` - ##hotp.gen(key, opt) Generate a counter based One Time Password @@ -156,14 +123,6 @@ console.log('valid, counter is out of sync by %d steps', res.delta); counter - Counter value. This should be stored by the application, must be user specific, and be incremented for each request. -**Example** - -```javascript -var token = notp.hotp.gen(key, { - counter : 5 // COUNTER VALUE -}); -``` - ##totp.gen(key, opt) Generate a time based One Time Password @@ -178,34 +137,3 @@ var token = notp.hotp.gen(key, { Default - 30 -**Example** - -```javascript -var token = notp.totp.gen(key); -``` - -## License - -(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. - From 022ef8d128d09696dcff10cf66dbbb1e7da4c3e6 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Sun, 3 Jun 2012 18:15:56 -0400 Subject: [PATCH 16/18] add migrating from 1.x to 2.x to readme --- Readme.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Readme.md b/Readme.md index 74c1e11..816403d 100644 --- a/Readme.md +++ b/Readme.md @@ -137,3 +137,29 @@ Note: If your label has spaces or other invalid uri characters you will need to Default - 30 +# Migrating from 1.x to 2.x + +## 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. + +## Changed + +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. + +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. + +* `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)` + +## Args + +The argument names have also changed to better describe the purpose of the argument. + +* `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` + From 10381a3a883b57a6d92a3b7ddfa410b62a8b3066 Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Sun, 3 Jun 2012 18:27:32 -0400 Subject: [PATCH 17/18] update README formatting for API --- Readme.md | 95 ++++++++++++++++++------------------------------------- 1 file changed, 30 insertions(+), 65 deletions(-) diff --git a/Readme.md b/Readme.md index 816403d..cded5ca 100644 --- a/Readme.md +++ b/Readme.md @@ -52,90 +52,55 @@ Note: If your label has spaces or other invalid uri characters you will need to # API ##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 - 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. +### 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 +** 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`) ##totp.verify(token, key, opt) +Check a time based one time password for validity - Check a One Time Password based on a timer. +Returns null if token is not valid for given key and options. - First argument of callback is true if password check is successful, - or false if check fails. +Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server. - 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 +** 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 - Arguments: - - opt - 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 calculat C. - - Default - 30 +** time ** +> The time step of the counter. This must be the same for every request and is used to calculate C. +> Default - 30 ##hotp.gen(key, opt) - Generate a counter based One Time Password +Return a counter based one time password - First argument of callback is the value of the One Time Password - - Arguments: - - opt - counter - Counter value. This should be stored by the application, must - be user specific, and be incremented for each request. +### opt +** counter ** +> Counter value. This should be stored by the application, must be user specific, and be incremented for each request. ##totp.gen(key, opt) - Generate a time based One Time Password +Return a time based one time password - First argument of callback is the value of the One Time Password - - Arguments: - - opt - time - The time step of the counter. This must be the same for - every request and is used to calculate C. - - Default - 30 +### opt +** time ** +> The time step of the counter. This must be the same for every request and is used to calculate C. +> Default - 30 # Migrating from 1.x to 2.x From 6ad05c5a7c1156c3268b2cd7346fb47d4a818d8d Mon Sep 17 00:00:00 2001 From: Roman Shtylman Date: Sun, 3 Jun 2012 18:29:06 -0400 Subject: [PATCH 18/18] README markdown formatting --- Readme.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Readme.md b/Readme.md index cded5ca..8fb232b 100644 --- a/Readme.md +++ b/Readme.md @@ -59,12 +59,12 @@ Returns null if token is not valid for given key and options. Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server. ### opt -** window ** +**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 -** counter ** +**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`) ##totp.verify(token, key, opt) @@ -76,12 +76,12 @@ Returns null if token is not valid for given key and options. Returns an object `{delta: #}` if the token is valid. `delta` is the count skew between client and server. ### opt -** window ** +**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 -** time ** +**time** > The time step of the counter. This must be the same for every request and is used to calculate C. > Default - 30 @@ -90,7 +90,7 @@ Returns an object `{delta: #}` if the token is valid. `delta` is the count skew Return a counter based one time password ### opt -** counter ** +**counter** > Counter value. This should be stored by the application, must be user specific, and be incremented for each request. ##totp.gen(key, opt) @@ -98,7 +98,7 @@ Return a counter based one time password Return a time based one time password ### opt -** time ** +**time** > The time step of the counter. This must be the same for every request and is used to calculate C. > Default - 30