Merge https://github.com/miracl/milagro-mfa-server

Conflicts:
	README.md
diff --git a/.gitignore b/.gitignore
index 68d56e7..812f591 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,5 +7,7 @@
 config.py
 coverage.xml
 credentials.json
+install
 M_Pin_Backend.egg-info/
 mpin_*_storage.json
+servers/demo/public/mpin
diff --git a/README.md b/README.md
index 90ee86f..72c84f2 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Milagro MFA Services
+# Milagro MFA Server
 
 ## General
 
@@ -12,10 +12,51 @@
 ### Cloning the code from the Git repository
 
 Using standard Git client, clone the code from this repository to a local one.
-The rest of this document assumes that the repository is cloned into `<mpin-backend>`.
-Wherever `<mpin-backend>` appears, it should be replaced with the real location on your machine.
+The rest of this document assumes that the repository is cloned into `<milagro-mfa-server>`.
+Wherever `<milagro-mfa-server>` appears, it should be replaced with the real location on your machine.
 
-### Installing Prerequisites
+### Install with provided script
+
+`install.sh` bash script is provided to ease the install process.
+You can run it from `<milagro-mfa-server>` base directory like this
+```
+ > ./install.sh
+```
+you can provide optional argument to the script <milagro-mfa-js-client-location> where this is an absolute path of
+the location `https://github.com/miracl/milagro-mfa-js-client` is downloaded.
+```
+ > ./install.sh <milagro-mfa-js-client-location>
+```
+If location provided the install script can initiate the frontend build and link the Pin Pad  in the Demo, so the demo is fully operational.
+
+If no location is provided you should change the `mpinJSURL` yourself in demo/config.py. Which may include building the frontend and serve it from some web server.
+
+The script is tested and should work without any issue on Ubuntu 14.04,
+other versions of Ubuntu or Debian based distributions may work but is not guaranteed.
+
+The script install some dependencies from apt-get as packages:
+    * python-dev
+    * python-pip
+    * libffi-dev
+    * git ( We use it to get Milagro crypto library)
+    * cmake ( We use it to build Milagro crypto library)
+
+Several pip packages would be installed too. They can be reviewed in \`<milagro-mfa-server>/requirements/common.txt` and `<milagro-mfa-server>/requirements/dev.txt`
+`INSTALL_TYPE` environment variable is used is control  which file is used. You can use “common” or “dev” as values. “common” is used by default
+The script try its best to detect virtualenv and install python packages inside one if it is founded.
+
+The script build the needed Milagro Crypto ( Version 1.0.0 )
+
+NOTE: While running the script if config file is already found for dta, rps or demo the user would have the option to override its content or keep it as it is.
+
+Review the script for more details.
+
+###Part 1: Installation
+Install all dependencies needed for the services to run.
+
+NOTE: If install.sh script is used you can skip this step
+
+#### Installing Prerequisites
 
 **1** Update your package manager tool
 ```
@@ -27,28 +68,27 @@
  > sudo pip install -r requirements/common.txt
 ```
 
-### Building the Milagro Crypto Libraries
+#### Building the Milagro Crypto Libraries
 
