SlideShare a Scribd company logo
Cracking Java pseudorandom
sequences
Mikhail Egorov
Sergey Soldatov
Why is this important?
• Even useless for crypto often used for other “random” sequences:
• Session ID
• Account passwords
• CAPTCHA
• etc.
• In poor applications can be used for cryptographic keys generation
Why Java?
• I am Java programmer 
• Used in many applications
• Easy to analyze (~decompile)
• Thought to be secure programming language
Known previous analysis
TOO simple about PRNG security
When problems with PRNG security arises:
1. PRNG state is small, we can just brute force all combinations.
2. We can make some assumptions about PRNG state by examining
output from PRNG. So we can reduce brute force space.
3. PRNG is poorly seeded and having output from PRNG we can easily
brute force its state.
Linear congruential generator (In a nutshell)
“Statei” – internal statei:
Statei+1 = Statei × A + Ci+1:
Case 1: “Modular”
(take from bottom)
Si+1
Si+1= Statei+1 mod limit
Si+1
Si+1= (Statei+1 × limit) >> k
k bit
Case 2: “Multiplicative”
(take from top)
java.util.Random:
N = 48
A = 0x5deece66dL = 25 214 903 917
C = 11
N bit
“Seed” == State0
java.util.Random’s nextInt()
32 bit 16 bit
{state0} S0 {state1} S1 {statei} … {staten} Sn
16
S0
exhaustive
search
For each state of this form we check if it
returns our sequence – this takes less than
second
java.util.Random’s nextLong()
32 bit 16 bit
{state0, state1} S0 {state2, state3} S1 {statei, statei+1} … {state2n, state2n+1} Sn
16
S0
exhaustive
search
For each state of this form we check if it
returns our sequence – this takes less than
second
32 bit 16 bit
16 bit
S0
low32S0
high32
java.util.Random’s nextInt(limit), limit is even
H ~ 31 bit L ~ 17 bit
{state0} S0 {state1} S1 {statei} … {staten} Sn
17
S0
S0 % 2P 1) search for L
p + 17 bit
p bit
known L
S0 = H % limit
2) search for H = S0 + J*limit ~ 31 bit
p: limit = n×2P
SubLCG, generates Si % 2P
Search for L (1) and then search for H (2) take
less than 2 seconds
L1
java.util.Random’s nextInt(limit), limit is 2P
H0 ~ 31 bit L0 ~ 17 bit
{state0} S0 {state1} S1 {statei} … {staten} Sn
17
S0
~234,55
H1
S1
Hn Ln
Sn
p bit
java.util.Random’s nextInt(limit), limit is 2P
We search state in the form X = S0 × 248 - p + t mod 248
We have sequence S0 S1 S2 … Sn
Iterate through all t values (248 - p )
Does PRNG.forceSeed(X) produces S1 S2 … Sn ?
Simple Brute Force:
java.util.Random’s nextInt(limit), limit is 2P
limit = 1024 = 210
x1 x2
x2 = x1 mod limit
x2 = x1 + 1 mod limit
213-p < c < 214-p
~ 2 13.44644-p
java.util.Random’s nextInt(limit), limit is 2P
× We can skip (limit -1) × c values that do not produce S1
× Complexity is O(2 48 - 2·p) (~ 2 36 for limit = 64)
instead O(2 48 - 1·p) (~ 2 42 for limit = 64)
L1
java.util.Random’s nextInt(limit), limit is odd
H0 ~ 31 bit L0 ~ 17 bit
{state0} S0 {state1} S1 {statei} … {staten} Sn
17
S0
H1
Hn Ln
S1
Sn
java.util.Random’s nextInt(limit), limit is odd
We search state in form X = (217 × high) + low mod 248
We search high in form high = S0 + j × limit mod 231
Iterate through all high values with step limit (i.e. high += limit)
Iterate through all low values with step 1 (i.e. low += 1)
Does PRNG.forceSeed(X) produces S1 S2 … Sn ?
We have sequence S0 S1 S2 …Sn
Simple Brute Force:
java.util.Random’s nextInt(limit), limit is odd
limit = 73
d = 15 [d depends on limit]
217/d=8738
x2 = x1 mod limit
x2 = x1 – 1 mod limit
x2 = x1 – p mod limit
x2 = x1 – (p + 1) mod limit
x2
x1
where p = 231 mod limit
p = 16 period = 744
java.util.Random’s nextInt(limit), limit is odd
d = min i : (0x5deece66d × i) >> 17 = limit – 1 mod limit
// This is table width
period = 231 / ( (0x5deece66d × d) >> 17 )
// Decrease by p or p+1 happens periodically
19 19 3 2 2 2 2 1 1 1
java.util.Random’s nextInt(limit), limit is odd
Decrease by p=16
63 63 63 46 46 46 46 45 45 45
Decrease by p+1=17
……….... ………....30 29 29 29 29 28 28 ..…....
Decrease by 1 Stay the same
217 / d = 8738
× For each high we pre-compute low values where decrease by p or p+1 happens
There are 217 / (d × period) such low values!
× We skip low values that do not produce S1
In a column we have to check 217 / (d × limit) low values, not all 217 / d
× Complexity is O(248 / period)
× Instead O(248 / limit) better if period > limit
java.util.Random seeding
×In JDK
×System.nanoTime() – machine uptime in nanoseconds (10-9)
×In GNU Classpath
×System.currentTimeMillis() – time in milliseconds (10-3) since epoch
Tool: javacg
• Multi-threaded java.util.Random cracker
• Written in C++11
• Can be built for Linux/Unix and Windows
(tested in MSVS2013 and GCC 4.8.2)
• Available on github: https://github.com/votadlos/JavaCG.git
• Open source, absolutely free to use and modify 
Tool: javacg, numbers generation
• javacg -g [40] -l 88 [-s 22..2], - generate 40 (20 by default) numbers modulo 88 with
initial seed 22..2 (smth made of time by default).
• If -l 0 specified will generate as .nextInt() method
• If -l is omitted will work as .nextLong()
Tool: javacg, passwords generation
• Generate passwords: javacg -g [40] [-b 41] -l 88 -p
[18] [-s 22..2] [-a a.txt], - generate 40 passwords
with length 18 (15 by default) using alphabet a.txt (88
different simbols by default), initial seed – 22..2.
• If -b 41 specified – wind generator backward and
generate 41 passwords before specified seed
22..2.
Tool: javacg, crack options
• Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo
88 and return internal state after the last number from input.
• If min internal state 22..2 or max 44..4 or both are known they can be specified.
In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth
strategy)/-ds (depth strategy) options.
Tool: javacg, -ds-bs ‘advanced’ mode
• Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo
88 and return internal state after the last number from input.
• If min internal state 22..2 or max 44..4 or both are known they can be specified.
In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth
strategy)/-ds (depth strategy) options.
Tool: javacg, -ds-bs ‘advanced’ mode
• Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo
88 and return internal state after the last number from input.
• If min internal state 22..2 or max 44..4 or both are known they can be specified.
In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth
strategy)/-ds (depth strategy) options.
Tool: javacg, crack options (-sin, -sax)
• Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo
88 and return internal state after the last number from input.
• If min internal state 22..2 or max 44..4 or both are known they can be specified.
In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth
strategy)/-ds (depth strategy) options.
Tool: javacg, crack options (-l 0, -l -1)
• –l 0 perform .nextInt() case
• –l -1 (or no –l specified) perform .nextLong() case.
Tool: javacg, crack options (-l 0, -l -1)
• –l 0 perform .nextInt() case
• –l -1 (or no –l specified) perform .nextLong() case.
Tool: javacg, crack options (-l 0, -l -1)
• –l 0 perform .nextInt() case
• –l -1 (or no –l specified) perform .nextLong() case.
Tool: javacg, crack option -st
• Initial seed is milliseconds since epoch (GNU Class Path)
Tool: javacg, crack option –upt [–su]
• Initial seed is host uptime in nanoseconds (Random’s default constructor)
• –upt option takes uptime guess in milliseconds, combines diapason in
nanoseconds (as it’s in –sin and –sax options) and simple bruteforse it.
• –su – optional maximum seedUniquifier
increment, 1000 by default.
Tool: javacg, performance options
• -t 212 – perform brute with 212 threads (C++11 native threads are used).
Default – 128.
• -c 543534 – each thread will take 543534 states to check (‘cycles per thread’).
Default – 9999.
• - ms 12 – will build search matrix with 12 rows. Deault – half of length of input
sequence.
• -norm. During brute forcing we start from the max state (‘from the top’), if it’s
known that sought state is in the middle - use -norm option.
S0 S1 S2 S3 S4 S5 S6 S7
S0 S1 S2 S3 S4
S1 S2 S3 S4 S5
S2 S3 S4 S5 S6
S3 S4 S5 S6 S7
Input sequence Search matrix
Tool: javacg, threads
S0 S1 S2 S3 S4
S1 S2 S3 S4 S5
S2 S3 S4 S5 S6
S3 S4 S5 S6 S7
Generator internal state space
MAX MIN
Threadsforsearch
matrixrows
Threads for internal
states
-t - total number of
threads
Tool: javacg, threads with -norm opt.
S0 S1 S2 S3 S4
S1 S2 S3 S4 S5
S2 S3 S4 S5 S6
S3 S4 S5 S6 S7
Generator internal state space
MAX MIN
Threadsforsearch
matrixrows
Threads for internal
states
-t - total number of
threads
Suppose ‘normal’ distribution
Are you sure
v7n8Q=)71nw;@hE
is secure enough?
MyPasswords
http://sourceforge.net/projects/mypasswords7/ ~18 855 downloads ~4 542 downloads/last year
MyPasswords
http://sourceforge.net/projects/mypasswords7/ ~18 855 downloads ~4 542 downloads/last year
Mass Password Generator
http://sourceforge.net/project/javapwordgen/ ~3 825 downloads ~ 12 downloads/last year
Mass Password Generator
http://sourceforge.net/project/javapwordgen/ ~3 825 downloads ~ 12 downloads/last year
PasswordGenerator
http://sourceforge.net/p/java-pwgen/ ~2 195 downloads ~829 downloads/last year
PasswordGenerator
http://sourceforge.net/p/java-pwgen/ ~2 195 downloads ~829 downloads/last year
Java Password Generator
http://sourceforge.net/projects/javapasswordgen/ ~718 downloads ~145 downloads/last year
Java Password Generator
http://sourceforge.net/projects/javapasswordgen/ ~718 downloads ~145 downloads/last year
Safe Password Generator
http://sourceforge.net/project/safepasswordgenerator/ ~19 downloads ~19 downloads/last year
Safe Password Generator
http://sourceforge.net/project/safepasswordgenerator/ ~19 downloads ~19 downloads/last year
user
l33t Hax0r
IDM generates different
‘random’ local admin passwords
and sets them over all managed
endpoints
IDM
Web-interface
“Show me password
for workstation”
u-%=X_}6~&Eq+4n{gO
m;f9qHU){+6Y[+j$R8
[D7E?Og]Gz>nL5eVRD
df=m+]6l0pFSFbXT_=
Demo #1: “IdM”
Given:
Red password
Alphabet
Number of servers
Find:
[All] green passwords
Take known
df=m+]6l0pFSFbXT_=
Brute internal state
(seed)
Wind generator forward
Wind generator backward
Generate possible passwords
Brute passwords, using
generated passwords as
dictionary
×Jenkins – is open source continuous integration (CI) server, CloudBees
makes commercial support for Jenkins
×Hudson – is open source continuous integration (CI) server under
Eclipse Foundation
×Winstone – is small and fast servlet container (Servlet 2.5)
Other apps with java.util.Random inside
Session Id generation in Jenkins (Winstone)
Winstone_ Client IP Server Port_ _ Gen. time in ms PRNG.nextLong()MD5:
PRNG initialized by time in ms at startup: we need
time in ms and count of generated Long numbers
Can be quickly
guessedConstants
Can be quickly
guessed
Entropy ≈ 10 bit + 14 bit + log2(# of generated)
time PRNG init. time Count of generated Long numbers
Session id generation logic is in makeNewSession() method of winstone.WinstoneRequest class.
JSESSIONID.1153584c=254a8552370933b36b322c1d35fd4586
Receive one
cookie
Recover
PRNG state
Periodically (once a sec.)
receive cookie and
synchronize PRNG.
If we need to generate
more than one Long
number to sync PRNG →
somebody else received
cookie! Remember PRNG
state and time interval.
Brute exact
time in ms
from time
interval
Guess
Victim’s IP
HTTP
header: Date
Get server
uptime
WinstoneSessionCatcher.py WinstoneSessionHijacker.py
Recover
victim’s cookie
Session hijacking attack at a glance
PRNG millis estimate
×TCP timestamp is 32 bit value in TCP options and contains
value of the timestamp clock
×TCP timestamp is used to adjust RTO (retransmission
timeout) interval
×Used by PAWS (Protection Against Wrapping Sequence)
mechanism (RFC 1323)
×Enabled by default on most Linux distributives!
×Timestamp clock is initialized and then get incremented with
fixed frequency
× On Ubuntu 12.04 LTS we used for tests, timestamp clock was
initialized by -300 and clock frequency was 1000 Hz
×Knowing this we can compute host uptime from TCP
timestamp value
×Nmap can determine host uptime (nmap -O), we need to
subtract initial value from nmap’s result
PRNG millis estimate
×Jenkins prior to 1.534 (uses Winstone as container), later versions migrated to
Jetty
×Hudson prior to 3.0.0 (uses Winstone as container), later versions migrated to
Jetty
×Winstone 0.9.10
Vulnerable software
CVE-2014-2060 (SECURITY-106)
Demo #2: Session Hijacking in Jenkins
Request Cookie
Brute PRNG’s initial seed
Request Cookie and
synchronize PRNG
(in a loop)
Infer user’s cookie value
When user logs in
Try to hijack user’s
session
Given:
Attacker have no valid
credentials.
java.security.SecureRandom class
× Extends java.util.Random class
× Provides a cryptographically strong random number
generator (CSRNG)
× Uses a deterministic algorithm to produce a pseudo-
random sequence from a true random seed
SecureRandom logic is not obvious
Depends on:
× Operating System used
× -Djava.security.egd, securerandom.source parameters
× Seeding mechanism
SecureRandom implementation
× sun.security.provider.Sun (default JCE provider)
uses following implementations of
SecureRandom:
× sun.security.provider.NativePRNG
× sun.security.provider.SecureRandom
NativePRNG algorithm
× Default algorithm for Linux/Solaris OS’es
× Reads random bytes from /dev/random and
/dev/urandom
× There is SHA1PRNG instance that works in parallel
× Output from SHA1PRNG is XORed with bytes from
/dev/random and /dev/urandom
SHA1PRNG algorithm
State0 = SHA1(SEED)
Output i = SHA1(Statei-1)
Statei = Statei-1 + Outputi + 1 mod 2160
× Default algorithm for Windows OS
Implicit SHA1PRNG seeding
× sun.security.provider.Sun (default JCE provider) uses
following seeding algorithms:
× sun.security.provider.NativeSeedGenerator
× sun.security.provider.URLSeedGenerator
× sun.security.provider.ThreadedSeedGenerator
× State0= SHA1(getSystemEntropy() || seed)
NativeSeedGenerator logic
× Is used when securerandom.source equals to
value file:/dev/urandom or file:/dev/random
× Reads bytes from /dev/random (Linux/Solaris)
× CryptoAPI CSPRNG (Windows)
URLSeedGenerator logic
× Is used when securerandom.source specified as
some other file not file:/dev/urandom or
file:/dev/random
× Simply reads bytes from that source
ThreadedSeedGenerator logic
× Is used when securerandom.source parameter
not specified
× Multiple threads are used: one thread
increments counter, “bogus” threads make
noise
Explicit SHA1PRNG seeding
× Constructor SecureRandom(byte[] seed)
× State0= SHA1(seed)
× setSeed(long seed), setSeed(byte[] seed) methods
× Statei = Statei XOR seed
Why we need to change securerandom.source on Linux?
× Simply because reading from /dev/random
hangs when there is no enough entropy!
SecureRandom risky usage
× Windows and Linux/Solaris (with modified
securerandom.source parameter)
× Low quality seed is passed to constructor
× Low quality seed is passed to setSeed() before
nextBytes() call
Tiny Java Web Server
http://sourceforge.net/projects/tjws/, ~50 575 downloads, ~5 864 downloads last year
× Small and fast servlet container (servlets, JSP), could run on Android
and Blackberry platforms
× Acme.Serve.Serve class
31536000 seconds in year ~ 25 bits
TJWSSun May 11 02:02:20 MSK 2014
Oracle WebLogic Server
× WebLogic – Java EE application server
× WTC – WebLogic Tuxedo Connector
× Tuxedo – application server for applications written in
C, C++, COBOL languages
× LLE – Link Level Encryption protocol (40 bit, 128 bit
encryption, RC4 is used)
× Logic is inside weblogic.wtc.jatmi.tplle class
Oracle WebLogic Server
DH Private Key
DH Public Key
~ 10 bits
~ 10 bits
~ 1 bit
2nd party’s public key
Two keys for encryption
Shared secret
JacORB
http://www.jacorb.org/
× Free implementation of CORBA standard in Java
× Is used to build distributed application which
components run on different platforms (OS, etc.)
× JBoss AS and JOnAS include JacORB
× Supports IIOP over SSL/TLS (SSLIOP)
× Latest release is 3.4 (15 Jan 2014)
JacORB’s SSLIOP implementation
× org.jacorb.security.ssl.sun_jsse.JSRandomImpl class
× org.jacorb.security.ssl.sun_jsse.SSLSocketFactory class
Randomness in SSL/TLS
1. Client Hello
2. Server Hello
3. Certificate
4. Certificate Request
Random A (32 bytes)
536910a4 ec292466818399123………
4 bytes 28 bytes
Random B (32 bytes)
536910a4 4518c4a8e309f2c1c………
4 bytes 28 bytes
5. Server Hello Done
6. Certificate
7. Client Key Exchange
8. Certificate Verify
9. Change Cipher Spec
11. Change Cipher Spec
12. Finished
10. Finished
Cipher suites:
TLS_RSA_WITH_AES_128_CBC_SHA
Cipher suite:
TLS_RSA_WITH_AES_128_CBC_SHA
Pre-master key (48 bytes)
4C82F3B241F2AC85A93CA3AE……..
RSA-OAEP encrypted pre-master (128 bytes)
07c3e1be783da1b217392040c58e0da.…
0301
2 bytes 46 bytes
Master key computation
× Inspect com.sun.crypto.provider.TlsMasterSecretGenerator and
com.sun.crypto.provider.TlsPrfGenerator classes if you want all
details
× SSL v3 master key (48 bytes)
MD5(Pre-master || SHA1(‘A’|| Pre-master||Random A || Random B))
MD5(Pre-master || SHA1(‘BB’|| Pre-master||Random A || Random B))
MD5(Pre-master || SHA1(‘CCC’|| Pre-master||Random A || Random B))
× TLS master key (48 bytes)
F(Pre-master, Random A, Random B), where F – some tricky function
How JSSE uses SecureRandom passed
× Logic inside sun.security.ssl.RSAClientKeyExchange
× Java 6 or less
Only Random A, Random B
× Java 7 or above
Random A, Random B, Pre-master generation
Demo #3: TLS/SSL decryption in JacORB
Extract Session-id
Random A, Random B
from traffic dump
Guess Pre-master key
(due to poor PRNG
initialization)
Compute master key
(produce master log file)
Decrypt TLS/SSL
Given:
Attacker is capable to
intercept all traffic
(including ssl handshake)
GNU Classpath
×Is an implementation of the standard class library for Java 5
×Latest release - GNU Classpath 0.99 (16 March 2012)
×Is used by free JVMs (such as JamVM, Kaffe, CACAO, etc.)
GNU Classpath + JamVM
SecureRandom in GNU Classpath
State0 = SEED (is 32 bytes)
Output i = SHA512(Statei-1)
Statei = Statei-1 || Output i
Seeding logic is inside class
gnu.java.security.jce.prng.SecureRandomAdapter
SecureRandom in GnuClasspath
Tries to seed PRNG from following sources in sequence until succeeds:
1. From a file specified by parameter securerandom.source in
classpath.security file (located in /usr/local/classpath/lib/security/)
2. From a file specified by command line parameter java.security.egd
3. Using generateSeed method in java.security.VMSecureRandom class
VMSecureRandom generateSeed()
×Create 8 spinners (threads)
×Seed bytes are generated as follows
VMSecureRandom generateSeed()
×What is Thread.yeild()?
public static void yield()
A hint to the scheduler that the current thread is willing to yield its current use of a
processor. The scheduler is free to ignore this hint. Yield is a heuristic attempt to improve
relative progression between threads that would otherwise over-utilise a CPU. Its use should
be combined with detailed profiling and benchmarking to ensure that it actually has the
desired effect.
It is rarely appropriate to use this method. It may be useful for debugging or testing
purposes, where it may help to reproduce bugs due to race conditions. It may also be useful
when designing concurrency control constructs such as the ones in
the java.util.concurrent.locks package.
VMSecureRandom generateSeed()
×Is seed random enough? - one cpu/one core machine
VMSecureRandom generateSeed()
×Is seed random enough? - one cpu/one core machine
VMSecureRandom generateSeed()
×Two CPUs
VMSecureRandom generateSeed()
×Two CPUs
VMSecureRandom generateSeed()
×Two CPUs – launch some task that utilizes CPU
VMSecureRandom generateSeed()
×Two CPUs – launch some task that utilizes CPU
Jetty servlet container is open source project (part of the Eclipse
Foundation).
http://www.eclipse.org/jetty/
In the past Jetty was vulnerable to Session Hijacking (CVE-2007-5614)
http://www.securityfocus.com/bid/26695/info
Now Jetty uses SecureRandom for:
× SSL support
× Session id generation
Jetty and SecureRandom
× Component – jetty-server
× Class – org.eclipse.jetty.server.ssl. SslSocketConnector
protected SSLContext createSSLContext() throws Exception
{
KeyManager[] keyManagers = getKeyManagers();
TrustManager[] trustManagers = getTrustManagers();
SecureRandom secureRandom =
_secureRandomAlgorithm==null?null:SecureRandom.getInstance(_secureRandomAlgorithm);
SSLContext context = _provider==null?SSLContext.getInstance(_protocol):SSLContext.getInstance(_protocol,
_provider);
context.init(keyManagers, trustManagers, secureRandom);
return context;
}
SSLContext initialization in Jetty
Session id generation in Jetty
× Component – jetty-server
× Class – org.eclipse.jetty.server.session.AbstractSessionIdManager
× Initialization – public void initRandom ()
_random=new SecureRandom();
_random.setSeed(_random.nextLong()^System.currentTimeMillis()^hashCode()^Runtime.getRun
time().freeMemory());
× Session id generation – public String newSessionId(HttpServletRequest
request, long created)
long r0 = _random.nextLong(); long r1 = _random.nextLong();
if (r0<0) r0=-r0; if (r1<0) r1=-r1;
id=Long.toString(r0,36)+Long.toString(r1,36);
× Example – JSESSIONID=1s3v0f1dneqcv1at4retb2nk0u
Session id generation in Jetty
1. _random.nextLong() – SecureRandom implementation in GNU Classpath
× Try all possible combinations
× 16 bits of entropy (SecureRandom is seeded from spinning threads)
2. System.currentTimeMillis() – time since epoch in milliseconds
× Estimate using TCP timestamp technique
× 13 bits of entropy
3. Runtime.getRuntime().freeMemory() – free memory in bytes
× Estimate using machine with the same configuration
× 10 bits of entropy
4. hashCode() – address of object in JVM heap
× Estimate using known hashcode of another object (Jetty test.war)
× 12 bits of entropy
Session id generation in Jetty
For demo purpose we modified
AbstractSessionIdManager a little bit …
_random=new SecureRandom();
_random.setSeed(_random.nextLong());
Demo #4: Session Hijacking in Jetty
Request Cookie
Brute SecureRandom
PRNG’s initial seed and
recover state
Request Cookie and
synchronize
SecureRandom PRNG
(in a loop)
Infer user’s cookie value
When user logs in
Try to hijack user’s
session
Given:
Attacker have no valid
credentials.
Our recommendations for Java developers
1. DO NOT USE java.util.Random for security related
functionality!
2. Always use SecureRandom CSPRNG.
3. DO NOT INVENT your own CSPRNGs! ... Unless you're a
good cryptographer.
4. Ensure SecureRandom CSPRNG is properly seeded (seed
entropy is high enough).
5. Periodically add fresh entropy to SecureRandom CSPRNG
(via setSeed method).
You can find presentation and demo videos you
have seen and more interesting stuff in our blogs:
× http://0ang3el.blogspot.com/
× http://reply-to-all.blogspot.com/
That’s all. Have Questions?

More Related Content

What's hot

TensorFlow計算グラフ最適化処理
TensorFlow計算グラフ最適化処理TensorFlow計算グラフ最適化処理
TensorFlow計算グラフ最適化処理
Atsushi Nukariya
 
条件分岐とcmovとmaxps
条件分岐とcmovとmaxps条件分岐とcmovとmaxps
条件分岐とcmovとmaxpsMITSUNARI Shigeo
 
C++ マルチスレッド 入門
C++ マルチスレッド 入門C++ マルチスレッド 入門
C++ マルチスレッド 入門
京大 マイコンクラブ
 
実践イカパケット解析
実践イカパケット解析実践イカパケット解析
実践イカパケット解析
Yuki Mizuno
 
実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)
実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)
実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)
AtCoder Inc.
 
