Wednesday, March 15, 2017

Disable Certificate Validation in Java SSL Connections

By design when we open an SSL connection in Java (e.g. through java.net.URL.openConnection(“https://….”)) the JSSE implementation of the SSL protocol performs few validations to ensure the requested host is not fake. This involves validation of the server’s X.509 certificate with the PKIX algorithm and checking the host name agains the certificate subject. If the SSL certificate is not validates as trusted or does not match the target host, an HTTPS and other SSL encrypted connection cannot be established and all attempts will result in SSLHandshakeException or IOException.

Example of HTTPS Connection in Java that will Fail Due to Certificate Validation Failure

Consider we are trying to download a resource from HTTPS server:
URL url = new URL("https://www.nakov.com:2083/");
URLConnection con = url.openConnection();
Reader reader = new InputStreamReader(con.getInputStream());
while (true) {
    int ch = reader.read();
    if (ch==-1) {
        break;
    }
    System.out.print((char)ch);
}

If the server uses self-signed X.509 certificate, we will get SSLHandshakeException the following exception during the SSL handshaking:

Exception in thread "main" <strong>java.io.IOException: HTTPS hostname wrong: should be <www.nakov.com></strong> at sun.net.www.protocol.https.HttpsClient.checkURLSpoofing(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)

How to Turn Off Certificate Validation in Java HTTPS Connections


Avoiding these exceptions is possible by switching off the certificate validation and host verification for SSL for the current Java virtual machine. This can be done by replacing the default SSL trust manager and the default SSL hostname verifier:

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
 
public class Example {
    public static void main(String[] args) throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
        };
 
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
 
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
 
        URL url = new URL("https://www.nakov.com:2083/");
        URLConnection con = url.openConnection();
        Reader reader = new InputStreamReader(con.getInputStream());
        while (true) {
            int ch = reader.read();
            if (ch==-1) {
                break;
            }
            System.out.print((char)ch);
        }
    }
}

Monday, November 28, 2016

change the cache dir of netbeans 8.0.2

if you are looking for changing the default cache location of your netbeans 8.0.2 (this is the version i have, this might work for other versions as well) follow the below steps:
1. Make sure netbean is closed
2. Locate the netbeans.conf file (mostly it will be there @C:\Program Files (x86)\NetBeans 8.0.2\etc)
3. Open the notepad as admin (Notepad++ was giving some weird error, dono what)
4. change the location under the property : netbeans_default_cachedir  from "${DEFAULT_CHACHEDIR_ROOT}/8.0.2" to something like "D:/software/netbeanse/cache/8.0.2".

Hope this helped you, please leave your comment if it did. Thank you!

Monday, November 14, 2016

AngularJS Pagination with Filtering example

If you are looking for an working example on Pagination with Filtering using AngularJS, copy paste the following code in note pad and save as Pagination.html:

Additional notes: this example can filter more than one field.
Do let me know if it was helpful by commenting at the bottom! Thanks.

<html>
<head>
    <title>AngularJS Pagination Sample</title>
   <script src="./lib/angular.min.js"></script>
   <!--<script src="./lib/angular-resource.js"></script>-->
    <script src="./lib/ui-bootstrap-tpls-0.11.0.js"></script>
    <link href="./styles/bootstrap.min.css" rel="stylesheet" />
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
   <script src="http://code.angularjs.org/1.4.8/angular.js"></script>
   <script src="http://code.angularjs.org/1.4.8/angular-resource.js"></script>
   <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>  -->
    <meta charset="utf-8" />

    <script>
        (function () {
            var app = angular.module('paging-app', ['ui.bootstrap']);

            app.controller('MainCtrl', function ($scope, filterFilter) {
                $scope.list = [];
$scope.userList = [{"status":null,"role":"role1","permission":null,"username":"user1","password":null,"email":"user1@domain.com","samlresponse":null},{"status":null,"role":"role1","permission":null,"username":"user2","password":null,"email":"user2@domain.net","samlresponse":null},{"status":null,"role":"role1","permission":null,"username":"user3","password":null,"email":"user3@domain.com","samlresponse":null}];
                $scope.pageSize = 5;

                $scope.init = function () {
                    for (var i = 0; i < $scope.userList.length; i++) {
                        $scope.list.push({username:$scope.userList[i].username, email:$scope.userList[i].email});
                    }
                };
var array = [];
                $scope.$watch('search.name', function (term) {
                    var obj = { username: term }
var obj2 = { email: term}
                    $scope.filterList = filterFilter($scope.list, obj);
array = filterFilter($scope.list, obj2);
for (var i = 0; i < array.length; i++) {
if($scope.filterList.indexOf(array[i]) == -1){
$scope.filterList.push(array[i]);
}
}

                    $scope.currentPage = 1;
                });
            })

            .filter('start', function () {
                return function (input, start) {
                    if (!input || !input.length) { return; }

                    start = +start;
                    return input.slice(start);
                };
            });

        }());
    </script>
