GithubHelp home page GithubHelp logo

elsehow / signal-protocol Goto Github PK

View Code? Open in Web Editor NEW
188.0 7.0 31.0 2.5 MB

The Signal cryptographic protocol, for node and browsers

Home Page: http://people.ischool.berkeley.edu/~nick/signal-protocol-js/

License: GNU General Public License v3.0

JavaScript 94.75% C 3.70% C++ 0.21% HTML 0.01% Objective-C 1.33%

signal-protocol's Introduction

signal-protocol

Build Status Dependencies DevDependencies

Sauce Test Status

A ratcheting forward secrecy protocol that works in synchronous and asynchronous messaging environments.

THIS MODULE IS DEPRICATED

I recommend you use @wireapp/proteus.

All code in this repository is FOR RESEARCH PURPOSES ONLY!


This repository is forked from WhisperSystem's own libsignal-protocol-javascript by @liliakai, modified to support node and the browser. I use node-webcrypto-ossl as a drop-in native replacement for WebCrypto API.

WARNING: This code has NOT been reviewed by an experienced cryptographer. IT IS FOR RESEARCH ONLY!!!!!

You can read more about the signal protocol (formerly /axolotl/ for its self-healing abilities) here.

Install

npm install signal-protocol

Usage

There are two ways to use this package.

You can require with your front-end bundler of choice (e.g. browserify, webpack):

var signal = require('signal-protocol')

IMPT NOTE!!! If you intend to call this from the browser, have your bundler exclude src/node_polyfills.js. You won't need that file for your browser bundles, and it could crash your bundler. (Even at best, it will add tons of useless junk to your bundled js file).

Or, you can include the prebundled dist/libsignal.js in your HTML file.

The following steps will walk you through the lifecycle of the signal protocol

Generate an indentity + PreKeys

This protocol uses a concept called 'PreKeys'. A PreKey is an ECPublicKey and an associated unique ID which are stored together by a server. PreKeys can also be signed.

At install time, clients generate a single signed PreKey, as well as a large list of unsigned PreKeys, and transmit all of them to the server.

var signal = require('signal-protocol')
var KeyHelper = signal.KeyHelper;

var registrationId = KeyHelper.generateRegistrationId();
// Store registrationId somewhere durable and safe.

KeyHelper.generateIdentityKeyPair().then(function(identityKeyPair) {
    // keyPair -> { pubKey: ArrayBuffer, privKey: ArrayBuffer }
    // Store identityKeyPair somewhere durable and safe.
});

KeyHelper.generatePreKey(keyId).then(function(preKey) {
    store.storePreKey(preKey.keyId, preKey.keyPair);
});

KeyHelper.generateSignedPreKey(identityKeyPair, keyId).then(function(signedPreKey) {
    store.storeSignedPreKey(signedPreKey.keyId, signedPreKey.keyPair);
});

// Register preKeys and signedPreKey with the server

Build a session

Signal Protocol is session-oriented. Clients establish a "session," which is then used for all subsequent encrypt/decrypt operations. There is no need to ever tear down a session once one has been established.

Sessions are established in one of two ways:

  1. PreKeyBundles. A client that wishes to send a message to a recipient can establish a session by retrieving a PreKeyBundle for that recipient from the server.
  2. PreKeySignalMessages. A client can receive a PreKeySignalMessage from a recipient and use it to establish a session.

A note on state

An established session encapsulates a lot of state between two clients. That state is maintained in durable records which need to be kept for the life of the session.

State is kept in the following places:

  • Identity State. Clients will need to maintain the state of their own identity key pair, as well as identity keys received from other clients.
  • PreKey State. Clients will need to maintain the state of their generated PreKeys.
  • Signed PreKey States. Clients will need to maintain the state of their signed PreKeys.
  • Session State. Clients will need to maintain the state of the sessions they have established.

A signal client needs to implement a storage interface that will manage loading and storing of identity, prekeys, signed prekeys, and session state. See test/InMemorySignalProtocolStore.js for an example.

Building a session

Once your storage interface is implemented, building a session is fairly straightforward:

var store   = new MySignalProtocolStore();
var address = new signal.SignalProtocolAddress(recipientId, deviceId);

// Instantiate a SessionBuilder for a remote recipientId + deviceId tuple.
var sessionBuilder = new signal.SessionBuilder(store, address);

// Process a prekey fetched from the server. Returns a promise that resolves
// once a session is created and saved in the store, or rejects if the
// identityKey differs from a previously seen identity for this address.
var promise = sessionBuilder.processPreKey({
    registrationId: <Number>,
    identityKey: <ArrayBuffer>,
    signedPreKey: {
        keyId     : <Number>,
        publicKey : <ArrayBuffer>,
        signature : <ArrayBuffer>
    },
    preKey: {
        keyId     : <Number>,
        publicKey : <ArrayBuffer>
    }
});

