How to get the decrypt data from other user using GunDB - gun

I gave a try to .secret() and .trust() of gun.user though, there are unexpected results. How could I get the data from other users in order to access control in the application?
as well as I need to know how to decrypt data without the error message, 'Could not decrypt'.
node 10.16.0
gun 0.2019.515
chrome 74.0.3729.169
There are User03 and User01 in left and right.
My goal of this test is User01 to get User03's secret data.
1. Put data under the User03 and check the data on both consoles.
S.user.get('test').put('come on'); // on left console as user03
S.user.get('test').once(console.log); // on left console as user03
user03.get('test').once(console.log); // on right console as user01
2. Let User03 .trust() User01 on left side.
S.user.get('test').trust( user01 ); // left
3. Make User03's data secret using User03's pair.
S.user.get('test').secret( S.user.pair ); //left
4. Check the encrypt data on both sides.
S.user.get('test').once(console.log); // on left console as user03
user03.get('test').once(console.log); // on right console as user01
5. Decrypt user03's secret using user01's pair on the right.
it gets the error message, 'Could not decrypt'.
user03.get('test').once((data)=>{
SEA.decrypt(data, S.user.pair, console.log);
});; // right
6. Check the inside the return object of STEP 5.
I expect the output 'come on' as decrypted data.

#huhsame , sorry for the delay on answering this. (For urgent matters, please tag me on Twitter or in the Gitter)
The main issue is that User.trust and User.secret are currently (August 2019) unstable alpha API methods.
We however have a stable production-ready lower-level API you can use instead, called SEA.
Here is a complete example of how to do what you want:
var alice = await SEA.pair();
var bob = await SEA.pair();
var enc = await SEA.encrypt('shared data', await SEA.secret(bob.epub, alice));
await SEA.decrypt(enc, await SEA.secret(alice.epub, bob));
This is what GUN and the User API methods use underneath.
You see that alice and bob are the same keypairs (pub & priv of ECDSA & ECDH) behind the gun.user(ecdsaPubKey) lookups you've probably already done.
await SEA.secret(ecdhPubKey, alice) gets a common shared secret between your target user's public key (their ECDH pubkey, not ECDSA) and "yourself" (Alice). How this is done is famously described with mixing colors.
Then .encrypt( and .decrypt( do what you'd expect, as long as the have the same "passcode" (the 2nd parameter), which is gotten by deriving the common secret of two users, which gives the same output even in the reverse direction (Bob, the target user, passing his keypair as "you", and Alice's ECDH pubkey as 1st parameter into secret).
Hopefully this will buy you time, doing it yourself, until the User.trust and User.secret (in contrast to SEA.secret which works already) higher-level convenience methods are ready.

Related

How to create "Round Robin Call Forwarding Function" in Twilio Stack

I have researched high and low through multiple websites and have not found a single fully documented solution for round-robin call forwarding with-in the Twilio stack; let alone within Twilio Studio. The last time this question was asked in detail was in 2013 so your help is greatly appreciated. I am looking to find a solution to the following to educate myself and others:
[Round Robin Scenario]
Mentioned by Phil Krnjeu on Aug 1 '13 at 23:04, "I'm trying to create a website that has a phone number on it (say, a phone number for a school). When you call that number, it has different secretary offices (A,B,C, D). I want to create something where the main number is called, and then it goes and calls phone number A the first time, the second time someone calls the main number, number B is called, C, then D. Once D is called (which would be the 4th call), the 5th call goes back to A."
The response to the above question was to use an IVR Screening & Recording application which requires the caller to pick an agent which is not a true Round Robin solution. The solution I am looking for and many others require the system to know which agent is in a group and which agent is next to receive a call.
[Key Features Needed]
Ability to add forwarding numbers as identified above A, B, C, D as a group or IVR extensions such as 1 = Management, 2 = Sales and etc...
Set a subsequent calling rule that notates in a DB of some sort. Caller A through D, for example, equals 1 unsuccessful. When caller A has been forwarded a call it now equals 0 successful then the script stops and allows the call to be answered by the user or its voicemail. Then the next call comes in and is forwarded to user B and assigned a 0 successful value, then the script stops.
After the caller finishes the call or finishes leaving a voicemail the script needs to end the call.
[Final Destination]
The round-robin should finalize its call with the forwarded phone numbers voicemail.
[Known Issues]
Forwarding a call to multiple numbers not stopping when someone answers
[Options]
Once this question is posted I am sure someone will ask in the near future what if I wanted the call to be forwarded to a Twilio voicemail instead of using the forwarded phone number's voicemail which could be let's say a cell phone. I do not necessarily need this feature, however, making an additional comment would be very helpful to the community. Thank you for your time.
I have limited knowledge of programming besides having the ability to review articles posted by other users. One article I researched in detail that did not work for me was, "IVR: Screening & Recording with PHP and Laravel."
The solution I am looking for first would be to make this code through the new Twilio Studio interface if that is not possible then any other solution would be helpful to all.
Sam here from the Twilio Support Team. You can build what you've described using Twilio's Runtime suite, Studio, and Functions.
I wrote a blog post with detailed instructions and screenshots here, and I've included a summarized version below as well.
CREATE YOUR VARIABLE
First, you need to create a serverless Variable which will be used as the round robin counter. The variable must be inside an Environment, which is inside a Service. This is the only part of the application where you will need your own laptop. You can see how to create these with any of the SDKs or using curl in the docs.
Create a Service
Create an Environment
Create a Variable
Be sure to copy the SIDs of your Service, Environment, and Variable since you will need that for your function.
For convenience, this is how you create the Variable in NodeJS.
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.serverless.services('ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.environments('ZEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.variables
.create({key: 'key', value: 'value'})
.then(variable => console.log(variable.sid));
CREATE YOUR FUNCTION
Create the following Environment Variables here in the console and save set them equal to their respective SID that you saved earlier.
RR_SERVICE_SID
RR_ENV_SID
RR_VAR_SID_CTR
Next, make sure you check the Enable ACCOUNT_SID and AUTH_TOKEN checkbox above the Environment Variables section under Credentials.
Be sure your Twilio Client version in the Dependencies section is set to the latest, so we can be sure it includes the Serverless resources. At the time of writing (March 2020), the default Client version does not include them, so we upgraded to 3.41.1, which was the latest.
Go here in the console and create a blank Function.
Copy and paste the following code and replace the numbers with the ones you would like to include in your Round Robin (make sure the environment variables you just created match what's in the code).
exports.handler = function(context, event, callback) {
// Number List
let numbers = [
"+18652142345", //Sam
"+18651092837", //Tina
"+19193271892", //Matt
// Copy and paste line above to add another number.
];
// Initialize Twilio Client
let client = context.getTwilioClient();
// Fetch Round Robin Ctr
client.serverless.services(context.RR_SERVICE_SID)
.environments(context.RR_ENV_SID)
.variables(context.RR_VAR_SID_CTR)
.fetch()
.then(variable => {
// Use counter value to determine number to call
let number = numbers[variable.value];
// Create var with new ctr value
let ctr = variable.value;
// Check if current counter value is less than RR length (i.e. the number of numbers in round robin)
// If so, increment
if(ctr == numbers.length-1) {
ctr = 0;
}
// Otherwise reset ctr
else ctr++;
// Update counter value
client.serverless.services(context.RR_SERVICE_SID)
.environments(context.RR_ENV_SID)
.variables(context.RR_VAR_SID_CTR)
.update({value: ctr})
.then(resp => {
// Return number to call
let response = {number};
// Return our counter value and a null error value
callback(null, response);
});
});
};
CREATE YOUR STUDIO FLOW
Click the red plus sign to create a new Flow here.
Give the Flow a name and click Next.
Scroll to the bottom of the templates and click 'Import from JSON' and click Next.
Paste the Flow JSON shown here and click Next.
Click the RoundRobin function widget and select the Function you just created under the Default service.
Click the FunctionError widget, click MESSAGING & CHAT CONFIG, and change the SEND MESSAGE TO number to a number that you would like to notify by text in the event of a Function failure.
Click the DefaultNumber widget and change the default number that will be forwarded to in the event of a Function failure.
Click the Publish button at the top of your Flow.
CONFIGURE YOUR TWILIO NUMBER
Go here in the console.
Click the Twilio number you would like to configure.
Scroll down to the A CALL COMES IN dropdown in the Voice section and select Studio Flow.
Select your new Flow in the Select a Flow dropdown to the right.
Click Save at the bottom.
And that's it. You're now all set to test!

how to encrypt the chat message with multiple people public key together and restore the message?

I have a application with two users and one middle man, all of them holding the private and public key, To make the secured chat, two users and one middle man are all sending the public key and generate a secured channel. After establishing the channel, the middle man doesn't have the ability to see the encrypted message unless one of the user is sending his own key to the middle man.
i am not very familiar with cryptography, so for this app i know how to encrypt and decrypt the message.
encrypt(data) {
try {
var cipher = Crypto.createCipher('aes-256-cbc', this.password);
var encrypted = Buffer.concat([cipher.update(new Buffer(JSON.stringify(data), "utf8")), cipher.final()]);
FileSystem.writeFileSync(this.filePath, encrypted);
return { message: "Encrypted!" };
} catch (exception) {
throw new Error(exception.message);
}
}
but I don't know how to establish the encrypted channel from the stakeholders' key, and how can the one middle to see the message using his key and one of users' key?
is there a way to accomplish this using the cryptography?
I'm not sure I completely understand, but I think if you want to go with a system that doesn't use public key crypto I would suggest a system using 2 stages of encryption, actually a lot like PGP only both stages use symmetric keys-
1) There is a fixed session key generated by the first person in the chat, this can be a randomly generated number.
2) This session key is then encrypted by the keys belonging to every new member of the chat group and individually sent to them.
3) The new members decrypt with their own unique keys to get the plaintext session key back.
4) This session key is subsequently used to decrypt the messages sent to all participants. The same key can also be used to encrypt and send any new messages from any entitled participant(i.e. has the valid session key) on the chat group.
This is used in some systems but it relies on the unique keys being securely transmitted, in the first instance. If this condition can't be met, it's a problem that can be solved with public key crypto to build an end-to-end secure message system like PGP, whatsapp, etc.