</head>
<body ng-app="paging-app">
    <br />
    <div class="container" ng-controller="MainCtrl" ng-init="init()">
        <div>
            <input type="text" class="form-control" placeholder="Search" ng-model="search.name" />
            <br />
        </div>
        <div>
            <div ng-repeat="item in filterList | start: (currentPage - 1) * pageSize | limitTo: pageSize"
                 class="alert alert-success col-md-12">
                <span ng-bind="item.username"></span>
<span ng-bind="item.email"></span>
            </div>
            <pagination total-items="filterList.length" items-per-page="pageSize" ng-model="currentPage" max-size="5" class="pagination-sm"></pagination>
        </div>
    </div>
</body>
</html>

Wednesday, June 18, 2014

How to reset the key

$ ssh-keygen -p
Enter file in which the key is (/Users/tekkub/.ssh/id_rsa):
Key has comment '/Users/tekkub/.ssh/id_rsa'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.

Friday, March 7, 2014

Microsoft | Word | 2010 - normal.dotm error while opening Word doc 2010

1. Locate the normal.dotm file in the user profile path: %userprofile%\AppData\Roaming\Microsoft\Templates\Normal.dotm

2. Rename the file name Normal.dotm as Normal_old.dotm

3. Now try to open the document again, this should fix the issue.

Thursday, October 3, 2013

Deploy war in tomcat (run in eclipse)

I am using apache 7. When started in command prompt everything works as expected but if I start same from eclipse then I was not able to access it and find the

settings.

Looks like eclipse uses by default 'Use workspace metadata' and deploy path to 'wtpwebapps' in server settings. Follow the below steps to change these and you will be

able access localhost:8080 when you start server in eclipse.

1. In eclipse servers tab at bottom, right click, where you can see start, stop etc, and select properties.
2. In properties window, select general, then select Switch Location.
3. Now you can see Tomcat v7.0 Server at localhost, open it.
4a. If there are any modules deployed, temporarily remove them and close out tab to save this change, otherwise go directly to step 4c below.
4b. If you removed any modules, restart server after step 4a and proceed to step 4c.
4c. In server location, select radio button 'Use tomcat installation', and select 'webapps' in deploy path.
Save and start server in eclipse. Now you will be able to access the server.

5. You need to setup the admin user name /password in conf\tomcat-users.xml as below:

Add the below code in the xml:
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>

  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
<role rolename="manager"/>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>

  <role rolename="admin"/>
  <user username="admin" password="admin" roles="manager,manager-gui"/>

6. Restart the server from eclipse.
7. access the tomcat using localhost:8080/manager -> enter the user : admin and password : admin.
8. Deploy the war file
9.  access it using localhost:8080/project_name

If the above procedure does not work, change the port number as below:
- double click on the tomcat 7.0... server in the eclipse to open overview screen
- change the default port (HTTP/1.1) for example 8080 to 8001 and do change other ports for AJP and tomcat admin as well.
- then follow the steps 1 to 9.