promise.then(function onsuccess() {
  // encrypt messages
});

promise.catch(function onerror(error) {
  // handle identity key conflict
});

Encrypting

Once you have a session established with an address, you can encrypt messages using SessionCipher.

var plaintext = "Hello world";
var sessionCipher = new signal.SessionCipher(store, address);
sessionCipher.encrypt(plaintext).then(function(ciphertext) {
    // ciphertext -> { type: <Number>, body: <string> }
    handle(ciphertext.type, ciphertext.body);
});

Decrypting

Ciphertexts come in two flavors: WhisperMessage and PreKeyWhisperMessage.

var address = new signal.SignalProtocolAddress(recipientId, deviceId);
var sessionCipher = new signal.SessionCipher(store, address);

// Decrypt a PreKeyWhisperMessage by first establishing a new session.
// Returns a promise that resolves when the message is decrypted or
// rejects if the identityKey differs from a previously seen identity for this
// address.
sessionCipher.decryptPreKeyWhisperMessage(ciphertext).then(function(plaintext) {
    // handle plaintext ArrayBuffer
}).catch(function(error) {
    // handle identity key conflict
});

// Decrypt a normal message using an existing session
var sessionCipher = new signal.SessionCipher(store, address);
sessionCipher.decryptWhisperMessage(ciphertext).then(function(plaintext) {
    // handle plaintext ArrayBuffer
});

Cryptography Notice

A number of nations restrict the use or export of cryptography. If you are potentially subject to such restrictions you should seek competent professional legal advice before attempting to develop or distribute cryptographic code.

License

I (elsehow) release copyright to Copyright 2015-2016 Open Whisper Systems under the GPLv3: http://www.gnu.org/licenses/gpl-3.0.html

signal-protocol's People

Contributors

elsehow avatar liliakai avatar tcyrus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

signal-protocol's Issues

Remove console.log in src/

There are a few places where we console.log informative messages, resulting in a console with messages like:

New remote ephemeral key
Duplicate PreKeyMessage for session
Duplicate PreKeyMessage for session

I think each of these messages should get emitted over some emitter returned by the highest-level entity that makes sense (sessionCiphers come to mind).

generateIdentityKeyPair() returning special characters key pair

Hello,

I am using signal-protocol in my express project. The issue that I am facing is that the generateIdentityKeyPair() method returns identity key pair (pubKey, privKey) in form of an array buffer which is fine.
But i need to store them somewhere on client end and I want to convert them to string format (base64)
but when i try to do so, i get non-readable ascii characters like this : ♣X�WQ�]�J�dF�♦�l-w>̪���g>���U�!
I have tried ab2str and a few similar methods to convert them into proper keys but still no luck.
Any guidance would be highly appreciated. Thanks

module Long does not match the corresponding path on disk `long`

pre i'm working on dva2.x.
as follow the guide , npm install signal-protocol

i got a error:
./node_modules/signal-protocol/build/dcodeIO.js
Module not found: /Users/eatwood/Desktop/workspace/web_version/node_modules/Long/dist/long.js does not match the corresponding path on disk long.

and I found the module Long exist

Making it less annoying to bundle signal in the browser

If I npm install signal-protcol for my app, and require it in my browser bundle, I get

