Saturday, October 12, 2019

Firebase encrypting user data with Public / Private key pair

After user A logs in a random public private key pair is generated on his phone. eg.: use Ecc Curve25519
The private key from A is stored securely on his phone
The public key from A is stored in firebase and is accessible to anybody that chats with A.
If X sends a message to A he fetches the public key from A from firebase encrypts the message for A locally and stores the encrypted message on firebase in the inbox from A
A downloads the encrypted message from firebase and decrypts it with his private key stored on his phone
(vice versa for A to X)

If A want's to move to another phone or wants to use multiple phones you can do this that way:

Ask A to define a strong password to encrypt his locally stored private key. (or create a random passphrase and use QR codes for key exchange)
Encrypt the private key locally (eg.: use AES256) on his phone with the password from step 1 and upload it to firebase. (optional sign it with his private key)
Download the encrypted private key from the second device from A
Ask for the passphrase on the second device from A and store the private key securely (optional check the signature with the public key from A)
Delete the encrypted private key from firebase if no backup is wanted

references:
https://stackoverflow.com/questions/38304258/how-to-encrypt-user-data-in-firebase

Do firebase encrypt the data on transit as well as on Rest?


Google Cloud Platform encrypts customer data stored at rest by default, with no additional action required from you

Data in Google Cloud Platform is broken into subfile chunks for storage, and each chunk is encrypted at the storage level with an individual encryption key. The key used to encrypt the data in a chunk is called a data encryption key (DEK). Because of the high volume of keys at Google, and the need for low latency and high availability, these keys are stored near the data that they encrypt. The DEKs are encrypted with (or “wrapped” by) a key encryption key (KEK). Customers can choose which key management solution they prefer for managing the KEKs that protect the DEKs that protect their data.

The summary is that the data is encrypted in transit, and it is stored on encrypted disks on the servers. If you enable local persistence on the device, the on device data is not encrypted.

But administrators of the app can see the data in the Firebase console. If it is a requirement of your app that administrators can't read this data, then you'll need to encrypt it on the client before sending it to Firebase.


references:
https://stackoverflow.com/questions/38788258/encryption-of-data-between-clients-and-firebase-real-time-database
https://cloud.google.com/security/encryption-at-rest/#googles_default_encryption



Friday, September 13, 2019

iOS UNUserNotifications Learning



The trigger is the main this. We can either use TimeInterval or Calendar Trigger.
For repeating intervals, 60 seconds or more must be the minimum between two repeating ones.
Does it actually apply for non repeating? For e.g. If we set 5 different alarms separately
With 5 different identifiers, do they fire? To be checked!

From the investigations by doing sample, the info that I could collect is that we are not able to
Get the notification even if not repeat is set to true and even if the identifier is set as unique one,
It just posts for 2 and then it stops posting!. Not sure if it is something specific to testing


OK with a bit of investigation, the crux is around the type of trigger. The time interval trigger could be used
For repeating ones.

Below setup works well to repeat the notification every X times

let content = UNMutableNotificationContent()
        content.title = "Pizza Time!!"
        content.body = "Monday is Pizza Day"

var timeInterval : TimeInterval = 60;

let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: timeInterval,
            repeats: true)
        content.title = "Pizza Time!! "
        let request = UNNotificationRequest(identifier: baseID, content: content, trigger: trigger)
       
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("error in pizza reminder: \(error.localizedDescription)")
            }
        }


Now as per documentation, we should not have < 60 seconds for a repeating one.

This works best if schedule every X second using scheduler interval than calendar date.


References:
https://makeapppie.com/2017/01/31/how-to-repeat-local-notifications/

CWE, and CERT Secure Coding Standards



Common Weakness Enumeration

The Common Weakness Enumeration (CWE) is a unified, measurable set of software weaknesses that enables the effective discussion, description, selection, and use of software security tools and services that can find these weaknesses in source code and operational systems. The CWE also enables better understanding and management of software weaknesses related to architecture and design. It enumerates design and architectural weaknesses, as well as low-level coding and design errors.

CERT Secure Coding Standards

CERT is developing secure coding standards for commonly used programming languages such as C, C++, and Java through a broad-based community effort that includes members of the software development and software security communities. Well-documented and enforceable coding standards are essential to secure software development. Coding standards encourage programmers to follow a uniform set of rules and guidelines determined by the requirements of the project and organization, rather than by the programmer’s familiarity or preference. Once established, these standards can be used as a metric to evaluate source code (using manual or automated processes) to determine compliance with the standard.

CERT secure coding standards include guidelines for avoiding coding and implementation errors, as well as low-level design errors.