平面グラフと交通ネットワークのアルゴリズム
平面グラフと交通ネットワークのアルゴリズム平面グラフと交通ネットワークのアルゴリズム
平面グラフと交通ネットワークのアルゴリズム
Takuya Akiba
 
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
Takuya Akiba
 
ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14
Ryo Suzuki
 
More modern gpu
More modern gpuMore modern gpu
More modern gpu
Preferred Networks
 
マルチコアを用いた画像処理
マルチコアを用いた画像処理マルチコアを用いた画像処理
マルチコアを用いた画像処理
Norishige Fukushima
 
LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)
LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)
LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)Takeshi Yamamuro
 
Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」
Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」
Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」
Hiro H.
 
RSA暗号運用でやってはいけない n のこと #ssmjp
RSA暗号運用でやってはいけない n のこと #ssmjpRSA暗号運用でやってはいけない n のこと #ssmjp
RSA暗号運用でやってはいけない n のこと #ssmjp
sonickun
 
直交領域探索
直交領域探索直交領域探索
直交領域探索
okuraofvegetable
 
勉強か?趣味か?人生か?―プログラミングコンテストとは
勉強か?趣味か?人生か?―プログラミングコンテストとは勉強か?趣味か?人生か?―プログラミングコンテストとは
勉強か?趣味か?人生か?―プログラミングコンテストとはTakuya Akiba
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由kikairoya
 