-Clone the [_milagro-crypto_ repository](https://github.com/miracl/milagro-crypto) and checkout tag `1.0.0`.
+Clone the [_milagro-crypto_ repository](https://github.com/miracl/milagro-crypto) 
 ```
 > git clone https://github.com/miracl/milagro-crypto.git
-> git checkout tags/1.0.0
-```
+``` 
 Follow the instructions for your platform from the milagro-crypto [README file](https://github.com/miracl/milagro-crypto/blob/master/README.md#build-instructions).
 
-### Getting Credentials
+#### Getting Credentials
 
 Before running any Milagro Services, you should obtain your *Credentials*.
 This is done with the following script:
 ```
- > cd <mpin-backend>
+ > cd <milagro-mfa-server>
  > python scripts/getCommunityCredentials.py .
 ```
 *NOTE:* Make sure you don't miss the dot (.) at the end of the above command.<br/>
 **Important:** During the above process you will be asked to enter your e-mail address. While this is not mandatory, it is recommended so we can later contact you in case of any problems with the service.
-The above script will download a `credentials.json` file into the `<mpin-backend>` directory.
+The above script will download a `credentials.json` file into the `<milagro-mfa-server>` directory.
 
-### Configuring the Services
+###Part 2: Configuring the Services
 
 The Milagro MFA Services consist of: *Distributed Trusted Authority (D-TA)* and *Relying Party Service (RPS)*.
 The Web Application that integrates with the MFA in order to be able to log-in users using Milagro, is called *Relying Party Application (RPA)*.
@@ -56,12 +96,14 @@
 The initial configuration allows the Demo RPA and the Milagro MFA Services to be access from any machine on the local network.
 Further details about configuration options might be found in the [Documentation](http://docs.miracl.com/m-pin-core-configuration).
 
+NOTE: If install.sh script is used you can skip this step
+
 #### Configuring the D-TA
 
 The source includes a "default" D-TA configuration file that should serve as a template for the actual one. To configure the D-TA perform the following steps:<br/>
-**1** Go to the directory `<mpin-backend>/servers` and copy the `dta/config_default.py` to `dta/config.py`
+**1** Go to the directory `<milagro-mfa-server>/servers` and copy the `dta/config_default.py` to `dta/config.py`
 ```
- > cd <mpin-backend>/servers
+ > cd <milagro-mfa-server>/servers
  > cp dta/config_default.py dta/config.py
 ```
 **2** Generate a hex-encoded 8-byte (or longer) random number. You can do this with the following command:
@@ -76,11 +118,11 @@
 ```
 **5** Add/change the `credentialsFile` parameter, specifying the location for the credential file that was previously obtained:
 ```
-credentialsFile = "<mpin-backend>/credentials.json"
+credentialsFile = "<milagro-mfa-server>/credentials.json"
 ```
 **6** Change the value of the `backup_file` parameter to the path to file where the master secret will be backed up.<br/>
 ```
-backup_file = "<mpin-backend>/backup_dta.json"
+backup_file = "<milagro-mfa-server>/backup_dta.json"
 ```
 **7** Change the value of the `passphrase` parameter as well. You might generate a random string for it as well, or write some phrase of your own.<br/>
 **8** Save the file and exit the editor
@@ -88,24 +130,24 @@
 #### Configuring the RPS
 
 The source includes a "default" RPS configuration file that should serve as a template for the actual one. To configure the RPS perform the following steps:<br/>
-**1** Go to the directory `<mpin-backend>/servers` and copy the `rps/config_default.py` to `rps/config.py`
+**1** Go to the directory `<milagro-mfa-server>/servers` and copy the `rps/config_default.py` to `rps/config.py`
 ```
- > cd <mpin-backend>/servers
+ > cd <milagro-mfa-server>/servers
  > cp rps/config_default.py rps/config.py
 ```
 **2** Using `vi` or other editor, edit the `rps/config.py` file<br/>
 **3** Add/change the `credentialsFile` parameter, specifying the location for the credential file that was previously obtained:
 ```
-credentialsFile = "<mpin-backend>/credentials.json"
+credentialsFile = "<milagro-mfa-server>/credentials.json"
 ```
 **4** Save the file and exit the editor
 
 #### Configuring the Demo RPA
 
 The source includes a "default" Demo RPA configuration file. To configure the Demo RPA perform the following steps:<br/>
-**1** Go to the directory `<mpin-backend>/servers` and copy the `demo/config_default.py` to `demo/config.py`
+**1** Go to the directory `<milagro-mfa-server>/servers` and copy the `demo/config_default.py` to `demo/config.py`
 ```
- > cd <mpin-backend>/servers
+ > cd <milagro-mfa-server>/servers
  > cp demo/config_default.py demo/config.py
 ```
 **2** Generate a base64-encoded 64-byte (or longer) random number. You can do this with the following command:
@@ -125,22 +167,22 @@
 ```
 **6** Save the file and exit the editor
 
-### Running and Testing the Services
+###Part 3: Running and Testing the Services
 
 For development purposes you might run the services from command line. Open 3 terminals and set the following two environment variables as shown below:
 ```
-export PYTHONPATH=<mpin-backend>/lib:/usr/local/lib/python2.7/site-packages
+export PYTHONPATH=<milagro-mfa-server>/lib:/usr/local/lib/python2.7/site-packages
 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
 ```
 To run the services, perform the following commands, each in separate terminal:
 ```
- > python dta/dta.py
+ > python servers/dta/dta.py
 ```
 ```
- > python rps/rps.py
+ > python servers/rps/rps.py
 ```
 ```
- > python demo/mpinDemo.py
+ > python servers/demo/mpinDemo.py
 ```
 For more automated execution, you might need to write start/stop scripts in `/etc/init.d`
 
@@ -163,11 +205,11 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
-	. . .
+    . . .
 </head>
 <body>
 </body>
-	. . .
+    . . .
 </html>
 ```
 Finally, open a browser on any machine that has network access to the machine on which the Milagro MFA Services are running. Browse to `http://<mpin-server-ip>:8005`.
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000..03df987
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,218 @@
+#!/usr/bin/env bash
+
+BASE_DIR=$(pwd)
+
+# Specify where the frontend repo is located
+FRONTEND_LOCATION=${FRONTEND_LOCATION:-$1}
+
+INSTALL_TYPE=${INSTALL_TYPE:-"common"}
+
+function install_dependencies {
+    echo "Install needed packages"
+
+    # Update packages cache
+    sudo apt-get update
+
+    # Install needed packages
+    sudo apt-get install python-dev python-pip libffi-dev git cmake
+
+    # Install the required packages
+    VIRTUALENV=$(python -c 'import sys; print hasattr(sys, "real_prefix")' 2>/dev/null)
+    if [[ $VIRTUALENV == "True" ]]
+    then
+        # If in virtualenv use the local provided pip
+        # We assume that activation script is used and pip as command points to virtualenv pip
+        pip install -r "requirements/$INSTALL_TYPE.txt"
+    else
+        # If we are not in virtualenv we just install global
+        sudo pip install -r "requirements/$INSTALL_TYPE.txt"
+    fi
+}
+
+function get_crypto {
+    echo "Get Milagro Crypto Libraries"
+    mkdir -p install
+    cd install || exit
+    git clone https://github.com/miracl/milagro-crypto.git
+
+    cd milagro-crypto || exit
+}
+
+function build_crypto {
+    echo "Build Milagro crypto library"
+
+    mkdir Release
+    cd Release || exit
+    cmake ..
+    make
+    make test
+    sudo make install
+}
+
+function get_credentials {
+    cd "$BASE_DIR" || exit
+    python scripts/getCommunityCredentials.py .
+}
+
+function build_frontend {
+    echo "build frontend js"
+
+    # Go to frontend code location
+    cd "$FRONTEND_LOCATION" || exit
+    # run frontend build script
+    ./build.sh
+
+    # Create the needed directory and link the frontend
+    cd "$BASE_DIR/servers/demo/public/" || exit
+
+    ln -sf "$FRONTEND_LOCATION/build/out/browser" mpin
+}
+
+function get_dependencies {
+    install_dependencies
+
+    get_crypto
+
+    build_crypto
+
+    get_credentials
+
+}
+
+# Configure services
+
+function configure_dta {
+    echo "Configure DTA"
+
+    cd "$BASE_DIR/servers/dta" || exit
+
+    CONFIGURE=1
+    if [ -f config.py ]
+    then
+        echo "NOTE: Config file for DTA already exist"
+        read -p "Do you want to override it (y/n)?" choice
+        case "$choice" in 
+          y|Y ) echo "yes"; CONFIGURE=1;;
+          n|N ) echo "no"; CONFIGURE=0;;
+          * ) echo "invalid";;
+        esac
+    fi
+
+    if [ $CONFIGURE == 1 ]
+    then
+        cp config_default.py config.py
+        CONFIG_FILE=$(pwd)/config.py
+        SALT=$(python -c "import os; print os.urandom(8).encode('hex')")
+        PASSPHRASE=$(python -c "import os; print os.urandom(8).encode('hex')")
+
+        CREDENTIALSFILE="$BASE_DIR/credentials.json"
+        BACKUP_FILE="$BASE_DIR/backup_dta.json"
+        rm -f "$BASE_DIR/backup_dta.json"
+
+        sed -i "s/\(%SALT%\)/$SALT/" "$CONFIG_FILE"
+        sed -i "s/\(%PASSPHRASE%\)/$PASSPHRASE/" "$CONFIG_FILE"
+        sed -i "s#\(%CREDENTIALSFILE%\)#$CREDENTIALSFILE#" "$CONFIG_FILE"
+        sed -i "s#\(%BACKUP_FILE%\)#$BACKUP_FILE#" "$CONFIG_FILE"
+    fi
+}
+
+function configure_rps {
+    echo "Configure RPS"
+
+    cd "$BASE_DIR/servers/rps" || exit
+
+    CONFIGURE=1
+    if [ -f config.py ]
+    then
+        echo "NOTE: Config file for RPS already exist"
+        read -p "Do you want to override it (y/n)?" choice
+        case "$choice" in 
+          y|Y ) echo "yes"; CONFIGURE=1;;
+          n|N ) echo "no"; CONFIGURE=0;;
+          * ) echo "invalid";;
+        esac
+    fi
+
+    if [ $CONFIGURE == 1 ]
+    then
+        cp config_default.py config.py
+
+        CONFIG_FILE=$(pwd)/config.py
+        CREDENTIALSFILE="$BASE_DIR/credentials.json"
+
+        sed -i "s#\(%CREDENTIALSFILE%\)#$CREDENTIALSFILE#" "$CONFIG_FILE"
+    fi
+}
+
+function configure_demo {
+    echo "Configure Demo RPA"
+
+    cd "$BASE_DIR/servers/demo" || exit
+
+    CONFIGURE=1
+    if [ -f config.py ]
+    then
+        echo "NOTE: Config file for DEMO RPA already exist"
+        read -p "Do you want to override it (y/n)?" choice
+        case "$choice" in 
+          y|Y ) echo "yes"; CONFIGURE=1;;
+          n|N ) echo "no"; CONFIGURE=0;;
+          * ) echo "invalid";;
+        esac
+    fi
+
+    if [ $CONFIGURE == 1 ]
+    then
+        cp config_default.py config.py
+
+        CONFIG_FILE=$(pwd)/config.py
+        # We need to remove new line, sed does not like it
+        COOKIESECRET=$(python -c "import os; print os.urandom(64).encode('base64').replace(\"\n\", '')")
+
+        sed -i "s#\(%COOKIESECRET%\)#$COOKIESECRET#" "$CONFIG_FILE"
+
+        if [ "$FRONTEND_LOCATION" ]
+        then
+            build_frontend
+
+            # mpin.js can be downloaded or copied/linked from localy build milagro-js-client
+            MPINJSURL="/public/mpin/mpin.js"
+            sed -i "s#\(%MPINJSURL%\)#$MPINJSURL#" "$CONFIG_FILE"
+        else
+            echo $'\n'
+            echo "NOTE: No location for the frontend provided you will need to configure %MPINJSURL% yourself"
+        fi;
+    fi
+}
+
+function run_instructions {
+    echo "
+    For development purposes you might run the services from command line.
+    Open 3 terminals and set the following two environment variables as shown below:
+
+    export PYTHONPATH=<mpin-backend>/lib:/usr/local/lib/python2.7/site-packages
+    export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:/usr/local/lib
+    To run the services, perform the following commands, each in separate terminal:
+
+     > python servers/dta/dta.py
+     > python servers/rps/rps.py
+     > python servers/demo/mpinDemo.py
+    For more automated execution, you might need to write start/stop scripts in /etc/init.d
+    "
+}
+
+function configure_services {
+    echo "Configure the services"
+
+    configure_dta
+
+    configure_rps
+
+    configure_demo
+
+    run_instructions
+}
+
+get_dependencies
+
+configure_services
diff --git a/lib/crypto.py b/lib/crypto.py
index b26ef6e..b3c87e1 100644
--- a/lib/crypto.py
+++ b/lib/crypto.py
@@ -47,7 +47,7 @@
 
     # random number generator
     RNG = mpin.ffi.new('csprng*')