Webapplication log in system

I am using revel to build my webapplication and trying to write authentication module.
I finished with sign up part and now heading to write sign in part.
I read about security part on The definitive guide to form-based website authentication and will use this recommendation.
What I am really do not know is, how sign in works. I am imaging that the process works like this:
User write username and password into the html form and press sign in
Server receive request and the controller will check, if user information match with data on database.
If yes, how continue.
The third point is where I am staying. But I have some idea how could works and not sure, if is the right way.
So when sign in information match with the database, I would set in session object(hash datatype) key value pair signed_in: true. Everytime when the user make a request to the webapplication, that need to be authenticated, I would look in the session object, if signed_in is true or not.
This is the way I would do, but as I mentioned above, I do not know if it is the right way.
Yes like #twotwotwo mentioned, give it the user id and also a role.
So server side rendered flow: Step 1
user sends username (or other identifier) and secret.
using scrypt or bcrypt the secret is checked against the stored salted hash in the database
if it matches you create a struct or a map
serialize struct or map into string (json, msgpack, gob)
encrypt the string with AES https://github.com/gomango/utility/blob/master/crypto.go (for instance). Set a global AES key.
create a unique cookie (or session) identifier (key)
store identifier and raw struct or map in database
send encrypted cookie out (id = encrypted_struct_or_map aka the encrypted string)
On a protected resource (or page): Step 2
read identifier from cookie
check if id exists in db
decode cookie value using AES key
compare values from cookie with stored values
if user.role == "allowed_to_access_this_resource" render page
otherwise http.ResponseWriter.WriteHeader(403) or redirect to login page
Now if you wanted you could also have an application-wide rsa key and before encrypting the cookie value sign the string with the rsa private key (in Step 1). In Step 2 decode with AES key, check if signature valid, then compare content to db stored content.
On any changes you have to update the cookie values (struct/map) and the info in the database.