目grep入門 +解説
目grep入門 +解説目grep入門 +解説
目grep入門 +解説
murachue
 
動的計画法を極める!
動的計画法を極める!動的計画法を極める!
ウェーブレット木の世界
ウェーブレット木の世界ウェーブレット木の世界
ウェーブレット木の世界
Preferred Networks
 

What's hot (20)

TensorFlow計算グラフ最適化処理
TensorFlow計算グラフ最適化処理TensorFlow計算グラフ最適化処理
TensorFlow計算グラフ最適化処理
 
条件分岐とcmovとmaxps
条件分岐とcmovとmaxps条件分岐とcmovとmaxps
条件分岐とcmovとmaxps
 
C++ マルチスレッド 入門
C++ マルチスレッド 入門C++ マルチスレッド 入門
C++ マルチスレッド 入門
 
実践イカパケット解析
実践イカパケット解析実践イカパケット解析
実践イカパケット解析
 
実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)
実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)
実践・最強最速のアルゴリズム勉強会 第一回 講義資料(ワークスアプリケーションズ & AtCoder)
 
平面グラフと交通ネットワークのアルゴリズム
平面グラフと交通ネットワークのアルゴリズム平面グラフと交通ネットワークのアルゴリズム
平面グラフと交通ネットワークのアルゴリズム
 
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
 
ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14ゲーム開発者のための C++11/C++14
ゲーム開発者のための C++11/C++14
 