-    mpin.libmpin.CREATE_CSPRNG(RNG, SEED)
+    mpin.libmpin.MPIN_CREATE_CSPRNG(RNG, SEED)
 
     return RNG
 
@@ -129,7 +129,7 @@
     CIPHERTEXT[0].val = CIPHERTEXT_val
     CIPHERTEXT[0].max = len(plaintext)
 
-    mpin.libmpin.AES_GCM_ENCRYPT(AES_KEY, IV, HEADER, PLAINTEXT, CIPHERTEXT, TAG)
+    mpin.libmpin.MPIN_AES_GCM_ENCRYPT(AES_KEY, IV, HEADER, PLAINTEXT, CIPHERTEXT, TAG)
     IV_hex = mpin.toHex(IV)
     CIPHERTEXT_hex = mpin.toHex(CIPHERTEXT)
     TAG_hex = mpin.toHex(TAG)
@@ -181,7 +181,7 @@
     TAG[0].max = mpin.PAS
 
     # Decrypt ciphertext
-    mpin.libmpin.AES_GCM_DECRYPT(AES_KEY, IV, HEADER, CIPHERTEXT, PLAINTEXT, TAG)
+    mpin.libmpin.MPIN_AES_GCM_DECRYPT(AES_KEY, IV, HEADER, CIPHERTEXT, PLAINTEXT, TAG)
 
     return mpin.toHex(TAG), mpin.toHex(PLAINTEXT)