Filepicker API key

I like to ask a newbie question. By setting API key in JavaScript, wouldn't anyone can read the source and use the key freely?
Edited >>
Extracted the jsFiddle codes,
filepicker.setKey('8PbzrhP9Tr2r6wPlSqzS');
/* Unsecured */
/*
filepicker.pick(function(fpfile){
console.log(fpfile);
});
filepicker.read(fpfile, function(contents){
console.log(contents);
})
*/
var fpfile = {'url': 'https://www.filepicker.io/api/file/KW9EJhYtS6y48Whm2S6D'};
var policy = 'eyJoYW5kbGUiOiJLVzlFSmhZdFM2eTQ4V2htMlM2RCIsImV4cGlyeSI6MTUwODE0MTUwNH0=';
var signature = '4098f262b9dba23e4766ce127353aaf4f37fde0fd726d164d944e031fd862c18';
filepicker.read(fpfile, {policy: policy, signature:signature}, function(contents){
console.log(contents);
})
filepicker.pick({policy: policy, signature:signature}, function(fpfile){
console.log(fpfile);
});
How does it prevents anyone from using the key ONLY, to upload or read/download files from my account?
Because browser-side javascript is always publically readable, your API key will be visible to others. To increase the protection of your API key beyond simple url/hostname checking, you can use the rich policy-based security API we provide: https://developers.filepicker.io/docs/security/
Java bytecode is easily reversable with trivial amount of work. If you need to have it, pull it from a website using TLS and store it in RAM or at the very least, xor it with a password