More modern gpu
More modern gpuMore modern gpu
More modern gpu
 
マルチコアを用いた画像処理
マルチコアを用いた画像処理マルチコアを用いた画像処理
マルチコアを用いた画像処理
 
LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)
LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)
LLVMで遊ぶ(整数圧縮とか、x86向けの自動ベクトル化とか)
 
Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」
Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」
Boost.勉強会 #21 札幌「C++1zにstring_viewが導入されてうれしいので紹介します」
 
RSA暗号運用でやってはいけない n のこと #ssmjp
RSA暗号運用でやってはいけない n のこと #ssmjpRSA暗号運用でやってはいけない n のこと #ssmjp
RSA暗号運用でやってはいけない n のこと #ssmjp
 
直交領域探索
直交領域探索直交領域探索
直交領域探索
 
llvm入門
llvm入門llvm入門
llvm入門
 
勉強か?趣味か?人生か?―プログラミングコンテストとは
勉強か?趣味か?人生か?―プログラミングコンテストとは勉強か?趣味か?人生か?―プログラミングコンテストとは
勉強か?趣味か?人生か?―プログラミングコンテストとは
 
組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由組み込みでこそC++を使う10の理由
組み込みでこそC++を使う10の理由
 
目grep入門 +解説
目grep入門 +解説目grep入門 +解説
目grep入門 +解説
 
