sea.js refactored to use NodeJS crypto and Web Cryptography API for better performance & security

This commit is contained in:
Mika Helander 2017-08-29 01:09:09 +03:00
parent 08e239ee2d
commit 4c31edd468

321
sea.js
View File

@ -7,8 +7,34 @@
/* THIS IS AN EARLY ALPHA!!! */ /* THIS IS AN EARLY ALPHA!!! */
if(typeof require !== "undefined"){ var Gun = require('./gun') } var nodeCrypto = require('crypto');
if(typeof window !== "undefined"){ var Gun = window.Gun } var ecCrypto = require('eccrypto');
var Gun = Gun || require('gun');
// Following enable Web Cryptography API use in NodeJS
var crypto = (typeof window !== 'undefined' && window.crypto)
|| { subtle: require('subtle') };
var TextEncoder = (typeof window !== 'undefined' && window.TextEncoder)
|| require('text-encoding').TextEncoder;
var TextDecoder = (typeof window !== 'undefined' && window.TextDecoder)
|| require('text-encoding').TextDecoder;
var Buffer = (typeof window !== 'undefined' && require('./buffer/').Buffer)
|| require('Buffer');
var pbkdf2 = {
hash: 'SHA-256', // Was 'SHA-1'
iter: 50000,
ks: 64
};
var ecdh = {
enc: (typeof window !== 'undefined' && 'secp256r1') || 'prime256v1'
};
var aes = {
enc: 'aes-256-cbc'
};
// let's extend the gun chain with a `user` function. // let's extend the gun chain with a `user` function.
// only one user can be logged in at a time, per gun instance. // only one user can be logged in at a time, per gun instance.
@ -27,10 +53,10 @@
var gun = Gun(); var gun = Gun();
var user = gun.user(); var user = gun.user();
gun.on('auth', function(at){ Gun.on('auth', function(at){
// do something once logged in. // do something once logged in.
}); });
gun.on('secure', function(at){ Gun.on('secure', function(at){
// enforce some rules about shared app level data // enforce some rules about shared app level data
var no; var no;
if(no){ return } if(no){ return }
@ -57,16 +83,23 @@
} }
var user = {alias: alias, salt: Gun.text.random(64)}; var user = {alias: alias, salt: Gun.text.random(64)};
// pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it. // pseudo-randomly create a salt, then use CryptoJS's PBKDF2 function to extend the password with it.
SEA.proof(pass, user.salt, function(proof){ SEA.proof(pass, user.salt).then(function(proof){
// this will take some short amount of time to produce a proof, which slows brute force attacks. // this will take some short amount of time to produce a proof, which slows brute force attacks.
var pair = SEA.pair(); SEA.pair().then(function(pair){
// now we have generated a brand new ECDSA key pair for the user account. // now we have generated a brand new ECDSA key pair for the user account.
user.pub = pair.pub; user.pub = pair.pub;
// the user's public key doesn't need to be signed. But everything else needs to be signed with it! // the user's public key doesn't need to be signed. But everything else needs to be signed with it!
user.alias = SEA.write(alias, pair.priv); SEA.write(alias, pair.priv).then(function(sAlias){
user.salt = SEA.write(user.salt, pair.priv); user.alias = sAlias;
return SEA.write(user.salt, pair.priv);
}).then(function(sSalt){
user.salt = sSalt;
// to keep the private key safe, we AES encrypt it with the proof of work! // to keep the private key safe, we AES encrypt it with the proof of work!
user.auth = SEA.write(SEA.en(pair.priv, proof), pair.priv); return SEA.en(pair.priv, proof);
}).then(function(encVal){
return SEA.write(encVal, pair.priv);
}).then(function(sAuth){
user.auth = sAuth;
var tmp = 'pub/'+pair.pub; var tmp = 'pub/'+pair.pub;
//console.log("create", user, pair.pub); //console.log("create", user, pair.pub);
// awesome, now we can actually save the user with their public key as their ID. // awesome, now we can actually save the user with their public key as their ID.
@ -77,9 +110,12 @@
cb({ok: 0, pub: pair.pub}); cb({ok: 0, pub: pair.pub});
}); });
}); });
} });
});
};
// now that we have created a user, we want to authenticate them! // now that we have created a user, we want to authenticate them!
User.auth = function(alias, pass, cb){ User.auth = function(props, cb){
var alias = props.alias, pass = props.pass, newpass = props.newpass;
var root = this.back(-1); var root = this.back(-1);
cb = cb || function(){}; cb = cb || function(){};
// load all public keys associated with the username alias we want to log in with. // load all public keys associated with the username alias we want to log in with.
@ -98,12 +134,18 @@
ev.off(); ev.off();
if(!at.put){ return cb({err: "Public key does not exist!"}) } if(!at.put){ return cb({err: "Public key does not exist!"}) }
// attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.) // attempt to PBKDF2 extend the password with the salt. (Verifying the signature gives us the plain text salt.)
SEA.proof(pass, SEA.read(at.put.salt, key), function(proof){ SEA.read(at.put.salt, key).then(function(salt){
return SEA.proof(pass, salt);
}).then(function(proof){
// the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force. // the proof of work is evidence that we've spent some time/effort trying to log in, this slows brute force.
var priv = SEA.de(SEA.read(at.put.auth, key), proof); return SEA.read(at.put.auth, key).then(function(auth){
return SEA.de(auth, proof);
});
}).then(function(priv){
// now we have AES decrypted the private key, from when we encrypted it with the proof at registration. // now we have AES decrypted the private key, from when we encrypted it with the proof at registration.
if(priv){ // if we were successful, then that means... if(priv){ // if we were successful, then that means...
// we're logged in! // we're logged in!
function doLogin(){
var user = root._.user; var user = root._.user;
// add our credentials in-memory only to our root gun instance // add our credentials in-memory only to our root gun instance
user._ = at.gun._; user._ = at.gun._;
@ -116,7 +158,35 @@
// callbacks success with the user data credentials. // callbacks success with the user data credentials.
cb(user._); cb(user._);
// emit an auth event, useful for page redirects and stuff. // emit an auth event, useful for page redirects and stuff.
root.on('auth', user._); Gun.on('auth', user._);
}
if(newpass) {
// password update so encrypt private key using new pwd + salt
var newsalt = Gun.text.random(64);
SEA.proof(newpass, newsalt).then(function(proof){
SEA.en(priv, proof).then(function(encVal){
return SEA.write(encVal, priv).then(function(sAuth){
return { pub: key, auth: sAuth };
});
}).then(function(user){
return SEA.write(alias, priv).then(function(sAlias){
user.alias = sAlias; return user;
});
}).then(function(user){
return SEA.write(newsalt, priv).then(function(sSalt){
user.salt = sSalt; return user;
});
}).then(function(user){
var tmp = 'pub/'+key;
// awesome, now we can update the user using public key ID.
root.get(tmp).put(user);
// then we're done
doLogin();
});
});
} else {
doLogin();
}
return; return;
} }
// Or else we failed to log in... // Or else we failed to log in...
@ -126,7 +196,7 @@
}); });
}); });
}); });
} };
// After we have a GUN extension to make user registration/login easy, we then need to handle everything else. // After we have a GUN extension to make user registration/login easy, we then need to handle everything else.
// We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change) // We do this with a GUN adapter, we first listen to when a gun instance is created (and when its options change)
@ -135,7 +205,6 @@
at.sea = {own: {}}; at.sea = {own: {}};
at.gun.on('in', security, at); // now listen to all input data, acting as a firewall. at.gun.on('in', security, at); // now listen to all input data, acting as a firewall.
at.gun.on('out', signature, at); // and output listeners, to encrypt outgoing data. at.gun.on('out', signature, at); // and output listeners, to encrypt outgoing data.
at.gun.on('node', every, at);
} }
this.to.next(at); // make sure to call the "next" middleware adapter. this.to.next(at); // make sure to call the "next" middleware adapter.
}); });
@ -153,16 +222,18 @@
// Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous! // Here is a problem: Multiple public keys can "claim" any node's ID, so this is dangerous!
// This means we should ONLY trust our "friends" (our key ring) public keys, not any ones. // This means we should ONLY trust our "friends" (our key ring) public keys, not any ones.
// I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile! // I have not yet added that to SEA yet in this alpha release. That is coming soon, but beware in the meanwhile!
function every(at){ Gun.on('node', function(at){ // TODO: Warning: Need to switch to `gun.on('node')`! Do not use `Gun.on('node'` in your apps!
var own = (at.gun.back(-1)._).sea.own, soul = at.get, pub = own[soul] || soul.slice(4), vertex = (at.gun._).put; var own = (at.gun.back(-1)._).sea.own, soul = at.get, pub = own[soul] || soul.slice(4), vertex = (at.gun._).put;
Gun.node.is(at.put, function(val, key, node){ // for each property on the node. Gun.node.is(at.put, function(val, key, node){ // for each property on the node.
vertex[key] = node[key] = val = SEA.read(val, pub); // verify signature and get plain value. SEA.read(val, pub).then(function(data){
vertex[key] = node[key] = val = data; // verify signature and get plain value.
if(val && val['#'] && (key = Gun.val.rel.is(val))){ // if it is a relation / edge if(val && val['#'] && (key = Gun.val.rel.is(val))){ // if it is a relation / edge
if('alias/' === soul.slice(0,6)){ return } // if it is itself if('alias/' === soul.slice(0,6)){ return } // if it is itself
own[key] = pub; // associate the public key with a node own[key] = pub; // associate the public key with a node
} }
}); });
}; });
})
// signature handles data output, it is a proxy to the security function. // signature handles data output, it is a proxy to the security function.
function signature(at){ function signature(at){
@ -222,39 +293,49 @@
} }
if(at.user){ // if we are logged in if(at.user){ // if we are logged in
if(tmp === at.user._.pub){ // as this user if(tmp === at.user._.pub){ // as this user
val = node[key] = SEA.write(val, at.user._.sea); // then sign our updates as we output them. SEA.write(val, at.user._.sea).then(function(data){
val = node[key] = data; // then sign our updates as we output them.
});
} // (if we are lying about our signature, other peer's will reject our update) } // (if we are lying about our signature, other peer's will reject our update)
} }
if(u === (val = SEA.read(val, tmp))){ // make sure the signature matches the account it claims to be on. // TODO: this likely isn't working as expected
SEA.read(val, tmp).then(function(data){
if(u === (val = data)){ // make sure the signature matches the account it claims to be on.
return no = true; // reject any updates that are signed with a mismatched account. return no = true; // reject any updates that are signed with a mismatched account.
} }
}); });
});
} else } else
if(at.user && (tmp = at.user._.sea)){ // not special case, if we are logged in, then if(at.user && (tmp = at.user._.sea)){ // not special case, if we are logged in, then
Gun.obj.map(node, function(val, key){ // any data we output needs to Gun.obj.map(node, function(val, key){ // any data we output needs to
if('_' === key){ return } if('_' === key){ return }
node[key] = SEA.write(val, tmp); // be signed by our logged in account. SEA.write(val, tmp).then(function(data){
node[key] = data; // be signed by our logged in account.
});
}); });
} else // TODO: BUG! These two if-statements are not exclusive to each other!!! } else // TODO: BUG! These two if-statements are not exclusive to each other!!!
if(tmp = sea.own[soul]){ // not special case, if we receive an update on an ID associated with a public key, then if(tmp = sea.own[soul]){ // not special case, if we receive an update on an ID associated with a public key, then
Gun.obj.map(node, function(val, key){ // for each over the property/values Gun.obj.map(node, function(val, key){ // for each over the property/values
if('_' === key){ return } if('_' === key){ return }
if(u === (val = SEA.read(val, tmp))){ // and verify they were signed by the associated public key! // TODO: this likely isn't working as expected
SEA.read(val, tmp).then(function(data){
if(u === (val = data)){ // and verify they were signed by the associated public key!
return no = true; // reject the update if it fails to match. return no = true; // reject the update if it fails to match.
} }
}); });
});
} else { // reject any/all other updates by default. } else { // reject any/all other updates by default.
return no = true; return no = true;
} }
}); });
if(no){ // if we got a rejection then... if(no){ // if we got a rejection then...
if(!at || !Gun.tag.secure){ return } if(!at || !Gun.tag.secure){ return }
cat.on('secure', function(at){ // (below) emit a special event for the developer to handle security. Gun.on('secure', function(at){ // (below) emit a special event for the developer to handle security.
this.off(); this.off();
if(!at){ return } if(!at){ return }
to.next(at); // and if they went ahead and explicitly called "next" (to us) with data, then approve. to.next(at); // and if they went ahead and explicitly called "next" (to us) with data, then approve.
}); });
cat.on('secure', at); Gun.on('secure', at);
return; // else wise, reject. return; // else wise, reject.
} }
//console.log("SEA put", at.put); //console.log("SEA put", at.put);
@ -262,63 +343,166 @@
return to.next(at); return to.next(at);
} }
to.next(at); // pass forward any data we do not know how to handle or process (this allows custom security protocols). to.next(at); // pass forward any data we do not know how to handle or process (this allows custom security protocols).
};
// Does enc/dec key like OpenSSL - works with CryptoJS encryption/decryption
function makeKey(p, s) {
var ps = Buffer.concat([ new Buffer(p, 'utf8'), s ]);
var h128 = new Buffer(nodeCrypto.createHash('md5').update(ps).digest('hex'), 'hex');
// TODO: 'md5' is insecure, do we need OpenSSL compatibility anymore ?
return Buffer.concat([
h128,
new Buffer(nodeCrypto.createHash('md5').update(
Buffer.concat([ h128, ps ]).toString('base64'), 'base64'
).digest('hex'), 'hex')
]);
} }
function SEA(){}; var nHash = pbkdf2.hash.replace('-', '').toLowerCase();
// create a wrapper library around CryptoJS and JSRSAsign.
// of course, these libraries are required. A bundle is included in lib/cryptography.js // These SEA functions support both callback AND Promises
if(typeof CryptoJS === "undefined"){ console.log("Error: CryptoJS required!") } var SEA = {};
if(typeof KJUR === "undefined"){ console.log("Error: JSRSAsign required!") } // create a wrapper library around NodeJS crypto & ecCrypto and Web Crypto API.
// now wrap the various AES, ECDSA, PBKDF2 functions we called above. // now wrap the various AES, ECDSA, PBKDF2 functions we called above.
SEA.proof = function(pass,salt,cb){ SEA.proof = function(pass,salt,cb){
cb(CryptoJS.PBKDF2(pass, salt, {keySize: 512/32, iterations: 100}).toString(CryptoJS.enc.Base64)); var doProof = (typeof window !== 'undefined' && function(resolve, reject){
crypto.subtle.importKey( // For browser crypto.subtle works fine
'raw', new TextEncoder().encode(pass), {name: 'PBKDF2'}, false, ['deriveBits']
).then(function(key){
return crypto.subtle.deriveBits({
name: 'PBKDF2',
iterations: pbkdf2.iter,
salt: new TextEncoder().encode(salt),
hash: pbkdf2.hash,
}, key, pbkdf2.ks*8);
}).then(function(result){
return new Buffer(result, 'binary').toString('base64');
}).then(resolve).catch(function(e){Gun.log(e); reject(e)});
}) || function(resolve, reject){ // For NodeJS crypto.pkdf2 rocks
nodeCrypto.pbkdf2(pass,new Buffer(salt, 'utf8'),pbkdf2.iter,pbkdf2.ks,nHash,function(err,hash){
resolve(!err && hash && hash.toString('base64'));
});
}; };
SEA.pair = function(){ if(cb){doProof(cb, function(){cb()})} else {return new Promise(doProof)}
var master = new KJUR.crypto.ECDSA({"curve": 'secp256r1'});
var pair = master.generateKeyPairHex();
return {pub: pair.ecpubhex, priv: pair.ecprvhex};
}; };
SEA.sign = function(m, p){ SEA.pair = function(cb){
var sig = new KJUR.crypto.Signature({'alg': 'SHA256withECDSA'}); var doPair = function(resolve, reject){
sig.initSign({'ecprvhex': p, 'eccurvename': 'secp256r1'}); var priv = nodeCrypto.randomBytes(32);
sig.updateString(JSON.stringify(m)); resolve({
return sig.sign(); pub: new Buffer(ecCrypto.getPublic(priv), 'binary').toString('hex'),
} priv: new Buffer(priv, 'binary').toString('hex')
SEA.verify = function(m, p, s){ });
var sig = new KJUR.crypto.Signature({'alg': 'SHA256withECDSA', 'prov': "cryptojs/jsrsa"}), yes; };
if(cb){doPair(cb, function(){cb()})} else {return new Promise(doPair)}
};
SEA.derive = function(m,p,cb){
var doDerive = function(resolve, reject){
ecCrypto.derive(new Buffer(p, 'hex'), new Buffer(m, 'hex'))
.then(function(secret){
resolve(new Buffer(secret, 'binary').toString('hex'));
}).catch(function(e){Gun.log(e); reject(e)});
};
if(cb){doDerive(cb, function(){cb()})} else {return new Promise(doDerive)}
};
SEA.sign = function(m, p, cb){
var doSign = function(resolve, reject){
ecCrypto.sign(
new Buffer(p, 'hex'),
nodeCrypto.createHash(nHash).update(JSON.stringify(m), 'utf8').digest()
).then(function(sig){
resolve(new Buffer(sig, 'binary').toString('hex'));
}).catch(function(e){Gun.log(e); reject(e)});
};
if(cb){doSign(cb, function(){cb()})} else {return new Promise(doSign)}
};
SEA.verify = function(m, p, s, cb){
var doVerify = function(resolve, reject){
ecCrypto.verify(
new Buffer(p, 'hex'),
nodeCrypto.createHash(nHash).update(JSON.stringify(m), 'utf8').digest(),
new Buffer(s, 'hex')
).then(function(){resolve(true)}).catch(function(e){Gun.log(e);reject(e)})
};
if(cb){doVerify(cb, function(){cb()})} else {return new Promise(doVerify)}
};
SEA.en = function(m,p,cb){
var doEncrypt = function(resolve, reject){
var s = nodeCrypto.randomBytes(8);
var iv = nodeCrypto.randomBytes(16);
var r = {iv: iv.toString('hex'), s: s.toString('hex')};
var key = makeKey(p, s);
if (typeof window !== 'undefined'){ // Browser doesn't run createCipheriv
crypto.subtle.importKey('raw', key, 'AES-CBC', false, ['encrypt'])
.then(function(aesKey){
crypto.subtle.encrypt({
name: 'AES-CBC', iv: iv
}, aesKey, new TextEncoder().encode(JSON.stringify(m))).then(function(ct){
r.ct = new Buffer(ct, 'binary').toString('base64');
return JSON.stringify(r);
}).then(resolve).catch(function(e){Gun.log(e); reject(e)});
}).catch(function(e){Gun.log(e); reject(e)});
} else { // NodeJS doesn't support crypto.subtle.importKey properly
try{ try{
sig.initVerifyByPublicKey({'ecpubhex': p, 'eccurvename': 'secp256r1'}); var cipher = nodeCrypto.createCipheriv(aes.enc, key, iv);
sig.updateString(JSON.stringify(m)); r.ct = cipher.update(m, 'utf8', 'base64');
yes = sig.verify(s); r.ct += cipher.final('base64');
}catch(e){Gun.log(e)} }catch(e){Gun.log(e); return reject(e)}
return yes; resolve(JSON.stringify(r));
} }
SEA.write = function(m, p){ };
return 'SEA'+JSON.stringify([m,SEA.sign(m,p)]); if(cb){doEncrypt(cb, function(){cb()})} else {return new Promise(doEncrypt)}
return JSON.stringify([m,SEA.sign(m,p)]); };
SEA.de = function(m,p,cb){
var doDecrypt = function(resolve, reject){
var d = JSON.parse(m);
var key = makeKey(p, new Buffer(d.s, 'hex'));
var iv = new Buffer(d.iv, 'hex');
if (typeof window !== 'undefined'){ // Browser doesn't run createDecipheriv
crypto.subtle.importKey('raw', key, 'AES-CBC', false, ['decrypt'])
.then(function(aesKey){
crypto.subtle.decrypt({
name: 'AES-CBC', iv: iv
}, aesKey, new Buffer(d.ct, 'base64')).then(function(ct){
var ctUtf8 = new TextDecoder('utf8').decode(ct);
var ret = JSON.parse(ctUtf8);
return ret;
}).then(resolve).catch(function(e){Gun.log(e); reject(e)});
}).catch(function(e){Gun.log(e); reject(e)});
} else { // NodeJS doesn't support crypto.subtle.importKey properly
try{
var decipher = nodeCrypto.createDecipheriv(aes.enc, key, iv);
r = decipher.update(d.ct, 'base64', 'utf8') + decipher.final('utf8');
}catch(e){Gun.log(e); return reject(e)}
resolve(r);
} }
SEA.read = function(m, p){ };
if(!m){ return } if(cb){doDecrypt(cb, function(){cb()})} else {return new Promise(doDecrypt)}
if(!m.slice || 'SEA[' !== m.slice(0,4)){ return m } };
SEA.write = function(m,p,cb){
var doSign = function(resolve, reject) {
SEA.sign(m, p).then(function(signature){
resolve('SEA'+JSON.stringify([m,signature]));
}).catch(function(e){Gun.log(e); reject(e)});
};
if(cb){doSign(cb, function(){cb()})} else {return new Promise(doSign)}
// TODO: what's this ?
// return JSON.stringify([m,SEA.sign(m,p)]);
};
SEA.read = function(m,p,cb){
var doRead = function(resolve, reject) {
if(!m){ return resolve(); }
if(!m.slice || 'SEA[' !== m.slice(0,4)){ return resolve(m); }
m = m.slice(3); m = m.slice(3);
try{m = JSON.parse(m); try{m = JSON.parse(m);
}catch(e){ return } }catch(e){ return reject(e); }
m = m || ''; m = m || '';
if(SEA.verify(m[0], p, m[1])){ SEA.verify(m[0], p, m[1]).then(function(ok){
return m[0]; resolve(ok && m[0]);
} });
}
SEA.en = function(m, p){
return CryptoJS.AES.encrypt(JSON.stringify(m), p, {format:SEA.froto}).toString();
}; };
SEA.de = function(m, p){ if(cb){doRead(cb, function(){cb()})} else {return new Promise(doRead)}
var r;
try{r = CryptoJS.AES.decrypt(m, p, {format:SEA.froto}).toString(CryptoJS.enc.Utf8);
r = JSON.parse(r);
}catch(e){};
return r;
}; };
SEA.froto = {stringify:function(a){var b={ct:a.ciphertext.toString(CryptoJS.enc.Base64)};a.iv&&(b.iv=a.iv.toString());a.salt&&(b.s=a.salt.toString());return JSON.stringify(b)},parse:function(a){a=JSON.parse(a);var b=CryptoJS.lib.CipherParams.create({ciphertext:CryptoJS.enc.Base64.parse(a.ct)});a.iv&&(b.iv=CryptoJS.enc.Hex.parse(a.iv));a.s&&(b.salt=CryptoJS.enc.Hex.parse(a.s));return b}};
Gun.SEA = SEA; Gun.SEA = SEA;
// all done! // all done!
@ -331,4 +515,5 @@
// Adding friends (trusted public keys), sending private messages, etc. // Adding friends (trusted public keys), sending private messages, etc.
// Cheers! Tell me what you think. // Cheers! Tell me what you think.
module.exports = Gun;
}()); }());