SuiteScript hmac sha256 - netsuite

I'm actually working on a new project based on netsuite product.
I'm trying to encrypt a message using hmac sha256.
What's is the simple way to do it considering that I have the stringToEncrypt and a key.
I've read the documentation in Netsuite but I'm still stucked...
There is my function
function toHmacSHA256Base64(toCrypt, key) {
var inputString = toCrypt;
var myGuid = key;
var sKey = crypto.createSecretKey({
guid: myGuid,
encoding: encode.Encoding.UTF_8
});
var hmacSHA256 = crypto.createHmac({
algorithm: 'SHA256',
key: sKey
});
hmacSHA256.update({
input: inputString,
inputEncoding: encode.Encoding.BASE_64
});
var digestSHA256 = hmacSHA256.digest({
outputEncoding: encode.Encoding.HEX
});
return digestSHA256;
};
of course behind the word crypto I use the module 'N/crypto' and encode 'N/encode'.
Thx a lot.

That's roughly correct and looks exactly like the sample from the NS help. If you have a string then you probably want inputEncoding:encode.Encoding.UTF_8 for the update call.
What's missing is how to generate the guid of the secret key.
For that you use a suitelet. Note the addSecretKeyField not the addCredentialField of the NS help:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(['N/ui/serverWidget', './config.js'],
function(serverWidget, config) {
function onRequest(context) {
if (context.request.method === 'GET') {
var form = serverWidget.createForm({
title: 'SFTP Password'
});
form.addSecretKeyField({
id : 'username',
label : 'Pwd',
restrictToScriptIds : config.targetScript,
restrictToCurrentUser : false
});
form.addSubmitButton({
label: 'Submit Button'
});
context.response.writePage(form);
} else {
var textField = context.request.parameters.username;
context.response.write('You have entered: ' + textField);
}
}
return {
onRequest: onRequest
};
});
FWIW encrypt is the wrong term here. You are creating a hash of the data which will be used for ensuring data integrity. You cannot decrypt a hash.
Once a GUID for a key has been generated I just store it in a config file (same one as is used for the script list above.
in TypeScript it looks like:
/**
* config.js
* #NApiVersion 2.x
*/
export var config = {
'host': '162.242.144.xxx',
'userName': 'unsername',
'targetScript': ['customscript_transmit_dsv_943', 'customscript_transmit_dsv_940', 'customscript_retrieve_dsv_944'],
'hostKey': 'AAAAB3Nza...Wz'
};
Then everything except the config.xs files can be stored in version control. Audience needs to be set appropriately on the files used in the script.

Related

Google Cloud KMS: The checksum in field ciphertext_crc32c did not match the data in field ciphertext

I am having issues setting up a system to encrypt and decrypt data in my Node.js backend. I am following this guide in the process.
I wrote a helper class KMSEncryption to abstract the logic from the example. Here's the code where I call it:
const kms = new KMSEncryption();
const textToEncrypt = 'hello world!';
const base64string = await kms.encrypt(textToEncrypt);
const decrypted = await kms.decrypt(base64string);
The issue I am having is that the decryption fails with the following error:
UnhandledPromiseRejectionWarning: Error: 3 INVALID_ARGUMENT: The checksum in field ciphertext_crc32c did not match the data in field ciphertext.
I tried to compare side by side with guide from Google docs but I cannot see where I went wrong.
Some of the things I have tried include:
Converting the base64string into a Buffer
Trying to calculate checksum on a Buffer of base64string and not the string itself
Any help is appreciated. Thank you
I believe you are base64 encoding the ciphertext when you do:
if (typeof ciphertext !== 'string') {
return this.toBase64(ciphertext);
}
but you are not reversing the encoding before calculating the crc32c.
I pulled this example together from sample code, it works correctly for me from Cloud Shell. (Sorry it's messy):
// On Cloud Shell, install ts first with:
// npm install -g typescript
// npm i #types/node
// npm i #google-cloud/kms
// npm i fast-crc32c
// Then to compile and run:
// tsc testcrc.ts && node testcrc.js
// Code adapted from https://cloud.google.com/kms/docs/encrypt-decrypt#kms-decrypt-symmetric-nodejs
const projectId = 'kms-test-1367';
const locationId = 'global';
const keyRingId = 'so-67778448';
const keyId = 'example';
const plaintextBuffer = Buffer.from('squeamish ossifrage');
// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('#google-cloud/kms');
const crc32c = require('fast-crc32c');
// Instantiates a client
const client = new KeyManagementServiceClient();
// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);
// Optional, but recommended: compute plaintext's CRC32C.
async function encryptSymmetric() {
const plaintextCrc32c = crc32c.calculate(plaintextBuffer);
console.log(`Plaintext crc32c: ${plaintextCrc32c}`);
const [encryptResponse] = await client.encrypt({
name: keyName,
plaintext: plaintextBuffer,
plaintextCrc32c: {
value: plaintextCrc32c,
},
});
const ciphertext = encryptResponse.ciphertext;
// Optional, but recommended: perform integrity verification on encryptResponse.
// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
// https://cloud.google.com/kms/docs/data-integrity-guidelines
if (!encryptResponse.verifiedPlaintextCrc32c) {
throw new Error('Encrypt: request corrupted in-transit');
}
if (
crc32c.calculate(ciphertext) !==
Number(encryptResponse.ciphertextCrc32c.value)
) {
throw new Error('Encrypt: response corrupted in-transit');
}
console.log(`Ciphertext: ${ciphertext.toString('base64')}`);
console.log(`Ciphertext crc32c: ${encryptResponse.ciphertextCrc32c.value}`)
return ciphertext;
}
async function decryptSymmetric(ciphertext) {
const cipherTextBuf = Buffer.from(await ciphertext);
const ciphertextCrc32c = crc32c.calculate(cipherTextBuf);
console.log(`Ciphertext crc32c: ${ciphertextCrc32c}`);
const [decryptResponse] = await client.decrypt({
name: keyName,
ciphertext: cipherTextBuf,
ciphertextCrc32c: {
value: ciphertextCrc32c,
},
});
// Optional, but recommended: perform integrity verification on decryptResponse.
// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:
// https://cloud.google.com/kms/docs/data-integrity-guidelines
if (
crc32c.calculate(decryptResponse.plaintext) !==
Number(decryptResponse.plaintextCrc32c.value)
) {
throw new Error('Decrypt: response corrupted in-transit');
}
const plaintext = decryptResponse.plaintext.toString();
console.log(`Plaintext: ${plaintext}`);
console.log(`Plaintext crc32c: ${decryptResponse.plaintextCrc32c.value}`)
return plaintext;
}
decryptSymmetric(encryptSymmetric());
You can see that it logs the crc32c several times. The correct crc32c for the example string, "squeamish ossifrage", is 870328919. The crc32c for the ciphertext will vary on every run.
To run this code yourself, you just need to point it at your project, region, key ring, and key (which should be a symmetric encryption key); hopefully comparing this code with your code's results will help you find the issue.
Thanks for using Google Cloud and Cloud KMS!

How to configure the user_token of Damn Vulnerable Web Application within CSRF field while Script based authentication using ZAP?

I had been following the documentation of Script Based Authentication for Damn Vulnerable Web Application using ZAP. I have navigated to http://localhost/dvwa/login.php through Manual Explore which opens up the DVWA application on my localhost as follows:
and adds the URL to the Default Context.
I've also created the dvwa script with the following configuration:
and modified the dvwa script:
Now when I try Configure Context Authentication, dvwa script does gets loaded but the CSRF field doesn't shows up.
Additionally, POST Data doesn't even shows up but Extra POST Data is shown.
Am I missing something in the steps? Can someone help me out?
The modified script within the documentation of Script Based Authentication section for Damn Vulnerable Web Application using ZAP
seems incomplete.
The complete script is available at Setting up ZAP to Test Damn Vulnerable Web App (DVWA) which is as follows:
function authenticate(helper, paramsValues, credentials) {
var loginUrl = paramsValues.get("Login URL");
var csrfTokenName = paramsValues.get("CSRF Field");
var csrfTokenValue = extractInputFieldValue(getPageContent(helper, loginUrl), csrfTokenName);
var postData = paramsValues.get("POST Data");
postData = postData.replace('{%username%}', encodeURIComponent(credentials.getParam("Username")));
postData = postData.replace('{%password%}', encodeURIComponent(credentials.getParam("Password")));
postData = postData.replace('{%' + csrfTokenName + '%}', encodeURIComponent(csrfTokenValue));
var msg = sendAndReceive(helper, loginUrl, postData);
return msg;
}
function getRequiredParamsNames() {
return [ "Login URL", "CSRF Field", "POST Data" ];
}
function getOptionalParamsNames() {
return [];
}
function getCredentialsParamsNames() {
return [ "Username", "Password" ];
}
function getPageContent(helper, url) {
var msg = sendAndReceive(helper, url);
return msg.getResponseBody().toString();
}
function sendAndReceive(helper, url, postData) {
var msg = helper.prepareMessage();
var method = "GET";
if (postData) {
method = "POST";
msg.setRequestBody(postData);
}
var requestUri = new org.apache.commons.httpclient.URI(url, true);
var requestHeader = new org.parosproxy.paros.network.HttpRequestHeader(method, requestUri, "HTTP/1.0");
msg.setRequestHeader(requestHeader);
helper.sendAndReceive(msg);
return msg;
}
function extractInputFieldValue(page, fieldName) {
// Rhino:
var src = new net.htmlparser.jericho.Source(page);
// Nashorn:
// var Source = Java.type("net.htmlparser.jericho.Source");
// var src = new Source(page);
var it = src.getAllElements('input').iterator();
while (it.hasNext()) {
var element = it.next();
if (element.getAttributeValue('name') == fieldName) {
return element.getAttributeValue('value');
}
}
return '';
}
Using this script, CSRF Field and POST Data field shows up just perfect.

How to verify an ES256 JWT token using Web Crypto when public key is distributed in PEM?

I need to verify ES256 JWT tokens in a Cloudflare Worker. To my understanding they do not run Node.js there and I will have to make everything work with the Web Crypto API (available in browsers, too, as window.crypto.subtle). However, I am expecting to receive the public keys as PEM files and I think I am having problems importing them.
I have been trying to modify an existing open source JWT implementation that only supports HS256 to support ES256.
In addition to trying to use the actual tokens and keys, and keys generated in browsers and OpenSSL, I have tried to use a working example from the JWT.io website (after converting it to JWK format using node-jose), since it should validate correctly. But I am not getting any errors, my code running in browser just tells me the token is not valid.
Here is my Node REPL session I used for converting the key from JWT.io to JWK:
> const jose = require('node-jose')
> const publicKey = `-----BEGIN PUBLIC KEY-----
... MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEEVs/o5+uQbTjL3chynL4wXgUg2R9
... q9UU8I5mEovUf86QZ7kOBIjJwqnzD1omageEHWwHdBO6B+dFabmdT9POxg==
... -----END PUBLIC KEY-----`
> const keyStore = jose.JWK.createKeyStore()
> keyStore.add(publicKey, 'pem')
> keyStore.toJSON()
{
keys: [
{
kty: 'EC',
kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
crv: 'P-256',
x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
}
]
}
>
Here is the failing validation, based on code from webcrypto-jwt package:
function utf8ToUint8Array(str) {
// Adapted from https://chromium.googlesource.com/chromium/blink/+/master/LayoutTests/crypto/subtle/hmac/sign-verify.html
var Base64URL = {
stringify: function (a) {
var base64string = btoa(String.fromCharCode.apply(0, a));
return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
},
parse: function (s) {
s = s.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
return new Uint8Array(Array.prototype.map.call(atob(s), function (c) { return c.charCodeAt(0); }));
}
};
str = btoa(unescape(encodeURIComponent(str)));
return Base64URL.parse(str);
}
var cryptoSubtle = (crypto && crypto.subtle) ||
(crypto && crypto.webkitSubtle) ||
(window.msCrypto && window.msCrypto.Subtle);
// Token from JWT.io
var tokenParts = [
'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9',
'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0',
'tyh-VfuzIxCyGYDlkBA7DfyjrqmSHu6pQ2hoZuFqUSLPNY2N0mpHb3nk5K17HWP_3cYHBw7AhHale5wky6-sVA'
];
// Public key from JWT.io converted in Node using node-jose
var publicKey = {
kty: 'EC',
kid: '19J8y7Zprt2-QKLjF2I5pVk0OELX6cY2AfaAv1LC_w8',
crv: 'P-256',
x: 'EVs_o5-uQbTjL3chynL4wXgUg2R9q9UU8I5mEovUf84',
y: 'kGe5DgSIycKp8w9aJmoHhB1sB3QTugfnRWm5nU_TzsY'
};
var importAlgorithm = {
name: 'ECDSA',
namedCurve: 'P-256',
hash: 'SHA-256',
};
cryptoSubtle.importKey(
"jwk",
publicKey,
importAlgorithm,
false,
["verify"]
).then(function (key) {
var partialToken = tokenParts.slice(0,2).join('.');
var signaturePart = tokenParts[2];
cryptoSubtle.verify(
importAlgorithm,
key,
utf8ToUint8Array(signaturePart),
utf8ToUint8Array(partialToken)
).then(function (ok) {
if (ok) {
console.log("I think it's valid");
} else {
console.log("I think it isn't valid");
}
}).catch(function (err) {
console.log("error verifying", err);
});
}).catch(function(err) {
console.log("error importing", err);
});
Since I copied a valid key and a valid token from JWT.io, I am expecting the code to log "I think it's valid" without errors. It does not show any errors, indeed, but it ends up in "I think it isn't valid" branch.
Answered here How to verify a signed JWT with SubtleCrypto of the Web Crypto API?
So, if I understood correctly, the problem was that base64 encoding included in the open source upstream just does not work correctly in one of the directions, since it uses the browser's btoa. Adapting https://github.com/swansontec/rfc4648.js instead works.

generate random unique token for user id

I want to generate token as user id and store in database , but how to generate unique one?
should I add timestamp var currentUnixTimestamp = (new Date().getTime() / 1000); as salt? how to do with crypto?
var generateToken = function() {
return new Promise(function (fulfill, reject){
crypto.randomBytes(8, function(error, buf) {
if (error) {
reject(error);
} else {
var token = buf.toString('hex');
fulfill(token);
}
});
});
};
Eight random bytes from a properly seeded crypto library has a low chance of a collision, so you don't usually need to concern yourself with duplicates. In fact, increase that to 16 bytes, and your code is on par with UUID version 4. This is considered a standard for UUIDs. The chances of a collision are so remote it is not usually worth considering.
If you are going that far though, consider using a standard format UUID, such as the node package "uuid". There are also database-side uuid functions which you can add as default to schemas e.g. in Postgres. The advantage is a standardised and well-understood format for your ids, and you won't need to spend any time justifying or maintaining your code for this, just point developers to the standard docs.
If you want this token for authentication purposes you should use json web token instead. It will manage for you and its quite efficient.
Only have to include as a middleware .
app.use(expressJWT({
secret: new Buffer("Your-secret-key").toString('base64')
}).unless({
//# pass api without validating
path: unlessRoutes
}));
You could specify which routes you don't want to to skip in jwt middleware by giving an array in unlessRoutes.
var unlessRoutes = [
'/',
/\/login/,
/\/register/,
/\/customers/,
/\/customer$/,
/\/addCustomer/,
/\/just/,
/\/search/,
/\/dynamic/,
/\/favicon.ico/
]
This is what i think we can do for generating the random token using the crypto:
var passwordResetToken = createRandomToken(data.body.email);
exports.createRandomToken = function (string) {
var seed = crypto.randomBytes(20);
return crypto.createHash('abcde').update(seed + string).digest('hex');
};

Redis: How to save (and read) Key-Value pairs at once by namespace/rule?

I want to utilize Redis for saving and reading a dynamic list of users.
Essentially, Redis is Key-Value pair storage. How can I read all the saved users at once? (for example, creating a namespace "users/user_id")
And since I am a Redis beginner,
Do you think the use of Redis in the above case is proper/efficient?
Thanks.
When using key/values for storing objects you should create a domain specific key by combining the domain name plus the unique id. For example, a user object that might look like this:
// typical user data model
var User = function(params) {
if (!params) params = {};
this.id = params.id;
this.username = params.username;
this.email = params.email;
// other stuff...
};
Then domain key could be created like this:
var createUserDomainKey = function(id) {
return 'User:' + id;
};
If the id was 'e9f6671440e111e49f14-77817cb77f36' the key would be this:
User:e9f6671440e111e49f14-77817cb77f36
Since redis will store string values, you need to serialize, probably with json so to save the user object. Assuming a valid use object would would do something like this:
var client = redis.createClient(),
key = createUserDomainKey( user.id ),
json = JSON.stringify( user ) ;
client.set( key, json, function(err, result) {
if (err) throw err; // do something here...
// result is 'OK'
});
For simple fire-hose queries returning all users, you can do this:
var client = redis.createClient();
client.keys( createUserDomainKey( '*' ), function(err, keys) {
if (err) throw err; // do something here
// keys contains all the keys matching 'User:*'
});
Note that the redis folks discourage the use of 'keys' for production, so a better approach is to build your own index using sorted-set, but if your user list is limited to a few hundred, there is no problem.
And since it returns a list of keys, you need to loop through and get each user then parse the json string to recover the real object. Assuming a populated list of keys, you could do something like this:
var client = redis.getClient(),
users = [];
var loopCallback = function(err, value) {
if (!err && value) {
// parse and add the user model to the list
users.push( JSON.parse( value ) );
}
// pull the next key, if available
var key = keys.pop();
if (key) {
client.get( key, loopCallback );
} else {
// list is complete so return users, probably through a callback;
}
}
// start the loop
loopCallback();
This is a good general purpose solution, but there are others that use sorted sets that are move efficient when you want access to the entire list with each access. This solution gives you the ability to get a single user object when you know the ID.
I hope this helps.
ps: a full implementation with unit tests of this can be found in the AbstractBaseDao module of this project.

Resources