lundi 27 janvier 2014

Full HTTPS REST server in Node.js

Posted by Bogomil Shopov, on 

How to write a simple HTTPS JSON REST server using node.js components. 

0. Create certificates.

If you don’t have valid https certificates, you can generate one for testing purposes. If you need one cool certificate, you can join cacert community. Anyway, let’s openssl for a while:
openssl genrsa -out privatekey.pem 1024 
openssl req -new -key privatekey.pem -out certrequest.csr 
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

1. Install additional modules.

We will need just one aditional module, called journey.
It’s working only in JSON mode, but anyway I don’t like XML REST at all. JSON is the future, baby.
npm install journey

2. Writing the router.js file.

- Define the modules required:
var journey = require('journey');
var https = require('https');
var fs = require('fs');
- Define the certificates part:
var privateKey = fs.readFileSync('../certs/privatekey.pem');
var certificate = fs.readFileSync('../certs/certificate.pem');
 
var options = {
  key: privateKey,
  cert: certificate
};
- Define the router that will handle all REST requests (GET, POST, PUT, DELETE):
var mrouter = new (journey.Router)();
- Define the map of all requests. In other words what to do when the router receive a request:
mrouter.map(function () {
// Default URL
this.root.bind(function (req, res) { res.send("Welcome to my application") });
 
//GET request on /databases
this.get('/databases').bind(function (req, res) {
do something
});
 
//GET request on a specific database - /database/users21
this.get(/^databases\/([A-Za-z0-9_]+)$/).bind(function (req, res, id) {
  //id contains 'users21' part       
 });
 
/**PUT request example. 
* You can deal with as many parameters as you need, just write the regexp for it and assign a parameter. 
* Here is an example to update a document on a collection on MongoDB database. 
* We have 3 user parameters - 6 parameters in URL:
**/
this.put(/^databases\/([A-Za-z0-9_]+)\/collections+\/([A-Za-z0-9_]+)\/documents+\/([A-Za-z0-9_]+)$/).bind(function (req, res, dbid, collid, docid, data) {
         res.send('update '+docid+ 'in '+collid + 'on: '+ dbid);
 });
}); //end mapping

3. And the last thing we should do is to turn on the HTTPS server and the router

https.createServer(options,function (request, response) {
    var body = "";
 
    request.addListener('data', function (chunk) { body += chunk });
    request.addListener('end', function () {
 
        mrouter.handle(request, body, function (result) {
 
            response.writeHead(result.status, result.headers);
            response.end(result.body);
        });
    });
}).listen(8081);

4. Run and connect your JSON client on httpS://127.0.0.1:8081 to test it.

node router.js

mardi 21 janvier 2014

Secure Clients and Web Browsers with a Self-Signed Certificate


In these procedures, you will learn how to configure secure networking between Kaazing WebSocket Gateway and clients and web browsers using self-signed certificates. Typically, a self-signed certificate is intended for limited development and testing environments.
In this procedure, you will configure applications for TLS/SSL connections with the Gateway in the following ways:

Creating the Truststore and Keystore

Creating the Truststore and Keystore

The SSL configuration works through two separate files that define the server and client side of the encryption configuration. Because individual hosts within a Tungsten Replicator configuration are both servers (when acting as a master, or when providing status information), and clients (when reading remote THL and managing nodes remotely), both the server and client side of the configuration must be configured. Configuration for all systems relies on two files, the truststore, which contains the server certificate information (the certificates it will accept from clients), and the keystore , which manages the client certificate information (the certificates that will be provided to servers). The truststore and keystore hold SSL certificate information, and are password protected.
The keystore and truststore operate by holding one or more certificates that will be used for encrypting communication. The following certificate options are available:
  • Create your own server and client certificates
  • Create your own server certificates, get the server certificate signed by a Certificate Authority (CA), and use a corresponding signed client certificate
  • Use a server and client certificate already signed by a CA. Care should be taken with these certificates, as they are associated with specific domains and/or hosts, and may cause problems in a dynamic environment.
In a multi-node environment such as Tungsten Replicator, all the hosts in the dataservice can use the same keystore and truststore certificates. The tpm command will distribute these files along with the configuration when a new installation is deployed, or when updating an existing deployment.

2.18.1.1. Creating Your Own Client and Server Certificates

Because the client and server components of the Tungsten Replicator configuration are the same, the same certificate can be used and add to both the keystore and truststore files.
The process is as follows:
  1. Create the keystore and generate a certificate
  2. Export the certificate
  3. Import the certificate to the truststore
