Solved

java.net.SocketPermission error trying to access MySQL database from servlet

Posted on 2007-04-05
14
592 Views
Last Modified: 2013-11-24
Apologies for any incorrect terminology I may use. Some of this is quite new to me.

I have a small Java program that connects to a MySQL database and retrieves and displays some data from it. The code runs fine at the command line.

A similar piece of Java code that runs in the context of a servlet gives this error at the point where it starts making the connection to the MySQL database: -

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException
MESSAGE: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:3306 connect,resolve)

STACKTRACE:

java.net.SocketException: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:3306 connect,resolve)
        at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
        at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:277)
        at com.mysql.jdbc.Connection.createNewIO(Connection.java:2668)
        at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
        at java.sql.DriverManager.getConnection(DriverManager.java:525)
        at java.sql.DriverManager.getConnection(DriverManager.java:171)
        at ShowPVersions.doGet(ShowPVersions.java:31)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:243)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
        at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:275)
        at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:161)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)
        at org.apache.catalina.core.ApplicationFilterChain.access$0(ApplicationFilterChain.java:177)
        at org.apache.catalina.core.ApplicationFilterChain$1.run(ApplicationFilterChain.java:156)
        at java.security.AccessController.doPrivileged(Native Method)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:152)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
        at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
        at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
        at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
        at java.lang.Thread.run(Thread.java:595)


** END NESTED EXCEPTION **



The Java code is: -

import java.sql.*;

public class ShowPVersions {
  public static void main(String args[]){
    System.out.println("Looking for P Version Information");
    try {
        Statement stmt;
      ResultSet rs;

      //Register the JDBC driver for MySQL.
      Class.forName("com.mysql.jdbc.Driver");

      String url = "jdbc:mysql://127.0.0.1:3306/ptest";

      Connection con = DriverManager.getConnection(url,"USER", "SECRET");

      //Display URL and connection information
      System.out.println("URL: " + url);
      System.out.println("Connection: " + con);

      //Get a Statement object
      stmt = con.createStatement();

      stmt = con.createStatement(
               ResultSet.TYPE_SCROLL_INSENSITIVE,
                     ResultSet.CONCUR_READ_ONLY);

      //Query the database, storing the result
      // in an object of type ResultSet
      rs = stmt.executeQuery("SELECT * from PVersion");

      System.out.println("Versions: -");
      while(rs.next()){
        String strVer = rs.getString("Version");
        String strTime = rs.getString("InstallTime");
        System.out.println("\t" + strVer + "\t" + strTime);
      }

      con.close();
    }catch( Exception e ) {
      e.printStackTrace();
    }
  }
}



I'm running the following: -

Debian etch
MySQL 5.0
Tomcat 5.5
Sun JRE 5.0
0
Comment
Question by:SimonFisher
14 Comments
 
LVL 10

Expert Comment

by:Jaax
ID: 18857378
In Tomcat/conf, you would find catalina.conf
Add these lines (after modifying to your configurartion values) and restart TomCat

grant codeBase "file:${catalina.home}/webapps/ExamplApp/WEB-INF/lib/MySQLDriverJar.jar!/-" {
     permission java.net.SocketPermission "<The DB Server IP Address>", "connect";
};

Hope it helps
0
 

Author Comment

by:SimonFisher
ID: 18857917
The MySQL driver/jar file is symbolically linked so it appears at various places under /usr/share/tomcat and /usr/share/java. It's not in my application area.

My MySQL database server is on the same machine as Tomcat.

It appears that under Debian, you don't edit /var/lib/tomcat5.5/conf/catalina.policy directly, but make changes to files in /etc/tomcat5.5/policy.d/ which then get merged to form the catalina.policy file. So, I've added this to /etc/tomcat5.5/policy.d/50user.policy

I can confitm that after restarting tomcat, the catalina.policy file does contain the required addition: -

grant codeBase "file:/usr/share/tomcat5.5/common/lib/mysql.jar!/-" {
     permission java.net.SocketPermission "127.0.0.1", "connect";
};

I still get the error.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18860620
>> "file:/usr/share/tomcat5.5/common/lib/mysql.jar!/"

Try grant codeBase "file:/usr/share/tomcat5.5/common/lib/mysql.jar" {
permission java.net.SocketPermission "*", "connect";
};
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:SimonFisher
ID: 18903952
Still getting the same error message.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 18928428
Try giving all files under lib the same permission
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 19069752
What was the result of: >> Try giving all files under lib the same permission
0
 

Author Comment

by:SimonFisher
ID: 19070671
The solution I used was to modify the file /etc/tomcat5.5/policy.d/04webapps.policy such that within a section starting: -

    grant {

I added: -

    permission java.net.SocketPermission "127.0.0.1:3306", "connect,resolve";
    permission java.util.PropertyPermission "file.encoding", "read";

I found this solution from elsewhere.
0
 

Author Comment

by:SimonFisher
ID: 19070689
mayankeagle's suggestion "Try giving all files under lib the same permission" wasn't detailed enough for me to follow. I was away on holiday from April 13th (shortly after I posted "Still getting the same error message." and found the solution on my return, after seeing your suggestion but before I had asked you to elaborate.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 19072642
All files under lib the same permission means you need to repeat the permission you are giving to one file to all other files in the directory. Since you have:

Try grant codeBase "file:/usr/share/tomcat5.5/common/lib/mysql.jar" {
permission java.net.SocketPermission "*", "connect";
};

Suppose you also have another abc.jar and xyz.jar in the same lib directory, then also give:

Try grant codeBase "file:/usr/share/tomcat5.5/common/lib/abc.jar" {
permission java.net.SocketPermission "*", "connect";
};

Try grant codeBase "file:/usr/share/tomcat5.5/common/lib/xyz.jar" {
permission java.net.SocketPermission "*", "connect";
};

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 19072648
you can reply back and ask for clarification if you fail to understand any of the comments because we come here only when we find free time from our work, so sometimes our replies might not be very elaborate.
0
 

Author Comment

by:SimonFisher
ID: 19072803
I would have asked for elaboration __IF__ I hadn't already found the solution elsewhere.

As it is, I do not feel that any of the comments or suggestions made contributed to me finding the solution. Do you think otherwise?
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 19073992
Well, I wouldn't know myself as to whether my comments helped or not and whether you tried them or not, or whether you're looking for a solution of your own or not, if you don't reply to my comment to let me know.
0
 
LVL 1

Accepted Solution

by:
Vee_Mod earned 0 total points
ID: 19080909
Closed, 500 points refunded.
Vee_Mod
Community Support Moderator
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
java 8 lambda expresssions exception handling 3 89
more than one jdk and one jre 1 41
difference of if loops 23 49
MySqlDump not dumping triggers 1 31
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question