Selasa, 22 Oktober 2013

Xathrya Sabertooth

Xathrya Sabertooth


NodeJS HTTPS

Posted: 21 Oct 2013 09:31 AM PDT

HTTPS or HTTP Secure is the HTTP protocol over TLS. It is the secure version of HTTP and implemented as separate module in Node. The API itself is very similar to the HTTP one, with some small differences.

HTTPS Server

To create a server, we can do:

var https = require('https'),      fs = require('fs');    var options = {      key: fs.readFileSync('/path/to/server/private-key.pem');      cert: fs.readFileSync('/path/to/server/certificate.pem');  };    https.createServer(options, function(req,res) {      res.writeHead(200, {'Content-Type': 'text/plain'});      res.end('Hello World!');  });

So here, the first argument to https.createServer is an options object that much like in TLS module, provides the private key and the certificate strings.

HTTPS Client

To make a HTTPS request, we must use https module:

var https = require('https'),      options = {          host: 'encrypted.google.com',          port: 443,          path: '/',          method: 'GET'      };    var req = https.request(options, function(res) {      console.log("statusCode: ", res.statusCode);      console.log("headers: ", res.headers);        res.on('data', function(d) {          process.stdout.write(d);      });  });  req.end();

Here options we can change:

  • port: port of host to request to. Defaults is 443
  • key: the client private key string to use for SSL. Defaults to null.
  • cert: the client certificate to use. Defaults to null
  • ca: an authority certificate or array of authority certificates to check the remote host against.

We may want to use the key and cert options if the server needs to verify the client.

Much like http module, this module also offers a shortcut https.get method that can be used:

var https = require('https');  var options = { host: 'encrypted.google.com', path: '/' };  https.get(options, function(res) {      res.on('data', function(d) {          process.console.log(d.toString());      });  });

NodeJS TLS / SSL

Posted: 21 Oct 2013 08:52 AM PDT

Transport Layer Security (TLS) is a successor of Secure Socket Layer (SSL) protocol. The technology allow client /server application to communicate across a network in a way designed to prevent eavesdropping and tampering. TLS and SSL encrypt the segments of network connections above the Transport layer, enabling both privacy and message authentication.

Node uses OpenSSL to provide TLS and/or SSL encrypted stream communication.

TLS is a standard base on the earlier SSL specification. In fact, TLS 1.0 is also known as SSL 3.1, and the latest version (TLS 1.2) is also known as SSL 3.3. From now on we will use TLS instead of SSL.

Public / Private Keys

The keys used in TLS is in pair of public / private keys. A public key is a key which is open publicly, where used by other party to encrypt data they want to sent to us. While the private key, like implied by name, is only known by us or our machine. This key is used to decrypt the message sent by other machine.

Private Key

Each client and server must have a private key. A private key can be generated by openssl utility on the command line by:

openssl genrsa -out private-key.pem 1024

This should create a file named private-key.pem with our private key.

Public Key

All servers and some clients need to have a certificate. Certificates are public keys signed by a Certificate Authority or self-signed. The first step to getting a certificate is to create a “Certificate Signing Request” file. This can be done with:

openssl req -new -key private-key.pem -out csr.pem

This will create CSR named node.csrcsr.pem and using our generated key (private-key.pem). When you are asked for some data, answer it. They will be written in certificate.

The purpose of CSR is to request certificate. That is, if we want a CA (Certificate Authority) to sign our certificate, we could give this file to them to process and they will give us back a certificate.

Alternatively, we can create self-signed certificate with the CSR we had.

openssl x509 -req -in csr.pem -signkey private-key.pem -out certificate.pem

Thus we have our certificate file certificate.pem

TLS Client

We can connect to a TLS server using something like this:

var tls = require('tls'),      fs = require('fs'),      port = 3000,      host = '192.168.1.135',      options = {          key: fs.readFileSync('/path/to/private-key.pem'),          cert: fs.readFileSync('/path/to/certificate.pem')      };    var client = tls.connect(port, host, options, function() {      console.log('connected');      if (client.authorized) {          console.log('authorized: ' + client.authorized);          client.on('data', function(data) {              client.write(data);    // Just send data back to server          });      } else {          console.log('connection not authorized: ' + client.authorizationError);      }  });

First we need to inform Node of the client private key and client certificate, which should be strings. We are then reading the pem files into memory using synchronous version of fs.readFile, fs.readFileSync.

Then, we are connecting to the server. tls.connect returns a CryptoStream object, which we can use normally as ReadStream and WriteStream. We then wait for data from server as we would on a ReadStream, and then we send it back to the server.

TLS Server

TLS server is a subclass of net.Server. With it, we can make everything we can with a net.Server, except that we are doing over a secure connection.

var tls = require('tls'),      fs = require('fs');      options = {          key: fs.readFileSync('/path/to/private-key.pem'),          cert: fs.readFileSync('/path/to/certificate.pem')      };    tls.createServer(options, function(s) {      s.pipe(s);  }).listen(4004);

Beside key and cert options, tls.createServer also accepts:

  • requestCert: if true, the server will request a certificate from clients that connect and attempt to verify that certificate. The default value is false.
  • rejectUnauthorized: If true, the server will reject any connection which is not authorized with the list of supplied CAs. This option only has effect if requestCert is true. The default value is false.

Verification

On both the client and the server APIs, the stream has a property named authorized. This is a boolean indicating if the client was verified by one of the certificate authorities you are using, or one that they delegate to. If s.authorized is false, then s.authorizationError contains the description of how the authorization failed.

NodeJS Streaming HTTP Chunked Responses

Posted: 21 Oct 2013 03:50 AM PDT

NodeJS is extremely streamable, including HTTP responses. HTTP being a first-class protocol in Node, make HTTP response streamable in very convenient way.

HTTP chunked encoding allows a server to keep sending data to the client without ever sending the body size. Unless we specify a “Content-Length” header, Node HTTP server sends the header

Transfer-Encoding: chunked

to client, which makes it wait for a final chunk with length of 0 before giving the response as terminated.

This can be useful for streaming data – text, audio, video – or any other into the HTTP client.

Streaming Example

Here we are going to code an pipes the output of a child process into the client:

var spawn = require('child_process').spawn;    require('http').createServer(function(req, res) {      var child = spawn('tail', ['-f', '/var/log/system.log']);      child.stdout.pipe(res);      res.on('end', function() {          child.kill();      });  }).listen(4000);

Here we are creating an HTTP server and binding it to port 4000.

When there is a new request, we launch a new child process by executing the command “tail -f /var/log/system.log” which output is being piped into the response.

When response ends (because the browser window was closed, or the network connection severed, etc), we kill the child process so it does not hang around indefinitely.

Tidak ada komentar:

Posting Komentar