動的計画法を極める!
動的計画法を極める!動的計画法を極める!
動的計画法を極める!
 
ウェーブレット木の世界
ウェーブレット木の世界ウェーブレット木の世界
ウェーブレット木の世界
 

Similar to Cracking Pseudorandom Sequences Generators in Java Applications

Csw2016 wheeler barksdale-gruskovnjak-execute_mypacket
Csw2016 wheeler barksdale-gruskovnjak-execute_mypacketCsw2016 wheeler barksdale-gruskovnjak-execute_mypacket
Csw2016 wheeler barksdale-gruskovnjak-execute_mypacket
CanSecWest
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
Ji Hun Kim
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...Positive Hack Days
 
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
JAX London
 
Xdp and ebpf_maps
Xdp and ebpf_mapsXdp and ebpf_maps
Xdp and ebpf_maps
lcplcp1
 
Don't dump thread dumps
Don't dump thread dumpsDon't dump thread dumps
Don't dump thread dumps
Tier1app
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On RandomnessRanel Padon
 
Seq2Seq (encoder decoder) model
Seq2Seq (encoder decoder) modelSeq2Seq (encoder decoder) model
Seq2Seq (encoder decoder) model
佳蓉 倪
 
Esd module2
Esd module2Esd module2
Esd module2
SOURAV KUMAR
 
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander NasonovMultiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
eurobsdcon
 
"You shall not pass : anti-debug methodics"
"You shall not pass : anti-debug methodics""You shall not pass : anti-debug methodics"
"You shall not pass : anti-debug methodics"
ITCP Community
 
Seq2grid aaai 2021
Seq2grid aaai 2021Seq2grid aaai 2021
Seq2grid aaai 2021
segwangkim
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
José Paumard
 
Understanding the Disruptor
Understanding the DisruptorUnderstanding the Disruptor
Understanding the Disruptor
Trisha Gee
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Data Con LA
 
Hidden in Plain Sight: DUAL_EC_DRBG 'n stuff
Hidden in Plain Sight: DUAL_EC_DRBG 'n stuffHidden in Plain Sight: DUAL_EC_DRBG 'n stuff
Hidden in Plain Sight: DUAL_EC_DRBG 'n stuff
WhiskeyNeon
 
FreeBSD 2014 Flame Graphs
FreeBSD 2014 Flame GraphsFreeBSD 2014 Flame Graphs
FreeBSD 2014 Flame Graphs
Brendan Gregg
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive Platform
Martin Zapletal
 
MongoDB for Time Series Data Part 3: Sharding
MongoDB for Time Series Data Part 3: ShardingMongoDB for Time Series Data Part 3: Sharding
MongoDB for Time Series Data Part 3: ShardingMongoDB
 
Debug generic process
Debug generic processDebug generic process
Debug generic process
Vipin Varghese
 

Similar to Cracking Pseudorandom Sequences Generators in Java Applications (20)

Csw2016 wheeler barksdale-gruskovnjak-execute_mypacket
Csw2016 wheeler barksdale-gruskovnjak-execute_mypacketCsw2016 wheeler barksdale-gruskovnjak-execute_mypacket
Csw2016 wheeler barksdale-gruskovnjak-execute_mypacket
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
 
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
 
Xdp and ebpf_maps
Xdp and ebpf_mapsXdp and ebpf_maps
Xdp and ebpf_maps
 
Don't dump thread dumps
Don't dump thread dumpsDon't dump thread dumps
Don't dump thread dumps
 
Python Programming - IX. On Randomness
Python Programming - IX. On RandomnessPython Programming - IX. On Randomness
Python Programming - IX. On Randomness
 
Seq2Seq (encoder decoder) model
Seq2Seq (encoder decoder) modelSeq2Seq (encoder decoder) model
Seq2Seq (encoder decoder) model
 
Esd module2
Esd module2Esd module2
Esd module2
 
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander NasonovMultiplatform JIT Code Generator for NetBSD by Alexander Nasonov
Multiplatform JIT Code Generator for NetBSD by Alexander Nasonov
 
"You shall not pass : anti-debug methodics"
"You shall not pass : anti-debug methodics""You shall not pass : anti-debug methodics"
"You shall not pass : anti-debug methodics"
 
Seq2grid aaai 2021
Seq2grid aaai 2021Seq2grid aaai 2021
Seq2grid aaai 2021
 
Java Keeps Throttling Up!
Java Keeps Throttling Up!Java Keeps Throttling Up!
Java Keeps Throttling Up!
 
Understanding the Disruptor
Understanding the DisruptorUnderstanding the Disruptor
Understanding the Disruptor
 
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Data Provenance Support in...
 
Hidden in Plain Sight: DUAL_EC_DRBG 'n stuff
Hidden in Plain Sight: DUAL_EC_DRBG 'n stuffHidden in Plain Sight: DUAL_EC_DRBG 'n stuff
Hidden in Plain Sight: DUAL_EC_DRBG 'n stuff
 
FreeBSD 2014 Flame Graphs
FreeBSD 2014 Flame GraphsFreeBSD 2014 Flame Graphs
FreeBSD 2014 Flame Graphs
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive Platform
 
MongoDB for Time Series Data Part 3: Sharding
MongoDB for Time Series Data Part 3: ShardingMongoDB for Time Series Data Part 3: Sharding
MongoDB for Time Series Data Part 3: Sharding
 
Debug generic process
Debug generic processDebug generic process
Debug generic process
 

More from Positive Hack Days

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Positive Hack Days
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
Positive Hack Days
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
Positive Hack Days
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
Positive Hack Days
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
Positive Hack Days
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
Positive Hack Days
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Positive Hack Days
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
Positive Hack Days
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
Positive Hack Days
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
Positive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
Positive Hack Days
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
Positive Hack Days
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
Positive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Positive Hack Days
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
Positive Hack Days
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
Positive Hack Days
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
Positive Hack Days
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
Positive Hack Days
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
Positive Hack Days
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
Positive Hack Days
 

More from Positive Hack Days (20)

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
 

Recently uploaded

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 