To start, use the supplied keytool to create a keystore and populate it with a certificate. The process asks for certain information. The alias is the name to use for the server and can be any identifier. When asked for the first and last name, use localhost, as this is used as the server identifier for the certificate. The other information should be entered accordingly.
Keystores (and truststores) also have their own passwords that are used to protect the store from updating the certificates. The password must be known as it is required in the configuration so that Tungsten Replicator can open the keystore and read the contents.
keytool -genkey -alias replserver -keyalg RSA -keystore keystore.jks The above process has created the truststore and the 'server' certificate, stored in the file keystore.jks.
Alternatively, you can create a new certificate in a keystore non-interactively by specifying the passwords and certificate contents on the command-line:
keytool -genkey -alias replserver \ -keyalg RSA -keystore keystore.jks \ -dname "cn=localhost, ou=IT, o=Continuent, c=US" \ -storepass password -keypass password Now you need to export the certificate so that it can be added to the truststore as the trusted certificate:
keytool -export -alias replserver -file client.cer -keystore keystore.jks This has created a certificate file in client.cer that can now be used to populate your truststore. When added the certificate to the truststore, it must be identified as a trusted certificate to be valid. The password for the truststore must be provided. It can be the same, or different, to the one for the keystore, but must be known so that it can be added to the Tungsten Replicator configuration.
keytool -import -v -trustcacerts -alias replserver -file client.cer -keystore truststore.ts This has created the truststore file, truststore.ts.
A non-interactive version is available by using the -noprompt option and supplying the truststore name:
keytool -import -trustcacerts -alias replserver -file client.cer \ -keystore truststore.ts -storepass password -noprompt The two files, the keystore (keystore.jks), and truststore (truststore.ts), along with their corresponding passwords can be now be used .

2.18.1.2. Creating a Custom Certificate and Getting it Signed

You can create your own certificate and get it signed by an authority such as VeriSign or Thawte. To do this, the certificate must be created first, then you create a certificate signing request, send this to your signing authority, and then import the signed certificate and the certificate authority certificate into your keystore and truststore.
Create the certificate:
keytool -genkey -alias replserver -keyalg RSA -keystore keystore.jks Create a new signing request the certificate:
keytool -certreq -alias replserver -file certrequest.pem \ -keypass password -keystore keystore.jks -storepass password This creates a certificate request, certrequest.pem. This must be sent the to the signing authority to be signed.
  • Official Signing
    Send the certificate file to your signing authority. They will send a signed certificate back, and also include a root CA and/or intermediary CA certificate. Both these and the signed certificate must be included in the keystore and truststore files.
    First, import the returned signed certificate:
    keytool -import -alias replserver -file signedcert.pem -keypass password \ -keystore keystore.jks -storepass password Now install the root CA certificate:
    keytool -import -alias careplserver -file cacert.pem -keypass password \ -keystore keystore.jks -storepass password

    Note

    If the import of your certificate with keytool fails, it may be due to an incompatibility with some versions of OpenSSL, which fail to create suitable certificates for third-party tools. In this case, see Section 2.18.1.4, “Converting SSL Certificates for keytool for more information.
    And an intermediary certificate if you were sent one:
    keytool -import -alias interreplserver -file intercert.pem -keypass password \ -keystore keystore.jks -storepass password Now export the signed certificate so that it can be added to the truststore. Although you can import the certificate supplied, by exporting the certificate in your keystore for inclusion into your truststore you can ensure that the two certificates will match:
    keytool -export -alias replserver -file client.cer -keystore keystore.jks The exported certificate and CA root and/or intermediary certificates must now be imported to the truststore:
    keytool -import -trustcacerts -alias replserver -file client.cer \ -keystore truststore.ts -storepass password -nopromptkeytool -import -trustcacerts -alias careplserver -file cacert.pem \ -keystore truststore.ts -storepass password -nopromptkeytool -import -trustcacerts -alias interreplserver -file intercert.pem \ -keystore truststore.ts -storepass password -noprompt
  • Self-Signing
    If you have setup your own certificate authority, you can self-sign the request using openssl:
    openssl ca -in certrequest.pem -out certificate.pem Convert the certificate to a plain PEM certificate:
    openssl x509 -in certificate.pem -out certificate.pem -outform PEM Finally, for a self-signed certificate, you must combine the signed certificate with the CA certificate:
    cat certificate.pem cacert.pem > certfull.pem This certificate can be imported into your keystore and truststore.
    To import your signed certificate into your keystore:
    keytool -import -alias replserver -file certfull.pem -keypass password \ -keystore keystore.jks -storepass password Then export the certificate for use in your truststore:
    keytool -export -alias replserver -file client.cer -keystore keystore.jks The same certificate must also be exported and added to the truststore:
    keytool -import -trustcacerts -alias replserver -file client.cer \ -keystore truststore.ts -storepass password -noprompt
This completes the setup of your truststore and keystore. The files created can be used in your tpm configuration. See Section 2.18.3, “Configuring the Secure Service through tpm.

2.18.1.3. Using an existing Certificate

