Wednesday, November 19, 2008

Let Java SSL Trust All Certificates without Violating Security Manager

Java SSL by default does not trust self-signed certificate. Wikibooks:Programming reveals a way to allow connection to secure HTTP server using self-signed certificate. The magic looks like:

// 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(
java.security.cert.X509Certificate[] certs, String authType) {
// do nothing
}

public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
// do nothing
}
}
};

// Install the all-trusting trust manager
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch(GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
}
HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());

However, HttpsURLConnection.setDefaultSSLSocketFactory(...) will throw a SecurityException (a RuntimeException) if a security manager exists and its checkSetFactory method does not allow a socket factory to be specified. The thrown SecurityException looks like

Exception in thread "main" java.security.AccessControlException: access denied (java.lang.RuntimePermission setFactory)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkSetFactory(SecurityManager.java:1612)
at javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(HttpsURLConnection.java:308)
at SecurityManagerTest.main(SecurityManagerTest.java:50)

A workaround to avoid such a SecurityException is as below:

URL url = new URL("https://engage.ac.uk");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.getInputStream();

The trick is to use the instance method setSSLSocketFactory instead of the static method setDefaultSSLSocketFactory. The former does not throw a SecurityException.

Note: need to use conn.getInputStream() instead of url.openStream(), otherwise the customised SocketFactory won't be used.

Of course to allow to connect the secure web site, the following permission should be added in the Java security policy file:

permission java.net.SocketPermission "engage.ac.uk:443", "connect";

15 comments:

andrea chiu said...

There are certain point in our life that we encounter failure but it doesn't mean you will lose hope and give up everything but it only means that every failure there's an exchange and that is new beginning. Well, thank you for sharing your article and keep on posting. Visit my site too for more information.

triciajoy.com

www.triciajoy.com

Silvia Jacinto said...

Life is a battle, if you don't know how to defend yourself then you'll end up being a loser.
So, better take any challenges as your stepping stone to become a better person. Have fun,
explore and make a lot of memories.

n8fan.net

www.n8fan.net

Kanye Co Jamila said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Dot Net Training in Chennai . Nowadays Java has tons of job opportunities on various vertical industry.


or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

William Blitz said...

This is the right weblog for anybody who desires to find out about this topic. You understand a lot its nearly onerous to argue with you (not that I really would need…HaHa). You undoubtedly put a brand new spin on a topic thats been written about for years. Nice stuff, just nice! online casino games

Aliya Manasa said...

Very well written blog and I always love to read blogs like these because they offer very good information to readers with very less amount of words....thanks for sharing your info with us and keep sharing.
python Training in Pune
python Training in Chennai
python Training in Bangalore

ragini ragini said...

Great thoughts you got there, believe I may possibly try just some of it throughout my daily life.
Best Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram

priya said...

Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.
Data Science Training in Indira nagar
Data Science training in marathahalli
Data Science Interview questions and answers
Data Science training in btm layout
Data Science Training in BTM Layout
Data science training in bangalore

Deepali M said...

This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. You have done a great job.

Full Stack Developer Training Online | Full Stack Web Developer Training | Full Stack Developer Certification | Full Stack Developer Course | Full Stack Developer Training

franklinraj said...

Thank you for excellent article.

Please refer below if you are looking for best project center in coimbatore

soft skill training in coimbatore
final year projects in coimbatore
Spoken English Training in coimbatore
final year projects for CSE in coimbatore
final year projects for IT in coimbatore
final year projects for ECE in coimbatore
final year projects for EEE in coimbatore
final year projects for Mechanical in coimbatore
final year projects for Instrumentation in coimbatore

digitalsourabh said...

Graphic designing training in bhopal
Python Coaching in Bhopal
Android Coaching in Bhopal
Machine Learning Course in Bhopal
Digital Marketing Training in Bhopal
IoT Training in Bhopal
Artificial Intelligence Training in Bhopal
SEO Training in Bhopal
Minor Training in Bhopal
Major Training in Bhopal

Creators Seo Master said...

super your blog
andaman tour packages
andaman holiday packages
web development company in chennai
Math word problem solver
laptop service center in chennai
Austin Homes for Sale

Sai Institutions said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us. great doing keep sharing.
cruise ship training and placement in chennai
best visual communication insitute in chennai
Carving classes in Chennai
hotel management institute in chennai
hotel management course in chennai
hotel management College in chennai
Fashion Design Course in Chennai

Priyanka said...

Attend The Python Training in Hyderabad From ExcelR. Practical Python Training Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Hyderabad.
python training in bangalore

Techxinx said...

I am a regular reader of your blog and I find it really informative. for more info contact us
CPCT Coaching in Bhopal
java coaching in bhopal
Autocad classes in bhopal
Catia coaching in bhopal

saketh varma said...

I like viewing web sites which comprehend the price of delivering the excellent useful resource Python classes in pune free of charge. I truly adored reading your posting. Thank you!