• Home
  • Events
  • About
  • Remote Script Execution with GroovySocketServer

    December 2nd, 2010

    File under: extremely dangerous but definitely fun. Here’s some directions on how to execute any arbitrary Groovy script on a remote server. We’re going to write a one line Groovy script that, when run, will listen to a socket and execute any incoming text as if it were Groovy script and return the result to the client. We’ll do it from the command line and programatically. The client is actually more difficult to write and weighs in at a whooping 5 lines. Let’s get started.

    Running Groovy in Socket/Listen Mode
    First of all, opening up a socket that executes a groovy snippet against incoming text is supported from the command line interface to the “groovy” binary. Opening a listening socket on port 1960 is as easy as:

    This will take any incoming socket data, convert it to a String, and call the reverse() method on it. The variable ‘line’ is the user specified data. “-l” is the signal to create the socket in listen mode, “-p” means the result is printed back to the client, and “-e” marks the script parameter. This is an easy way to set up an ad-hoc socket server. You can test this with the following code from GroovyConsole:

    Executing User Scripts
    I want more. Instead of passing data up to the server I want to pass code. It’s quite easy, again from the command line:

    This is going to parse and execute any incoming data as if it were code. Here is the client script to get the directory listing of the current server side directory:

    Fun stuff. Be sure not to send up ‘rm -rf .’.execute()! What’s up with the “success” message you may ask? For some reason the String “success” has special meaning in the server. If the script you execute results in this string then the socket is closed. Weird is exactly the right work, but I’m sure it served a purpose at the time.

    Doing it Programatically
    Behind the scenes, Groovy is delegating to the groovy.ui.GroovySocketServer object. You can invoke this class from Java or from Groovy.

    The GroovyShell argument is important because that is the ClassLoader that will execute the user script. If you want to include some Jar references or classes then you’re going to have to monkey with that thing.

    And there you have it. We opened a socket, with basically no security, and you can execute any arbitrary code against it. Mission accomplished.

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • email
    • Print
    • Twitter
    • LinkedIn
    • XING
    • Facebook
    • Google Bookmarks