If you have an existing certificate (for example with your MySQL, HTTP server or other configuration) that you want to use, you can import that certificate into your truststore and keystore. When using this method, you must import the signed certificate, and the certificate for the signing authority.
When importing the certificate into your keystore and truststore, the certificate supplied by the certificate authority can be used directly, but must be imported alongside the certificate authorities root and/or intermediary certificates. All the certificates must be imported for the SSL configuration to work.
The certificate should be in the PEM format if it is not already. You can convert to the PEM format by using the openssl tool:
openssl x509 -in signedcert.crt -out certificate.pem -outform PEM First, import the returned signed certificate:
keytool -import -file certificate.pem -keypass password \ -keystore keystore.jks -storepass password

Note

If the import of your certificate with keytool fails, it may be due to an incompatibility with some versions of OpenSSL, which fail to create suitable certificates for third-party tools. In this case, see Section 2.18.1.4, “Converting SSL Certificates for keytool for more information.
Now install the root CA certificate:
keytool -import -file cacert.pem -keypass password \ -keystore keystore.jks -storepass password And an intermediary certificate if you were sent one:
keytool -import -file intercert.pem -keypass password \ -keystore keystore.jks -storepass password Now export the signed certificate so that it can be added to the truststore:
keytool -export -alias replserver -file client.cer -keystore keystore.jks The exported certificate and CA root and/or intermediary certificates must now be imported to the truststore:
keytool -import -trustcacerts -alias replserver -file client.cer \ -keystore truststore.ts -storepass password -nopromptkeytool -import -trustcacerts -alias replserver -file cacert.pem \ -keystore truststore.ts -storepass password -nopromptkeytool -import -trustcacerts -alias replserver -file intercert.pem \ -keystore truststore.ts -storepass password -noprompt

2.18.1.4. Converting SSL Certificates for keytool

Some versions of the openssl toolkit generate certificates which are incompatible with the certificate mechanisms of third-party tools, even though the certificates themselves work fine with OpenSSL tools and libraries. This is due to a bug which affected certain releases of openssl 1.0.0 and later and the X.509 certificates that are created.
This problem only affects self-generated and/or self-signed certificates generated using the openssl command. Officially signed certificates from Thawte, VeriSign, or others should be compatible with keytool without conversion.
To get round this issue, the keys can be converted to a different format, and then imported into a keystore and truststore for use with Tungsten Replicator.
To convert a certificate, use openssl to convert the X.509 into PKCS12 format. You will be prompted to enter a password for the generated file which is required in the next step:
openssl pkcs12 -export -in client-cert.pem -inkey client-key.pem >client.p12 To import the converted certificate into a keystore, specifying the destination keystore name, as well as the source PKCS12 password used in the previous step:
keytool -importkeystore -srckeystore client.p12 -destkeystore keystore.jks -srcstoretype pkcs12 The same process can be used to import server certificates into truststore, by converting the server certificate and private key:
openssl pkcs12 -export -in server-cert.pem -inkey server-key.pem >server.p12 Then importing that into a truststore
keytool -importkeystore -srckeystore server.p12 -destkeystore truststore.ts -srcstoretype pkcs12 For official CA certificates, the generated certificate information should be valid for importing using keytool, and this file should not need conversion.

Glassfish: Secure Admin Must Be Enabled To Access The DAS Remotely

You can enable remote access with the following command:
asadmin --host www.yourdomain.com --port 4848 enable-secure-admin
Then stop/start glassfish immediately after enabling secure admin. 4848 is the default port

if you have this kind of errors
At least one admin user has an empty password

change or create the admin password
asadmin --port 4848 change-admin-password
Enter admin user name [default: admin]> 
Enter admin password> 
Enter new admin password> secret
Enter new admin password again> secret 

 then again  asadmin --host www.yourdomain.com --port 4848 enable-secure-admin

dimanche 12 janvier 2014

Premiers pas avec JSF

Une introduction au framework JSF, vous aller découvrir en quoi il consiste dans les grandes lignes, étudier ses composants de base, puis mettre en place un exemple très simple et enfin le comparer à son équivalent réalisé avec la technologie JSP.

Voici le lien vers la présentation http://fr.openclassrooms.com/informatique/cours/creez-votre-application-web-avec-java-ee/premiers-pas-avec-jsf

vendredi 10 janvier 2014

File Upload is Easy in JSF2.2 and netbeans 7.4

To bring the File Upload feature in Java based web application is one of the difficult and complex job, we need to dependent on 3rd party libraries like Apache Commons FileUpload Libraries. These libraries codes are complex and most of them boilerplate code.

If we are using Java Server Faces (JSF), we have the page with some fields and file upload menu the its add more complexity, fields are binded to backing bean but these file uploads components are need to tie up with some 3rd party file upload libraries.