CERT-CWE Relationship
The CWE and the CERT secure coding standards perform separate but mutually supportive roles. Simply stated, the CWE provides a comprehensive repository of known weaknesses, while CERT secure coding standards identify insecure coding constructs that, if present in code, could expose a weakness or vulnerability in the software. Not all weaknesses enumerated in the CWE are present in any particular secure coding standard because not all weaknesses are present in each language and because the CWE also includes high-level design issues. Not all CERT secure coding guidelines are mapped directly to weaknesses in the CWE because some coding errors can manifest in ways that do not directly correlate to any given weakness. Both tools are necessary in evaluating the security and safety of software systems.


References:
https://resources.sei.cmu.edu/library/asset-view.cfm?assetid=50399
https://www.us-cert.gov/bsi/articles/knowledge/coding-practices/mitre-cwe-and-cert-secure-coding-standards

Node JS - C++ Add On with file reading



Basic C++ code to read the text file is below

#include
using namespace std;

ifstream inFile;

inFile.open("C:\\temp\\datafile.txt");

if (!inFile) {
    cerr << "Unable to open file datafile.txt";
    exit(1);   // call system to stop
}

while (inFile >> x) {
  sum = sum + x;
}

inFile.close();


Now the above can be converted to node module like the below. The same worked without issues


#include "functionexample.h"
#include
#include
using namespace std;
std::string functionexample::hello(){
    return "Hello World";
}
Napi::String functionexample::HelloWrapped(const Napi::CallbackInfo& info)
{
    Napi::Env env = info.Env();
    Napi::String returnValue = Napi::String::New(env, functionexample::hello());
    ifstream inFile;
    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
//        exit(1); // terminate with error
    }
    else {
        cout << "Opened the file";
    }
    return returnValue;
}
Napi::Object functionexample::Init(Napi::Env env, Napi::Object exports)
{
    exports.Set("hello", Napi::Function::New(env, functionexample::HelloWrapped));
    return exports;
}




References:
http://www.fredosaurus.com/notes-cpp/io/readtextfile.html

What is Web Fingerprinting?



Web Finger printing is something that lets us to uniquely identify a browser execution which in case if to be done on an non logged in environment.

Usual sources for web finger printing are


    User Agent
    HTTP_ACCEPT Headers
    GEO-ip

There is an express middleware which is helping to implement the finger printing and it is like below

var Fingerprint = require('express-fingerprint')

app.use(Fingerprint({
    parameters:[
        // Defaults
        Fingerprint.useragent,
        Fingerprint.acceptHeaders,
        Fingerprint.geoip,

        // Additional parameters
        function(next) {
            // ...do something...
            next(null,{
            'param1':'value1'
            })
        },
        function(next) {
            // ...do something...
            next(null,{
            'param2':'value2'
            })
        },
    ]
}))

app.get('*',function(req,res,next) {
    // Fingerprint object
    console.log(req.fingerprint)
})


References:
https://www.npmjs.com/package/express-fingerprint

Thursday, September 12, 2019

Procedure for creating Node JS add ons

Below is how to setup the boiler plate code

mkdir test-addon
cd test-addon
git init
npm init

Now install the dependencies

npm install node-gyp --save-dev
npm install node-addon-api

node-gyp is the toolchain to compile the addons.
node-addon-api is a helper project as described earlier that will make writing C++ addons easier.


Couple of files that are important during the process are:

1. Bindings.gyp
2. package.json

Below is a sample content for this

Binding.gyp

{
    "targets": [{
        "target_name": "testaddon",
        "cflags!": [ "-fno-exceptions" ],
        "cflags_cc!": [ "-fno-exceptions" ],
        "sources": [
            "cppsrc/main.cpp"
        ],
        'include_dirs': [
            "<!@(node -p \"require('node-addon-api').include\")"
        ],
        'libraries': [],
        'dependencies': [
            "<!(node -p \"require('node-addon-api').gyp\")"
        ],
        'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
    }]
}

package.json

{
  "name": "test-addon",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "gypfile": true,
  "scripts": {
    "build": "node-gyp rebuild",
    "clean": "node-gyp clean"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "node-gyp": "^3.7.0"
  },
  "dependencies": {
    "node-addon-api": "^1.3.0"
  }
}


Just to note, gypfile:true should be present here

Now having these files set up, compilation of the modules can be done in the below steps

npm run build

This will generate the testaddon.node file in the release folder


The add on can be used like this below

const testAddon = require('./build/Release/testaddon.node');
console.log('addon',testAddon);
module.exports = testAddon;


binding.gyp file contains all the files that need to be compiled and all the include files / libraries that the project will be using. If you notice we have added cppsrc/main.cpp file as our source file.


References:
https://medium.com/@atulanand94/beginners-guide-to-writing-nodejs-addons-using-c-and-n-api-node-addon-api-9b3b718a9a7f