Sunday, October 13, 2019

What is Content Security Policy Header

The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS).

Syntax is like below

Content-Security-Policy: ;

Below are the directives

Fetch directives control locations from which certain resource types may be loaded.

child-src : Defines the valid sources for web workers and nested browsing contexts loaded using elements such as and

Checklist and guidelines for OWASP Mobile Security Testing

The GitHub pages given in the link give the list of test to be performed in an XL file. The contents in the spreadsheet is linked to the GitHub page again which gives ample notes about the security.


References:
https://github.com/OWASP/owasp-mstg/blob/1.1.3/Document/0x04b-Mobile-App-Security-Testing.md#architectural-information
https://github.com/OWASP/owasp-mstg/releases


What is Helmet

Helmet helps you secure your Express apps by setting various HTTP headers. It’s not a silver bullet, but it can help!

To install helmet, below is what to be done

npm install helmet --save

const express = require('express')
const helmet = require('helmet')

const app = express()

app.use(helmet())

Helmet is a collection of 13 smaller middleware functions that set HTTP response headers. Running app.use(helmet()) will not include all of these middleware functions by default.

Below are the various headers that can be set via Helmet

contentSecurityPolicy => For setting Content Security Policy Header
dnsPrefetchControl => controls browser DNS prefetching
expectCt for handling Certificate Transparency
featurePolicy -> to limit site features
frameGuard -> to prevent click jacking
hidePoweredBy => to remove X-Powered-By Header
Hsts => for HTTP strict transport security
ieNoOpen => sets X-Download-Options for IE8+
noCache => to disable client side caching
noSniff => To keep clients from sniffing the MIME type
permittedCrossDomainPolicies for handling Adobe products cross domain requests
referrerPolicy to hide the referrer header
xssFilter => adds some small XSS protections


References:
https://helmetjs.github.io

Material UI - TextArea

Below is the code that will help to have a text area in a material ui project. The regular TextField apparently cannot be used for showing multi line things

              rowsMax={4}
              fullWidth={true}
              className={classes.textField}
              aria-label="maximum height"
              placeholder="Maximum 4 rows"
              defaultValue="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
                  ut labore et dolore magna aliqua."
            />


This is not really required btw way. The TextField is having



References:
https://material-ui.com/components/textarea-autosize/

Mac Terminal How to copy one folder contents to another

Below is how to do it.

cp -a /source/. /dest/

References:
https://askubuntu.com/questions/86822/how-can-i-copy-the-contents-of-a-folder-to-another-folder-in-a-different-directo

Creating Electron app from React code base

The documentation was awesome. And most of the things did work. However, only one change that I had to do was below

First of all, took the react web application to a different folder and did a yarn to install and verify the app is still running.

Yarn start => to make sure the react web app is running

Now add electron using the step below

yarn add electron electron-builder --dev

Add some dev tools we'll need.

yarn add wait-on concurrently --dev
yarn add electron-is-dev

Now we need the electron.js file for Browser window, which looks like the below


const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

const path = require('path');
const isDev = require('electron-is-dev');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({width: 900, height: 680});
  mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, '../build/index.html')}`);
  if (isDev) {
    // Open the DevTools.
    //BrowserWindow.addDevToolsExtension('');
    mainWindow.webContents.openDevTools();
  }
  mainWindow.on('closed', () => mainWindow = null);
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});


Add the below to the scrips section

"dev": "concurrently \"BROWSER=none yarn start\" \"wait-on http://localhost:3000 && electron .\""

Add the below main tag

"main": "public/electron.js",

Just make sure the electron.js is present inside the public folder

Now, running yarn dev should bring up the application in the electron window/


To solve this we need to use the electron-renderer as the Webpack target... but we don't want to eject CRA to do it. So we use Rescripts. Let me show you.
This is required to add some modules such as fs etc.


yarn add @rescripts/cli @rescripts/rescript-env --dev

Now the react scripts to be converted from


"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",


To


"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",


Now below two files to be geared


.rescriptsrc.js
And have the content below

module.exports = [require.resolve('./.webpack.config.js')]

And another file .webpack.config.js
With the below contents

// define child rescript
module.exports = config => {
  config.target = 'electron-renderer';
  return config;
}

Now run once again and make sure the package is running in dev mode.

This process is breaking the app!! .... now when attempt to start, it just does not load properly. It just give the white screen.


"electron-pack": "build -mw"

To

"electron-pack": "electron-builder -mw"

OK .. looking into further details, below is the error that was seen in the web console.

Uncaught ReferenceError: require is not defined
    at Object.crypto (external "crypto":1)
    at __webpack_require__ (bootstrap:785)
    at fn (bootstrap:150)
    at Object../node_modules/react-scripts/node_modules/sockjs-client/lib/utils/random.js (random.js:4)
    at __webpack_require__ (bootstrap:785)
    at fn (bootstrap:150)
    at Object../node_modules/react-scripts/node_modules/sockjs-client/lib/utils/event.js (event.js:3)
    at __webpack_require__ (bootstrap:785)
    at fn (bootstrap:150)
    at Object../node_modules/react-scripts/node_modules/sockjs-client/lib/transport/websocket.js (websocket.js:3)

Looking through the details of this error, found that the electron.js file is having the require statements.
Browsing around, got the solution like this below


 mainWindow = new BrowserWindow({
    width: 900, height: 680, webPreferences: {
      nodeIntegration: true
    }
  });
That's all, it started working.


References:
https://www.codementor.io/randyfindley/how-to-build-an-electron-app-using-create-react-app-and-electron-builder-ss1k0sfer
https://github.com/electron/electron/issues/17241

Node JS, how to setup a TCP server that sends bytes upon request from client



const net = require('net');
const port = 7070;
const host = '127.0.0.1 ';

const server = net.createServer();
server.listen(port, host, () => {
    console.log('TCP Server is running on port ' + port + '.');
});

let sockets = [];

server.on('connection', function(sock) {
    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
    sockets.push(sock);

    sock.on('data', function(data) {
        console.log('DATA ' + sock.remoteAddress + ': ' + data);
        // Write the data back to all the connected, the client will receive it as data from the server
        sockets.forEach(function(sock, index, array) {
            sock.write(sock.remoteAddress + ':' + sock.remotePort + " said " + data + '\n');
        });
    });

    // Add a 'close' event handler to this instance of socket
    sock.on('close', function(data) {
        let index = sockets.findIndex(function(o) {
            return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort;
        })
        if (index !== -1) sockets.splice(index, 1);
        console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
    });
});

The above is the whole crux of it. However, one should also handle the error event. This is needed when the client abruptly close the
Connection

References:
https://www.digitalocean.com/community/tutorials/how-to-develop-a-node-js-tcp-server-application-using-pm2-and-nginx-on-ubuntu-16-04