Securing J2EE Services

Embed Size (px)

Citation preview

  • 8/14/2019 Securing J2EE Services

    1/27

    Copyright 2006 - Aspect SecurityCopyright 2006 - Aspect Security

    Securing J2EE Applications Coding Patternsfor Secure Connections to Services

    Jeff Williams

    Aspect Security [email protected] 9, 2006

  • 8/14/2019 Securing J2EE Services

    2/27

    )

    Copyright 2006 - Aspect Security2

    How Developers See Services

    Service(server-side)

    Application(client-side)

  • 8/14/2019 Securing J2EE Services

    3/27

    )

    Copyright 2006 - Aspect Security3

    How Attackers See Services

    SniffingInterceptionTampering

    Attacks on Client Attacks on Server

    Chained Attacks onOther Services or

    Other Clients

    Attacks onLocal Hostsand Networks

    Service(server-side)

    Application(client-side)

    intranet

  • 8/14/2019 Securing J2EE Services

    4/27

    )

    Copyright 2006 - Aspect Security4

    Imagine the Future

    Services mean trust relationships

    ) Who are you?

    ) What do you need?

    ) What will you provide?

    ) Will you protect my data?

    ) Can I trust what you send me?

    ) Will you attack me?

    ) Can I trust your code?

    ) Can I trust your other partners?) If something bad happens, who pays?

  • 8/14/2019 Securing J2EE Services

    5/27

    )

    Copyright 2006 - Aspect Security5

    Accessing Services Securely

    Credentials

    Credentials

    Access Control

    Input/Output Validation

    Error Handling

    Logging

    Encryption

    Availability

    Concurrency

    Authentication

    Error Handling

    Logging

    Encryption

    Availability

    Concurrency SecureCo

    mmun

    ications

    Note: the application is a client of the service, but might be a server application itself

    Service(server-side)

    Application(client-side)

  • 8/14/2019 Securing J2EE Services

    6/27

    )

    Copyright 2006 - Aspect Security6

    What Does Secure Mean for a Service?

    Client-Side (App)

    Secure Communications

    Authentication and SessionsAccess Control

    Validate & Encode Request

    Validate & Encode Response

    Error HandlingLogging & Intrusion Detection

    Encryption

    Availability

    Concurrency

    Server-Side (Service)

    Secure Communications

    Authentication and SessionsAccess Control

    Validate & Encode Request

    Validate & Encode Response

    Error HandlingLogging & Intrusion Detection

    Encryption

    Availability

    Concurrency

    Services are bidirectional attack vectors

  • 8/14/2019 Securing J2EE Services

    7/27

    )

    Copyright 2006 - Aspect Security7

    Techniques for Verifying Service Use

    Vulnerability Scanning

    Static Analysis

    Penetration Testing

    Code Review

  • 8/14/2019 Securing J2EE Services

    8/27

    )

    Copyright 2006 - Aspect Security8

    Using Eclipse for Code Review

    Syntax highlighting

    Code browsing

    Static Analysis

    Powerful Search Tools

    Security Help

  • 8/14/2019 Securing J2EE Services

    9/27

    )

    Copyright 2006 - Aspect Security9

    Using WebScarab for Penetration Testing

    Choose the WSDL

    Choose the operation to execute

    Add the parameter value

    Execute the request

    View the response

    Choose WebServices feature

    Use the WebScarab summaryfeature to view the HTTP traffic thatWebScarab created.

  • 8/14/2019 Securing J2EE Services

    10/27

    )

    Copyright 2006 - Aspect Security10

    Finding Services

    Search for them!

    ) Start with the architecture diagram

    ) Can be automated with tools

    Client Examples

    ) Sockets search for use of java.net.*

    ) HTTP search for use of URI, URL

    ) Operating System search for Runtime.exec()

    ) Web Services search for AXIS

    Server Examples

    ) Database search for use of JDBC) Servlet search for use of ServletRequest

    ) Custom services search for use of libraries

  • 8/14/2019 Securing J2EE Services

    11/27

    )

    Copyright 2006 - Aspect Security11

    Architecture for Accessing Services

    Create a "Service Access" Component

    ) Isolates details of using the service

    ) Provides a single implementation of security features

    ) May be a faade on top of a more powerful library

    Credentials

    Access Control

    Input/Output Validation

    Authentication

    Error Handling

    Logging

    Encryption

    AvailabilityConcurrency

    Application

    Service AccessComponent

    Simple Limited API

    Service

  • 8/14/2019 Securing J2EE Services

    12/27

    )

    Copyright 2006 - Aspect Security12

    Secure Service - Client Pattern

    // pseudo-code template for invoking a service with security...

    if ( !isAuthorized ) throw AuthorizationExceptionif ( !isValidInput ) throw ValidationExceptiontry {

    credentials = encryptedProperties.getCredentials()service = open( credentials ) // SSL? Least privilege?encode( parameters )results = service.invoke( parameters )validate( results )log success

    } catch Exception e {

    log errorthrow proper exception

    } finally {close connection

    }encode( results )do something with results

    ...

    Secure CommunicationsAuthentication and SessionsAccess ControlValidate & Encode RequestValidate & Encode Response

    Error HandlingLogging & Intrusion DetectionEncryptionAvailabilityConcurrency

  • 8/14/2019 Securing J2EE Services

    13/27

    )

    Copyright 2006 - Aspect Security13

    Client Example: LDAP Using JNDI

    // Set up environment for creating initial contextHashtable env = new Hashtable(11);env.put(Context.INITIAL_CONTEXT_FACTORY,

    "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL,"ldaps://localhost:636/o=jndi");

    // Authenticateenv.put(Context.SECURITY_AUTHENTICATION, "simple");env.put(Context.SECURITY_PRINCIPAL, "cn=user, ou=group, o=jndi");env.put(Context.SECURITY_CREDENTIALS, "password");

    DirContext ctx = null;try {

    ctx = new InitialDirContext(env);String group = request.getParameter( "group" );System.out.println(ctx.lookup( "ou=" + group ));

    } catch (NamingException e) {e.printStackTrace();} finally {

    ctx.close();}

  • 8/14/2019 Securing J2EE Services

    14/27

    )

    Copyright 2006 - Aspect Security14

    Client Example: TCP/IP Socket

    try {

    Socket t = new Socket(args[0], 7);

    DataInputStream dis =

    new DataInputStream(t.getInputStream());

    PrintStream ps = new PrintStream(t.getOutputStream());

    ps.println("Hello");

    String str = dis.readLine();

    if (str.equals("Hello"))

    System.out.println("Alive!");

    elseSystem.out.println("Dead or echo port not responding");

    t.close();

    }

    catch (IOException e) {

    e.printStackTrace();}

  • 8/14/2019 Securing J2EE Services

    15/27

    )

    Copyright 2006 - Aspect Security15

    Client Example: Web Service

    public class TestClient {public static void main(String [] args) {try {String endpoint = "https://localhost:8443/axis/Service.jws";

    System.setProperty("javax.net.ssl.trustStore","/etc/security/.keystore");

    Service service = new Service();Call call = (Call)service.createCall();call.setTargetEndpointAddress( new java.net.URL(endpoint) );call.setOperationName( new QName("serviceName") );

    call.setUsername("user");call.setPassword("password");call.setTimeout( 20000 ); // timeout after 20 seconds

    String ret = (String) call.invoke( new Object[] { args[0] } );System.out.println("Response: " + response );

    } catch (Exception e) {System.err.println(e.toString());}}

  • 8/14/2019 Securing J2EE Services

    16/27

    )

    Copyright 2006 - Aspect Security16

    Client Example: E-mail

    public void sendEmail( HttpServletRequest request ){

    String to = request.getParameter( "to" );String from = request.getParameter( "from" );String text = request.getParameter( "msg" );Properties props = new Properties();

    props.setProperty("mail.transport.protocol", "smtp");props.setProperty("mail.host", "mymail.server.org");props.setProperty("mail.user", "emailuser");props.setProperty("mail.password", "password");Session mailSession = Session.getDefaultInstance(props, null);Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);message.setContent( text, "text/plain");message.addRecipient(Message.RecipientType.TO,

    new InternetAddress( to ));msg.setFrom(new InternetAddress( from ));msg.setSubject( "Check out this cool site" );

    transport.connect();transport.sendMessage(message,

    message.getRecipients(Message.RecipientType.TO));transport.close();

    }

  • 8/14/2019 Securing J2EE Services

    17/27

    )

    Copyright 2006 - Aspect Security17

    Client Example: Google

    StringBuffer results = new StringBuffer();try {

    GoogleSearch gs = new GoogleSearch();gs.setKey(cd3H5SNQFHLjlSGI0vKhxFYUKKrx/M4g");

    gs.setQueryString(QUERY_FROM_PARAM);gs.setMaxResults(10);GoogleSearchResult sr = gs.doSearch();GoogleSearchResultElement[] results = sr.getResultElements();

    for (int index = 0; index < results.length; index++) {String title = results[index].getTitle();

    String url = results[index].getURL();String summary = results[index].getSnippet();results.append(title + ":" +

    summary + ":" + url + "\n" );}

    } catch (Exception e) {

    e.printStackTrace();}return results;

  • 8/14/2019 Securing J2EE Services

    18/27

    )

    Copyright 2006 - Aspect Security18

    Secure Service - Server Pattern

    // pseudo-code template for implementing a service with security...

    hash = hash( password )if ( !isAuthenticated( username, hash ) ) throw

    AuthenticationExceptionif ( !isAuthorized ) throw AuthorizationException

    if ( !isValidInput ) throw ValidationExceptiontry {

    encode( parameters )results = do something with parametersvalidate( results )log success

    } catch Exception e {log errorthrow proper exception

    } finally {close connection

    }encode( results )

    do something with results...

    Secure CommunicationsAuthentication and SessionsAccess ControlValidate & Encode RequestValidate & Encode ResponseError HandlingLogging & Intrusion DetectionEncryptionAvailabilityConcurrency

  • 8/14/2019 Securing J2EE Services

    19/27

    )

    Copyright 2006 - Aspect Security19

    Server Example - Web Service

    package server;import javax.jws.WebService;

    @WebServicepublic class HelloImpl {

    public String sayHello(String name) {return "Hello, " + name + "!";

    }}

    From the tutorialTake another look at the steps that we went through, and notice howlittle code we wrote to expose our original code as a Web service. Thesetools are only going to get better; at some point we will just think, "Iwant this as a Web service," and it will happen.

  • 8/14/2019 Securing J2EE Services

    20/27

    )

    Copyright 2006 - Aspect Security20

    Web Service Attack Names

    Coercive Parsing

    ) Inject malicious content into XML

    ) Solution: Validate before parsing

    XPath/XQuery Injection

    ) Tamper with query changing meaning

    ) Solution: Validate anything used inquery

    Recursive Payload

    ) Recursive references create DOSattack

    ) Solution: Validate for recursion

    External Entity Attack

    ) Use untrustworthy sources of data

    ) Solution: Use well known URIs Schema Poisoning

    ) Alter processing information

    ) Solution: Use only trusted schemas

    XML Parameter Tampering

    ) Submit malicious scripts or data

    ) Solution: Validate request carefully

    Oversized Payload

    ) Oversized files create DOS attack

    ) Solution: Validate and enforce sizelimits

    SOAP Fault

    ) Return full stack trace to attacker) Solution: Generate appropriate errors

    WSDL Scanning

    ) Scan and invoke everything in theWSDL

    ) Solution: Authenticate and authorize XML Denial of Service

    ) Overwhelm a web service withrequests

    ) Solution: Authenticate and set quotas

  • 8/14/2019 Securing J2EE Services

    21/27

    )

    Copyright 2006 - Aspect Security21

    Example XML Attacks

    Example: Recursive Entity Reference

    ]>

    &a;

    Example: Code Injection) In PHP, an attacker can provide an XML file that uses single quotes to

    escape into the eval() call, and execute PHP code on the target server

    Example: External Entity Attack

    ) Internet Explorer does not properly check to make sure that the XML datasource is not redirected

    ) See http://www.microsoft.com/technet/security/bulletin/MS05-025.mspx

  • 8/14/2019 Securing J2EE Services

    22/27

    )

    Copyright 2006 - Aspect Security22

    Web Services - Validation Paradox

    You must parse before validating

    ) Examine at each element and attribute

    )Validate using a set of validation rules or schema

    You must validate before parsing

    ) Many XML attacks attempt to break the parser

    )Validate before parsing

    Solution

    ) Ideal: Integrate security validation into parsers

    ) Current: Do your own validation (size, recursion, attacks)before feeding documents into the parser

  • 8/14/2019 Securing J2EE Services

    23/27

    )

    Copyright 2006 - Aspect Security23

    Web Services - SOAP Faults

    Same issues as web application

    ) Handle all errors

    ) Dont expose internals

    ) Dont provide other information useful to an attacker

    SOAP Fault

    ) Simple XML based description of an error

    ) WebSphere generates a Java exception and serializes into a SOAP fault

    soap:Serverfull stack trace

  • 8/14/2019 Securing J2EE Services

    24/27

    )

    Copyright 2006 - Aspect Security24

    WebGoat WSDL Scanning

  • 8/14/2019 Securing J2EE Services

    25/27

    )

    Copyright 2006 - Aspect Security25

    WebGoat Web Service SQL Injection

  • 8/14/2019 Securing J2EE Services

    26/27

    )

    Copyright 2006 - Aspect Security26

    Security in a Service Oriented World

    Services will create massive interconnected trust web

    ) Most services are security disasters

    ) Far worse than web applications

    Securing services is possible

    ) Takes some thought and planning

    Action plan the time to address this is NOW

    ) Before you have hundreds of insecure services to deal with

    ) Find out whether this is really a problem in your organization

    ) Start a secure services initiative Standards and guidelines Tools and training Process improvements

  • 8/14/2019 Securing J2EE Services

    27/27

    )

    Copyright 2006 - Aspect Security27

    Q U E S T I O N SQ U E S T I O N S

    A N S W E R SA N S W E R S

    Q&A