How should an application authenticate with a datastore?

I'm writing an iPad game that sends hi-score type data (ie data beyond what Game Center supports) to a Google appengine datastore. It sends these updates via http GET or POST requests, such as http://myapp.appspot.com/game/hiscore/925818
Here is how I thought to ensure the appengine datastore isn't spammed with false data.
zip/encrypt the payload data using hardcoded p#ssw0rd saved in the iOS binary. Encode that binary data as base64. Pass base64 payload in the url query string or in the POST data. At handler, unbase64, then unzip data with p#ssw0rd. Follow instructions in payload to update highscore-type data.
CON: If p#ssw0rd is somehow derived from the iOS binary, this scheme can be defeated.
Is this adequate/sufficient? Is there another way to do this?
There is absolutely no way to make sure it's your client that sends the data. All you can try is to obfuscate some thing to make it harder for spammers to submit data.
However I think there are two thing you can do:
Have some kind of secrect key saved in the binary
Have a custom algorithm calculating some checksum
Maybe you can go with a combination of both. Let me give you an example:
Create some custom (complex!) alorithm like (simplyfied):
var result = ((score XOR score / 5) XOR score * 8) BITSHIFT_BY 3
Then use your static stored key with that result and a well known hash function like:
var hash = SHA256(StaticKey + result)
Then send that hash with the score to the server. The server has to "validate" the hash by performing the exact same steps (evaluate algorithm + do the SHA256 stuff) and compare the hashes. If they match the score hopefully comes from your app otherwise throw it away, it comes from a spammer.
However this is only one thing you can do. Have a look at the link from mfanto, there are many other ideas that you can look at.
Be sure to not tell anybody about how you're doing it since this is security through obscurity.
Ok me, there are 2 methods to do this.
1) Purchase an SSL certificate for $FREE.99 and open HTTPS connections only to your server to submit hiscore type data. Connection speed should be around 500 ms due to handshake roundtrip time.
2) Embed an RSA public key certificate in your iOS app, and have the RSA private key on your server.
You can then do 1 of 2 things with this second scheme:
IF your data messages are really small (≤256 B) you can just encrypt and send 256B packages (RSA payload is limited by the number of bits in the key)
ELSE IF the data is too large (>256B), generate a random symmetric key (AES), and pack:
SYMMETRIC AES KEY ENCRYPTED WITH RSA PUBLIC KEY
BINARY DATA ENCODED WITH SYMMETRIC AES KEY
The server then takes the first 256 bytes and decodes it, then the server uses that AES key to decrypt the rest of the message.
The above 2 only prevent eavesdropping, but it means the data format of your messages is hidden. At some level, it is still a type of security by obscurity, since if the hacker has your public key AND your message format, they can manufacture messages.