Example #1
0
    req.pipe(bl(function (err, data) {
      if (err) {
        return hasError(err.message)
      }

      var obj
      var computedSig = new Buffer(signBlob(options.secret, data))

      if (!bufferEq(new Buffer(sig), computedSig))
        return hasError('X-Hub-Signature does not match blob signature')

      try {
        obj = JSON.parse(data.toString())
      } catch (e) {
        return hasError(e)
      }

      // res.writeHead(200, { 'content-type': 'application/json' })
      // res.end('{"ok":true}')

      var emitData = {
          event   : event
        , id      : id
        , payload : obj
        , protocol: req.protocol
        , host    : req.headers['host']
        , url     : req.url
      }

      handler.emit(event, emitData)
      handler.emit('*', emitData)
    }))
Example #2
0
 return co(function* handler() {
   const key = yield crypto.pbkdf2(
     password,
     this.salt,
     this.iterations,
     this.hash.length,
     'sha256'
   )
   return constantTimeEquals(this.hash, key)
 }.bind(this))
Example #3
0
app.post('/updateApp', (req, res) => {
    var contype = req.headers['content-type'];
    if (!contype || contype.indexOf('application/json') !== 0) return res.status(400).send('Unknown content type');

    var payload = req.body;
    if (!payload || !req.headers['x-hub-signature']) return res.status(403).send('Invalid payload or the signature is missing');

    var computedSig = new Buffer(signBlob(config.secret, req.rawBody));

    if (!bufferEq(new Buffer(req.headers['x-hub-signature']), computedSig))
        return res.status(401).send('X-Hub-Signature does not match blob signature');

    log.debug('Webhook received; payload:', payload);

    if (!payload.release) return res.status(405).send('No \'release\' variable');
    if (config.updates == 'stable' && payload.release.prerelease) return res.status(204).send('I don\'t want pre-releases');

    var zipURL;
    _.each(payload.release.assets, (fileObject) => {
        if (fileObject.name.indexOf('homecontrol-') == 0) zipURL = fileObject.browser_download_url;
    });
    if (!zipURL) return res.status(404).send('I haven\'t found a valid named zip file to download.');

    fs.removeSync('./build.zip');
    fs.removeSync('./temp');
    download(zipURL, './build.zip', (path) => {
        var backedupConfig;
        var base = config.production ? './' : './deploy/';
        var zip = new AdmZip(path);
        zip.extractAllTo('./temp');

        try {
            fs.accessSync(path, fs.F_OK);
            fs.copySync(base + 'config.js', '../config.js.back');
            backedupConfig = true;
        }
        catch (e) {
            backedupConfig = false;
        }

        fs.emptyDirSync(base);
        fs.copySync('./temp', base);

        if (backedupConfig) {
            fs.copySync('../config.js.back', base + 'config.js');
            fs.remove('../config.js.back');
        }

        fs.removeSync('./build.zip');
        fs.removeSync('./temp');

        res.send('success');
    });
});
module.exports.validateSignature = (rawBody, signature, secretKey) => {
	if (!(signature || secretKey)) { return true; }
	if (!(signature && secretKey)) { return false; }

	var algorithmAndHash = signature.split('=');
	if (algorithmAndHash.length !== 2) { return false; }

	try {
		// Replace bufferEq() once https://github.com/nodejs/node/issues/3043 is
		// resolved and the standard library implementation is available.
		var hmac = crypto.createHmac(algorithmAndHash[0], secretKey);
		var computed = new Buffer(hmac.update(rawBody, 'utf8').digest('hex'));
		var header = new Buffer(algorithmAndHash[1]);
		return bufferEq(computed, header);
	} catch (err) {
		console.log(err);
		return false;
	}
};
Example #5
0
 client.on('authentication', function (ctx) {
   if (ctx.method === 'password' && ctx.username === 'foo' && ctx.password === 'bar') {
     ctx.accept()
   } else if (ctx.method === 'publickey' && ctx.key.algo === pubKey.fulltype && buffersEqual(ctx.key.data, pubKey.public)) {
     if (ctx.signature) {
       let verifier = crypto.createVerify(ctx.sigAlgo)
       verifier.update(ctx.blob)
       if (verifier.verify(pubKey.publicOrig, ctx.signature, 'binary')) {
         ctx.accept()
       } else {
         ctx.reject()
       }
     } else {
       // If no signature present, that means the client is just checking
       // the validity of the given public key
       ctx.accept()
     }
   } else {
     ctx.reject()
   }
 }).on('ready', function () {}).on('end', function () {
    schema.methods.authenticateSync = function() {
        if (!this._ac) {
            if (options.requireAuthenticationCode) {
                throw new Error('Authentication code missing');
            } else {
                return null;
            }
        }
        var acBuf = this._ac.hasOwnProperty('buffer') ? this._ac.buffer : this._ac;
        if (acBuf.length < VERSION_LENGTH + AAC_LENGTH + 2) {
            throw new Error('_ac is too short and has likely been cut off or modified');
        }
        var versionUsed = acBuf.slice(0, VERSION_LENGTH).toString();
        var basicAC = acBuf.slice(VERSION_LENGTH, VERSION_LENGTH + AAC_LENGTH);
        var authenticatedFieldsUsed = JSON.parse(acBuf.slice(VERSION_LENGTH + AAC_LENGTH, acBuf.length).toString());

        var expectedHMAC = computeAC(this, authenticatedFieldsUsed, versionUsed, arguments[0]); // pass in modelName as argument in init hook

        var authentic = bufferEqual(basicAC, expectedHMAC);
        if (!authentic){
            throw new Error('Authentication failed');
        }
    };
Example #7
0
    /**
     * Authenticate a client with public key
     */
    function clientAuthenticate( ctx ) {

        /** Reject if we are not what we are looking for */
        if ( ctx.method !== "publickey" ||
             ctx.key.algo !== pubKey.fulltype ||
             !buffersEqual( ctx.key.data, pubKey.public )
        ) { return ctx.reject(); }

        /** Accept if we don't have signature */
        if ( !ctx.signature ) { return ctx.accept(); }

        /** Authenticate */
        const verifier = crypto.createVerify( ctx.sigAlgo );

        verifier.update( ctx.blob );

        if ( verifier.verify( pubKey.publicOrig, ctx.signature, 'binary' ) ) {
            ctx.accept();
        } else {
            ctx.reject();
        }

    }
Example #8
0
  /**
   * Checks whether a request's flowId and flowBeginTime are valid.
   * Returns a boolean, `true` if the request is valid, `false` if
   * it's invalid.
   *
   * @name validateMetricsContext
   * @this request
   */
  function validate() {
    const metadata = this.payload.metricsContext

    if (! metadata) {
      return logInvalidContext(this, 'missing context')
    }
    if (! metadata.flowId) {
      return logInvalidContext(this, 'missing flowId')
    }
    if (! metadata.flowBeginTime) {
      return logInvalidContext(this, 'missing flowBeginTime')
    }

    const age = Date.now() - metadata.flowBeginTime
    if (age > config.metrics.flow_id_expiry || age <= 0) {
      return logInvalidContext(this, 'expired flowBeginTime')
    }

    // The first half of the id is random bytes, the second half is a HMAC of
    // additional contextual information about the request.  It's a simple way
    // to check that the metrics came from the right place, without having to
    // share state between content-server and auth-server.
    const flowSignature = metadata.flowId.substr(FLOW_ID_LENGTH / 2, FLOW_ID_LENGTH)
    const flowSignatureBytes = Buffer.from(flowSignature, 'hex')
    const expectedSignatureBytes = calculateFlowSignatureBytes(this, metadata)
    if (! bufferEqualConstantTime(flowSignatureBytes, expectedSignatureBytes)) {
      return logInvalidContext(this, 'invalid signature')
    }

    log.info({
      op: 'metrics.context.validate',
      valid: true,
      agent: this.headers['user-agent']
    })
    log.increment('metrics.context.valid')
    return true
  }
app.post('/', function(req, res) {

    //convert JSON request body to string
    var body = JSON.stringify(req.body);
    //get hash of secret and payload body
    var signature = getSecretHash(body);

    //put hash and github signature into buffers to use
    var a = new Buffer(signature);
    var b = new Buffer(req.headers['x-hub-signature']);
    //secure compare
    if(!bufferEq(a,b)){
        //if the hashes arnt equal send a 500 error
        res.status(500).send('Secret could not be verified!');
        return;
    }   

    console.log(req.body);
    //if master was committed to
    if(req.body.repository.name == 'portfolio'){
        //run update website script
        exec('./pullWebsite.sh', print);
        res.status(200).send('master was committed to and updated');
    } else if(req.body.repository.name == 'Notes-Learning'){
        exec('./pullNotes.sh', print);
        res.status(200).send('master committed and updated');
    } else if(req.body.repository.name == 'Facebook-Chat-Streak-Calculator-WebApp'){
        exec('./pullFBStreakCalc.sh', print);
        res.status(200).send('master commited and updated');
    } else if(req.body.repository.name == 'Tinder-Bot'){
        exec('./pullTinderBot.sh', print);
        res.status(200).send('master commited and updated');
    }
    res.status(696).send('request not acted on');
    return;
});
 function verify (signature, data) {
   return bufferEq(Buffer.from(signature), Buffer.from(sign(data)))
 }
Example #11
0
 return function verify(thing, signature, secret) {
   var computedSig = createHmacSigner(bits)(thing, secret);
   return bufferEqual(Buffer.from(signature), Buffer.from(computedSig));
 }
function verifySignature(secret, data, signature) {
	return bufferEq(new Buffer(signature), new Buffer(signData(secret, data)));
}