Users/ffff/empty-browser-module/node_modules/node-webcrypto-ossl/build/Release/nodessl.node:1
����
   ����__TEXT __text__TEXT�
                           �g�
                              �__stubs__TEXT�s>��__stub_helper__TEXT�w��w�__const__TEXT�~/�~__gcc_except_tab__TEXT��I�__cstring__TEXT����__unwind_info__TEXT���	��__eh_frame__TEXTH��EH�(__DATA    __got__DATA  �__nl_symbol_ptr__DATA!!�__la_symbol_ptr__DATA !� !�__mod_init_func__DATA��&	__const__DATA�&�&__data__DATA@/`@/H__LINKEDIT@�@��"�0@xx@ �B��EH��&��
^
ParseError: Unexpected character '�'

As it says in the README, I would now need to configure my bundler to exclude/ignore ./node_modules/signal-protocol/src/node_polyfills.js.

This is really not the friendliest solution. How can we work around this? How have other modules worked around this issue?

Simple WebCrypto exploit in an untrusted `window` environment

Using window.crypto is not safe unless we have assurances about the browser environment. The following exploit could be exploited by a plugin, or script, that has access to the browser window in which libsignal is running.

Steps to reproduce.

  1. Come up with a bogus myFakeGetRandomBytes(typedArray) method that generates non-random stuff.

  2. window.crypto.getRandomBytes = myFakeGetRandomBytes

  3. Import signal as normal.

Conclusion

I believe this exploit speaks to the absolute necessity of keeping the browser environment isolated from normal userland browser, which is probably a madhouse of unsafe code running, reading the page, etc. If you must run the signal protocol in-browser, run it in Electron, or as a Chrome app (Signal Desktop currently does the latter).

In the future, we may think about moving toward emscripten-compiled dependencies for cryptographic primitives. At the end of the day, window.crypto can be absolutely anything. If we can bundle all primitives with the rest of the application code, we can verify the integrity of that one JS bundle, e.g. with subresource integrity.

The npm install signal-protocol command does not work

When I execute the installation command
npm install signal-protocol
it gives me the following result:

[email protected] install C:\xampp\htdocs\chat\node_modules\node-webc
rypto-ossl
node-gyp rebuild

C:\xampp\htdocs\chat\node_modules\node-webcrypto-ossl>if not defined npm_config_
node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\....
\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild )
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.InvalidPlatform
.Targets(23,7): error MSB8007: La plataforma del proyecto 'nodessl.vcxproj' no
es válida. Plataforma='x64'. Este mensaje puede aparecer porque está intentando
compilar un proyecto sin un archivo de solución y ha especificado una platafor
ma distinta de la predeterminada que no existe para dicho proyecto. [C:\xampp\h
tdocs\chat\node_modules\node-webcrypto-ossl\build\nodessl.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules
npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:106:13)
gyp ERR! stack at ChildProcess.emit (events.js:191:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:215:12)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej
s\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
gyp ERR! cwd C:\xampp\htdocs\chat\node_modules\node-webcrypto-ossl
gyp ERR! node -v v6.10.3
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\
node_modules\npm\bin\npm-cli.js" "install" "signal-protocol"
npm ERR! node v6.10.3
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebui
ld'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-webcrypto-ossl p
ackage,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs node-webcrypto-ossl
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls node-webcrypto-ossl
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! C:\xampp\htdocs\chat\npm-debug.log

C:\xampp\htdocs\chat>npm install node-gyp rebuild
npm WARN prefer global [email protected] should be installed with -g
[email protected] C:\xampp\htdocs\chat
+-- [email protected]
-- [email protected] -- [email protected]
`-- [email protected]

I would like to know if you can help me with the problem
Thank you very much

TypeError: Cannot read property 'privKey' of undefined

Hi there, I'm running into the following error when initiating a session using the signal-protocol:

TypeError: Cannot read property 'privKey' of undefined
    at SessionBuilder.<anonymous> (/Users/admin/projects/realtimelaw/node_modules/signal-protocol/src/SessionBuilder.js:147:66)
    at process._tickCallback (internal/process/next_tick.js:103:7)

Here's the relevant section of my code:

// START Building a Session
    var address = new signal.SignalProtocolAddress('test', 0);

    // Instantiate a SessionBuilder for a remote recipientId + deviceId tuple.
    var sessionBuilder = new signal.SessionBuilder(store, address);

    // Process a prekey fetched from the server. Returns a promise that resolves
    // once a session is created and saved in the store, or rejects if the
    // identityKey differs from a previously seen identity for this address.
    store.loadIdentityKey(defaultEndpoint.registrationId).then(function(identityKey) {
      store.loadSignedPreKey(defaultEndpoint.registrationId).then(function(signedPreKey) {
        store.loadPreKey(defaultEndpoint.registrationId).then(function(preKey) {
          var signature = str2ab(defaultEndpoint.signature);
          console.log(signature)
          var promise = sessionBuilder.processPreKey({
              registrationId: defaultEndpoint.registrationId,
              identityKey: identityKey.pubKey,
              signedPreKey: {
                  keyId     : defaultEndpoint.registrationId,
                  publicKey : signedPreKey.pubKey,
                  signature : signature
              },
              preKey: {
                  keyId     : defaultEndpoint.registrationId,
                  publicKey : preKey.pubKey
              }
          });
          promise.then(function onsuccess() {
            console.log('success');
            // encrypt messages
            var plaintext = "Hello world";
            var sessionCipher = new signal.SessionCipher(store, address);
            sessionCipher.encrypt(plaintext).then(function(ciphertext) {
                // ciphertext -> { type: <Number>, body: <string> }
                handle(ciphertext.type, ciphertext.body);
            });
          });

          promise.catch(function onerror(error) {
            console.log(error);
            // handle identity key conflict
          });
        });
      });
    })

Any tips?

store?

Hey, I feel a little stupid but I can't understand where store comes from?

Make PreKey optional in PreKeyBundle?

Apparently, a PreKeyBundle does not need to contain a one-time PreKey. (See the X3DH spec, 3.3 and 4.2 especially).

Including a PreKey in the bundle is certainly recommended. However, if the key server runs out of PreKeys for Bob, with PreKeys being optional, Bob can still be reachable by others trying to start sessions with him.

Some codes are different from the main source

I haven't check the rest but at first try I already received issue on mishandled preKeys because of this discrepancy...hope to be fixed sooner...thanks
@SessionBuilder.js
original
image

current code
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.