In Primefaces provide easy way to do the file upload in JSF web application, even though primefaces internally used the same Apache Commons FileUpload Libraries, but provide simple JSF tags. We need configure some listeners.

In Servlet 3.0 they introduced the Part Interfaces and @MultiPartConfig annotations for easy way to do the file upload without any 3rd party libs, Servlet 3.0 is part of Java EE 6 specification. so any servlet 3.0 implementation servers like Tomcat 7, Jboss 6, GlassFish 3 they can get benefit of servlet 3.0. but this feature is not available in JSF 2.1. so again still it's complex to use file upload in JSF, because we need to mix servlet and JSF backing bean.

At last JSF 2.2 is added the File Upload component, so we just use <h:inputFile> tag to make the file upload web application so easily, and this component use the Part interface, which its introduced its part of Servlet 3.0. so this JSF2.2 libraries is working perfectly with Tomcat 7 (because tomcat 7 is implemented the Servlet 3.0 spec).

To bring the File Upload feature we need to follow 3 step process

  1. Add <h:inputFile> tag in JSF page
  2. Add enctype="multipart/form-data" attribute in enclosing <h:form> tag
  3. Create the field in Backing bean with Part data type.

Setup the Environment

Add JavaServerFace framework in Netbeans and choose JSF2.2 library

Step 1: Add <h:inputFile> tag in JSF page

In JSF page add the <h:inputFile> tag where we need file upload component

  <h:inputFile value="#{demoBean.file1}" />

here we bind the value property to file1 field, which data type is Part, check the third step



Step 2: Add enctype="multipart/form-data" attribute in enclosing <h:form> tag

When u want file upload feature then we need to inform the browser that form may contain multiple normal text input field and some file upload component, so prepare the POST request in special form, like parts by part with special delimiter boundary.
<h:form enctype="multipart/form-data">
</h:form>

so index.xhtml file looks like
  1. <h:head>  
  2.     <title>Facelet Title</title>  
  3. </h:head>  
  4. <h:body>  
  5.     Hello from Facelets  
  6.       
  7.     <h:form enctype="multipart/form-data">  
  8.         <h:inputfile value="#{demoBean.file1}"></h:inputfile>  
  9.   
  10.           
  11.         <h:inputfile value="#{demoBean.file2}"> </h:inputfile>  
  12.   
  13.         <h:commandbutton action="#{demoBean.upload()}" value="Upload">  
  14.     </h:commandbutton></h:form>  
  15. </h:body>  



Step 2: Create Backing Bean

now create the backing bean for this page. we need to create the fields for input File component with Part type. Part interface is introduced in servlet 3.0 for represent the file chunks sent by browser, JSF 2.2 use this Part interface, Using the Part interface we can get the header information of each file chunk sent by browser, these header contain the file name and other meta information about the file.

Part interface also contain write() method to write the file contents into specified server location, or u can get the InputStream then we can process it.

DemoBean.java

  1. import java.io.IOException;  
  2. import javax.faces.bean.ManagedBean;  
  3. import javax.faces.bean.SessionScoped;  
  4. import javax.servlet.http.Part;  
  5.   
  6.   
  7. /** 
  8.  * 
  9.  * @author ramki 
  10.  */  
  11. @ManagedBean  
  12. @SessionScoped  
  13. public class DemoBean {  
  14.   
  15.     private Part file1;  
  16.     private Part file2;  
  17.   
  18.     // getters and setters for file1 and file2  
  19.   
  20.     public String upload() throws IOException {  
  21.          InputStream inputStream = file1.getInputStream();          
  22.         FileOutputStream outputStream = new FileOutputStream(getFilename(file1));  
  23.           
  24.         byte[] buffer = new byte[4096];          
  25.         int bytesRead = 0;  
  26.         while(true) {                          
  27.             bytesRead = inputStream.read(buffer);  
  28.             if(bytesRead > 0) {  
  29.                 outputStream.write(buffer, 0, bytesRead);  
  30.             }else {  
  31.                 break;  
  32.             }                         
  33.         }  
  34.         outputStream.close();  
  35.         inputStream.close();  
  36.          
  37.         return "success";  
  38.     }  
  39.   
  40.     private static String getFilename(Part part) {  
  41.         for (String cd : part.getHeader("content-disposition").split(";")) {  
  42.             if (cd.trim().startsWith("filename")) {  
  43.                 String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"""");  
  44.                 return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.  
  45.             }  
  46.         }  
  47.         return null;  
  48.     }  
  49. }  


here we need get the file name from the Header of the chunk, so there is boilerplate code can do, here i don't like this method :-(

there is no direct method to retrieve the file name. so use this code we can get the name of the file is uploaded by client, then using write method we can store into server.


Get the sample project from  Github or download from here