Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to execute unsafe code (disable security manager) in Java?

Please don't post an answer saying "you shouldn't do this." I don't plan to use this in production code, but only for some hacking fun.

In answering this question, I wanted to run some arbitrary unsafe Java code for fun. The code in question involves finding just the leaf nodes of a Java TreeMap.

Running the below code results in

Exception in thread "main" java.lang.SecurityException: Prohibited package name: java.util

According to this question, I can use System.setSecurityManager(null) to get around most of these restrictions. But I can't do this because the error pops up as my class is loaded.

I'm already aware that I can do everything I want to using reflection after disabling the security manager. But that would make the code much uglier. How do the core Java developers write their unit tests, for example, if they can't package things in java.util?

I also tried -Djava.security.manager=... but this causes a JVM initialization error when I set it to null, and I'm not sure what else I can set it to. Any ideas?

package java.util;

import java.util.TreeMap.Entry;

public class TreeMapHax {

    static <K,V> List<Entry<K, V>> getLeafEntries(TreeMap<K, V> map) {      
        Entry<K, V> root = map.getFirstEntry();
        while( root.parent != null ) root = root.parent;

        List<Entry<K,V>> l = new LinkedList<Entry<K,V>>();
        visitInOrderLeaves(root, l);
        return l;
    }

    static <K,V> void visitInOrderLeaves(Entry<K, V> node, List<Entry<K, V>> accum) {       
        if( node.left != null ) visitInOrderLeaves(node.left, accum);       
        if( node.left == null && node.right == null ) accum.add(node);      
        if( node.right != null ) visitInOrderLeaves(node.right, accum);
    }

    public static void main(String[] args) {
        TreeMap<String, Integer> map = new TreeMap<String, Integer>();

        for( int i = 0; i < 10; i++ )
            map.put(Integer.toString(i), i);

        System.out.println(getLeafEntries(map));
    }

}
like image 259
Andrew Mao Avatar asked Mar 22 '13 06:03

Andrew Mao


1 Answers

to simply answer your question, there is no usual way

the classes in java.* are restricted not by security manager, they are restricted by the class loader.

todo what you want, you somehow need to find a way to hack the jvm. or just do as you mentioned, do it with reflection. or just create a copy (source clone) of treemap in your own package.

like image 93
fmt.Println.MKO Avatar answered Oct 17 '22 02:10

fmt.Println.MKO