Cracking Pseudorandom Sequences Generators in Java Applications

  • 2. Why is this important? • Even useless for crypto often used for other “random” sequences: • Session ID • Account passwords • CAPTCHA • etc. • In poor applications can be used for cryptographic keys generation
  • 3. Why Java? • I am Java programmer  • Used in many applications • Easy to analyze (~decompile) • Thought to be secure programming language
  • 5. TOO simple about PRNG security When problems with PRNG security arises: 1. PRNG state is small, we can just brute force all combinations. 2. We can make some assumptions about PRNG state by examining output from PRNG. So we can reduce brute force space. 3. PRNG is poorly seeded and having output from PRNG we can easily brute force its state.
  • 6. Linear congruential generator (In a nutshell) “Statei” – internal statei: Statei+1 = Statei × A + Ci+1: Case 1: “Modular” (take from bottom) Si+1 Si+1= Statei+1 mod limit Si+1 Si+1= (Statei+1 × limit) >> k k bit Case 2: “Multiplicative” (take from top) java.util.Random: N = 48 A = 0x5deece66dL = 25 214 903 917 C = 11 N bit “Seed” == State0
  • 7. java.util.Random’s nextInt() 32 bit 16 bit {state0} S0 {state1} S1 {statei} … {staten} Sn 16 S0 exhaustive search For each state of this form we check if it returns our sequence – this takes less than second
  • 8. java.util.Random’s nextLong() 32 bit 16 bit {state0, state1} S0 {state2, state3} S1 {statei, statei+1} … {state2n, state2n+1} Sn 16 S0 exhaustive search For each state of this form we check if it returns our sequence – this takes less than second 32 bit 16 bit 16 bit S0 low32S0 high32
  • 9. java.util.Random’s nextInt(limit), limit is even H ~ 31 bit L ~ 17 bit {state0} S0 {state1} S1 {statei} … {staten} Sn 17 S0 S0 % 2P 1) search for L p + 17 bit p bit known L S0 = H % limit 2) search for H = S0 + J*limit ~ 31 bit p: limit = n×2P SubLCG, generates Si % 2P Search for L (1) and then search for H (2) take less than 2 seconds
  • 10. L1 java.util.Random’s nextInt(limit), limit is 2P H0 ~ 31 bit L0 ~ 17 bit {state0} S0 {state1} S1 {statei} … {staten} Sn 17 S0 ~234,55 H1 S1 Hn Ln Sn p bit
  • 11. java.util.Random’s nextInt(limit), limit is 2P We search state in the form X = S0 × 248 - p + t mod 248 We have sequence S0 S1 S2 … Sn Iterate through all t values (248 - p ) Does PRNG.forceSeed(X) produces S1 S2 … Sn ? Simple Brute Force:
  • 12. java.util.Random’s nextInt(limit), limit is 2P limit = 1024 = 210 x1 x2 x2 = x1 mod limit x2 = x1 + 1 mod limit 213-p < c < 214-p ~ 2 13.44644-p
  • 13. java.util.Random’s nextInt(limit), limit is 2P × We can skip (limit -1) × c values that do not produce S1 × Complexity is O(2 48 - 2·p) (~ 2 36 for limit = 64) instead O(2 48 - 1·p) (~ 2 42 for limit = 64)
  • 14. L1 java.util.Random’s nextInt(limit), limit is odd H0 ~ 31 bit L0 ~ 17 bit {state0} S0 {state1} S1 {statei} … {staten} Sn 17 S0 H1 Hn Ln S1 Sn
  • 15. java.util.Random’s nextInt(limit), limit is odd We search state in form X = (217 × high) + low mod 248 We search high in form high = S0 + j × limit mod 231 Iterate through all high values with step limit (i.e. high += limit) Iterate through all low values with step 1 (i.e. low += 1) Does PRNG.forceSeed(X) produces S1 S2 … Sn ? We have sequence S0 S1 S2 …Sn Simple Brute Force:
  • 16. java.util.Random’s nextInt(limit), limit is odd limit = 73 d = 15 [d depends on limit] 217/d=8738 x2 = x1 mod limit x2 = x1 – 1 mod limit x2 = x1 – p mod limit x2 = x1 – (p + 1) mod limit x2 x1 where p = 231 mod limit p = 16 period = 744
  • 17. java.util.Random’s nextInt(limit), limit is odd d = min i : (0x5deece66d × i) >> 17 = limit – 1 mod limit // This is table width period = 231 / ( (0x5deece66d × d) >> 17 ) // Decrease by p or p+1 happens periodically
  • 18. 19 19 3 2 2 2 2 1 1 1 java.util.Random’s nextInt(limit), limit is odd Decrease by p=16 63 63 63 46 46 46 46 45 45 45 Decrease by p+1=17 ……….... ………....30 29 29 29 29 28 28 ..….... Decrease by 1 Stay the same 217 / d = 8738 × For each high we pre-compute low values where decrease by p or p+1 happens There are 217 / (d × period) such low values! × We skip low values that do not produce S1 In a column we have to check 217 / (d × limit) low values, not all 217 / d × Complexity is O(248 / period) × Instead O(248 / limit) better if period > limit
  • 19. java.util.Random seeding ×In JDK ×System.nanoTime() – machine uptime in nanoseconds (10-9) ×In GNU Classpath ×System.currentTimeMillis() – time in milliseconds (10-3) since epoch
  • 20. Tool: javacg • Multi-threaded java.util.Random cracker • Written in C++11 • Can be built for Linux/Unix and Windows (tested in MSVS2013 and GCC 4.8.2) • Available on github: https://github.com/votadlos/JavaCG.git • Open source, absolutely free to use and modify 
  • 21. Tool: javacg, numbers generation • javacg -g [40] -l 88 [-s 22..2], - generate 40 (20 by default) numbers modulo 88 with initial seed 22..2 (smth made of time by default). • If -l 0 specified will generate as .nextInt() method • If -l is omitted will work as .nextLong()
  • 22. Tool: javacg, passwords generation • Generate passwords: javacg -g [40] [-b 41] -l 88 -p [18] [-s 22..2] [-a a.txt], - generate 40 passwords with length 18 (15 by default) using alphabet a.txt (88 different simbols by default), initial seed – 22..2. • If -b 41 specified – wind generator backward and generate 41 passwords before specified seed 22..2.
  • 23. Tool: javacg, crack options • Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo 88 and return internal state after the last number from input. • If min internal state 22..2 or max 44..4 or both are known they can be specified. In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth strategy)/-ds (depth strategy) options.
  • 24. Tool: javacg, -ds-bs ‘advanced’ mode • Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo 88 and return internal state after the last number from input. • If min internal state 22..2 or max 44..4 or both are known they can be specified. In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth strategy)/-ds (depth strategy) options.
  • 25. Tool: javacg, -ds-bs ‘advanced’ mode • Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo 88 and return internal state after the last number from input. • If min internal state 22..2 or max 44..4 or both are known they can be specified. In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth strategy)/-ds (depth strategy) options.
  • 26. Tool: javacg, crack options (-sin, -sax) • Crack: javacg -n [20] -l 88 [-sin 22..2] [-sax 44..4] [-p], - take 20 numbers modulo 88 and return internal state after the last number from input. • If min internal state 22..2 or max 44..4 or both are known they can be specified. In case of odd modulo it’s better to switch to ‘advanced’ brute with -bs (breadth strategy)/-ds (depth strategy) options.
  • 27. Tool: javacg, crack options (-l 0, -l -1) • –l 0 perform .nextInt() case • –l -1 (or no –l specified) perform .nextLong() case.
  • 28. Tool: javacg, crack options (-l 0, -l -1) • –l 0 perform .nextInt() case • –l -1 (or no –l specified) perform .nextLong() case.
  • 29. Tool: javacg, crack options (-l 0, -l -1) • –l 0 perform .nextInt() case • –l -1 (or no –l specified) perform .nextLong() case.
  • 30. Tool: javacg, crack option -st • Initial seed is milliseconds since epoch (GNU Class Path)
  • 31. Tool: javacg, crack option –upt [–su] • Initial seed is host uptime in nanoseconds (Random’s default constructor) • –upt option takes uptime guess in milliseconds, combines diapason in nanoseconds (as it’s in –sin and –sax options) and simple bruteforse it. • –su – optional maximum seedUniquifier increment, 1000 by default.
  • 32. Tool: javacg, performance options • -t 212 – perform brute with 212 threads (C++11 native threads are used). Default – 128. • -c 543534 – each thread will take 543534 states to check (‘cycles per thread’). Default – 9999. • - ms 12 – will build search matrix with 12 rows. Deault – half of length of input sequence. • -norm. During brute forcing we start from the max state (‘from the top’), if it’s known that sought state is in the middle - use -norm option. S0 S1 S2 S3 S4 S5 S6 S7 S0 S1 S2 S3 S4 S1 S2 S3 S4 S5 S2 S3 S4 S5 S6 S3 S4 S5 S6 S7 Input sequence Search matrix
  • 33. Tool: javacg, threads S0 S1 S2 S3 S4 S1 S2 S3 S4 S5 S2 S3 S4 S5 S6 S3 S4 S5 S6 S7 Generator internal state space MAX MIN Threadsforsearch matrixrows Threads for internal states -t - total number of threads
  • 34. Tool: javacg, threads with -norm opt. S0 S1 S2 S3 S4 S1 S2 S3 S4 S5 S2 S3 S4 S5 S6 S3 S4 S5 S6 S7 Generator internal state space MAX MIN Threadsforsearch matrixrows Threads for internal states -t - total number of threads Suppose ‘normal’ distribution
  • 38. Mass Password Generator http://sourceforge.net/project/javapwordgen/ ~3 825 downloads ~ 12 downloads/last year
  • 39. Mass Password Generator http://sourceforge.net/project/javapwordgen/ ~3 825 downloads ~ 12 downloads/last year
  • 46. user l33t Hax0r IDM generates different ‘random’ local admin passwords and sets them over all managed endpoints IDM Web-interface “Show me password for workstation” u-%=X_}6~&Eq+4n{gO m;f9qHU){+6Y[+j$R8 [D7E?Og]Gz>nL5eVRD df=m+]6l0pFSFbXT_= Demo #1: “IdM” Given: Red password Alphabet Number of servers Find: [All] green passwords Take known df=m+]6l0pFSFbXT_= Brute internal state (seed) Wind generator forward Wind generator backward Generate possible passwords Brute passwords, using generated passwords as dictionary
  • 47. ×Jenkins – is open source continuous integration (CI) server, CloudBees makes commercial support for Jenkins ×Hudson – is open source continuous integration (CI) server under Eclipse Foundation ×Winstone – is small and fast servlet container (Servlet 2.5) Other apps with java.util.Random inside
  • 48. Session Id generation in Jenkins (Winstone) Winstone_ Client IP Server Port_ _ Gen. time in ms PRNG.nextLong()MD5: PRNG initialized by time in ms at startup: we need time in ms and count of generated Long numbers Can be quickly guessedConstants Can be quickly guessed Entropy ≈ 10 bit + 14 bit + log2(# of generated) time PRNG init. time Count of generated Long numbers Session id generation logic is in makeNewSession() method of winstone.WinstoneRequest class. JSESSIONID.1153584c=254a8552370933b36b322c1d35fd4586
  • 49. Receive one cookie Recover PRNG state Periodically (once a sec.) receive cookie and synchronize PRNG. If we need to generate more than one Long number to sync PRNG → somebody else received cookie! Remember PRNG state and time interval. Brute exact time in ms from time interval Guess Victim’s IP HTTP header: Date Get server uptime WinstoneSessionCatcher.py WinstoneSessionHijacker.py Recover victim’s cookie Session hijacking attack at a glance
  • 50. PRNG millis estimate ×TCP timestamp is 32 bit value in TCP options and contains value of the timestamp clock ×TCP timestamp is used to adjust RTO (retransmission timeout) interval ×Used by PAWS (Protection Against Wrapping Sequence) mechanism (RFC 1323) ×Enabled by default on most Linux distributives!
  • 51. ×Timestamp clock is initialized and then get incremented with fixed frequency × On Ubuntu 12.04 LTS we used for tests, timestamp clock was initialized by -300 and clock frequency was 1000 Hz ×Knowing this we can compute host uptime from TCP timestamp value ×Nmap can determine host uptime (nmap -O), we need to subtract initial value from nmap’s result PRNG millis estimate
  • 52. ×Jenkins prior to 1.534 (uses Winstone as container), later versions migrated to Jetty ×Hudson prior to 3.0.0 (uses Winstone as container), later versions migrated to Jetty ×Winstone 0.9.10 Vulnerable software CVE-2014-2060 (SECURITY-106)
  • 53. Demo #2: Session Hijacking in Jenkins Request Cookie Brute PRNG’s initial seed Request Cookie and synchronize PRNG (in a loop) Infer user’s cookie value When user logs in Try to hijack user’s session Given: Attacker have no valid credentials.
  • 54. java.security.SecureRandom class × Extends java.util.Random class × Provides a cryptographically strong random number generator (CSRNG) × Uses a deterministic algorithm to produce a pseudo- random sequence from a true random seed
  • 55. SecureRandom logic is not obvious Depends on: × Operating System used × -Djava.security.egd, securerandom.source parameters × Seeding mechanism
  • 56. SecureRandom implementation × sun.security.provider.Sun (default JCE provider) uses following implementations of SecureRandom: × sun.security.provider.NativePRNG × sun.security.provider.SecureRandom
  • 57. NativePRNG algorithm × Default algorithm for Linux/Solaris OS’es × Reads random bytes from /dev/random and /dev/urandom × There is SHA1PRNG instance that works in parallel × Output from SHA1PRNG is XORed with bytes from /dev/random and /dev/urandom
  • 58. SHA1PRNG algorithm State0 = SHA1(SEED) Output i = SHA1(Statei-1) Statei = Statei-1 + Outputi + 1 mod 2160 × Default algorithm for Windows OS
  • 59. Implicit SHA1PRNG seeding × sun.security.provider.Sun (default JCE provider) uses following seeding algorithms: × sun.security.provider.NativeSeedGenerator × sun.security.provider.URLSeedGenerator × sun.security.provider.ThreadedSeedGenerator × State0= SHA1(getSystemEntropy() || seed)
  • 60. NativeSeedGenerator logic × Is used when securerandom.source equals to value file:/dev/urandom or file:/dev/random × Reads bytes from /dev/random (Linux/Solaris) × CryptoAPI CSPRNG (Windows)
  • 61. URLSeedGenerator logic × Is used when securerandom.source specified as some other file not file:/dev/urandom or file:/dev/random × Simply reads bytes from that source
  • 62. ThreadedSeedGenerator logic × Is used when securerandom.source parameter not specified × Multiple threads are used: one thread increments counter, “bogus” threads make noise
  • 63. Explicit SHA1PRNG seeding × Constructor SecureRandom(byte[] seed) × State0= SHA1(seed) × setSeed(long seed), setSeed(byte[] seed) methods × Statei = Statei XOR seed
  • 64. Why we need to change securerandom.source on Linux? × Simply because reading from /dev/random hangs when there is no enough entropy!
  • 65. SecureRandom risky usage × Windows and Linux/Solaris (with modified securerandom.source parameter) × Low quality seed is passed to constructor × Low quality seed is passed to setSeed() before nextBytes() call
  • 66. Tiny Java Web Server http://sourceforge.net/projects/tjws/, ~50 575 downloads, ~5 864 downloads last year × Small and fast servlet container (servlets, JSP), could run on Android and Blackberry platforms × Acme.Serve.Serve class 31536000 seconds in year ~ 25 bits TJWSSun May 11 02:02:20 MSK 2014
  • 67. Oracle WebLogic Server × WebLogic – Java EE application server × WTC – WebLogic Tuxedo Connector × Tuxedo – application server for applications written in C, C++, COBOL languages × LLE – Link Level Encryption protocol (40 bit, 128 bit encryption, RC4 is used) × Logic is inside weblogic.wtc.jatmi.tplle class
  • 68. Oracle WebLogic Server DH Private Key DH Public Key ~ 10 bits ~ 10 bits ~ 1 bit 2nd party’s public key Two keys for encryption Shared secret
  • 69. JacORB http://www.jacorb.org/ × Free implementation of CORBA standard in Java × Is used to build distributed application which components run on different platforms (OS, etc.) × JBoss AS and JOnAS include JacORB × Supports IIOP over SSL/TLS (SSLIOP) × Latest release is 3.4 (15 Jan 2014)
  • 70. JacORB’s SSLIOP implementation × org.jacorb.security.ssl.sun_jsse.JSRandomImpl class × org.jacorb.security.ssl.sun_jsse.SSLSocketFactory class
  • 71. Randomness in SSL/TLS 1. Client Hello 2. Server Hello 3. Certificate 4. Certificate Request Random A (32 bytes) 536910a4 ec292466818399123……… 4 bytes 28 bytes Random B (32 bytes) 536910a4 4518c4a8e309f2c1c……… 4 bytes 28 bytes 5. Server Hello Done 6. Certificate 7. Client Key Exchange 8. Certificate Verify 9. Change Cipher Spec 11. Change Cipher Spec 12. Finished 10. Finished Cipher suites: TLS_RSA_WITH_AES_128_CBC_SHA Cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA Pre-master key (48 bytes) 4C82F3B241F2AC85A93CA3AE…….. RSA-OAEP encrypted pre-master (128 bytes) 07c3e1be783da1b217392040c58e0da.… 0301 2 bytes 46 bytes
  • 72. Master key computation × Inspect com.sun.crypto.provider.TlsMasterSecretGenerator and com.sun.crypto.provider.TlsPrfGenerator classes if you want all details × SSL v3 master key (48 bytes) MD5(Pre-master || SHA1(‘A’|| Pre-master||Random A || Random B)) MD5(Pre-master || SHA1(‘BB’|| Pre-master||Random A || Random B)) MD5(Pre-master || SHA1(‘CCC’|| Pre-master||Random A || Random B)) × TLS master key (48 bytes) F(Pre-master, Random A, Random B), where F – some tricky function
  • 73. How JSSE uses SecureRandom passed × Logic inside sun.security.ssl.RSAClientKeyExchange × Java 6 or less Only Random A, Random B × Java 7 or above Random A, Random B, Pre-master generation
  • 74. Demo #3: TLS/SSL decryption in JacORB Extract Session-id Random A, Random B from traffic dump Guess Pre-master key (due to poor PRNG initialization) Compute master key (produce master log file) Decrypt TLS/SSL Given: Attacker is capable to intercept all traffic (including ssl handshake)
  • 75. GNU Classpath ×Is an implementation of the standard class library for Java 5 ×Latest release - GNU Classpath 0.99 (16 March 2012) ×Is used by free JVMs (such as JamVM, Kaffe, CACAO, etc.)
  • 77. SecureRandom in GNU Classpath State0 = SEED (is 32 bytes) Output i = SHA512(Statei-1) Statei = Statei-1 || Output i Seeding logic is inside class gnu.java.security.jce.prng.SecureRandomAdapter
  • 78. SecureRandom in GnuClasspath Tries to seed PRNG from following sources in sequence until succeeds: 1. From a file specified by parameter securerandom.source in classpath.security file (located in /usr/local/classpath/lib/security/) 2. From a file specified by command line parameter java.security.egd 3. Using generateSeed method in java.security.VMSecureRandom class
  • 79. VMSecureRandom generateSeed() ×Create 8 spinners (threads) ×Seed bytes are generated as follows
  • 80. VMSecureRandom generateSeed() ×What is Thread.yeild()? public static void yield() A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint. Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect. It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.
  • 81. VMSecureRandom generateSeed() ×Is seed random enough? - one cpu/one core machine
  • 82. VMSecureRandom generateSeed() ×Is seed random enough? - one cpu/one core machine
  • 85. VMSecureRandom generateSeed() ×Two CPUs – launch some task that utilizes CPU
  • 86. VMSecureRandom generateSeed() ×Two CPUs – launch some task that utilizes CPU
  • 87. Jetty servlet container is open source project (part of the Eclipse Foundation). http://www.eclipse.org/jetty/ In the past Jetty was vulnerable to Session Hijacking (CVE-2007-5614) http://www.securityfocus.com/bid/26695/info Now Jetty uses SecureRandom for: × SSL support × Session id generation Jetty and SecureRandom
  • 88. × Component – jetty-server × Class – org.eclipse.jetty.server.ssl. SslSocketConnector protected SSLContext createSSLContext() throws Exception { KeyManager[] keyManagers = getKeyManagers(); TrustManager[] trustManagers = getTrustManagers(); SecureRandom secureRandom = _secureRandomAlgorithm==null?null:SecureRandom.getInstance(_secureRandomAlgorithm); SSLContext context = _provider==null?SSLContext.getInstance(_protocol):SSLContext.getInstance(_protocol, _provider); context.init(keyManagers, trustManagers, secureRandom); return context; } SSLContext initialization in Jetty
  • 89. Session id generation in Jetty × Component – jetty-server × Class – org.eclipse.jetty.server.session.AbstractSessionIdManager × Initialization – public void initRandom () _random=new SecureRandom(); _random.setSeed(_random.nextLong()^System.currentTimeMillis()^hashCode()^Runtime.getRun time().freeMemory()); × Session id generation – public String newSessionId(HttpServletRequest request, long created) long r0 = _random.nextLong(); long r1 = _random.nextLong(); if (r0<0) r0=-r0; if (r1<0) r1=-r1; id=Long.toString(r0,36)+Long.toString(r1,36); × Example – JSESSIONID=1s3v0f1dneqcv1at4retb2nk0u
  • 90. Session id generation in Jetty 1. _random.nextLong() – SecureRandom implementation in GNU Classpath × Try all possible combinations × 16 bits of entropy (SecureRandom is seeded from spinning threads) 2. System.currentTimeMillis() – time since epoch in milliseconds × Estimate using TCP timestamp technique × 13 bits of entropy 3. Runtime.getRuntime().freeMemory() – free memory in bytes × Estimate using machine with the same configuration × 10 bits of entropy 4. hashCode() – address of object in JVM heap × Estimate using known hashcode of another object (Jetty test.war) × 12 bits of entropy
  • 91. Session id generation in Jetty For demo purpose we modified AbstractSessionIdManager a little bit … _random=new SecureRandom(); _random.setSeed(_random.nextLong());
  • 92. Demo #4: Session Hijacking in Jetty Request Cookie Brute SecureRandom PRNG’s initial seed and recover state Request Cookie and synchronize SecureRandom PRNG (in a loop) Infer user’s cookie value When user logs in Try to hijack user’s session Given: Attacker have no valid credentials.
  • 93. Our recommendations for Java developers 1. DO NOT USE java.util.Random for security related functionality! 2. Always use SecureRandom CSPRNG. 3. DO NOT INVENT your own CSPRNGs! ... Unless you're a good cryptographer. 4. Ensure SecureRandom CSPRNG is properly seeded (seed entropy is high enough). 5. Periodically add fresh entropy to SecureRandom CSPRNG (via setSeed method).
  • 94. You can find presentation and demo videos you have seen and more interesting stuff in our blogs: × http://0ang3el.blogspot.com/ × http://reply-to-all.blogspot.com/
  • 95. That’s all. Have Questions?