CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/msf/core/auxiliary/crand.rb
Views: 1904
1
module Msf
2
3
###
4
#
5
# This module provides a complete port of the libc rand() and srand() functions.
6
# It is used by the NETGEAR WNR2000v5 auxiliary and exploit modules, but might
7
# be useful for any other module that needs to emulate C's random number generator.
8
#
9
# Author: Pedro Ribeiro ([email protected]) / Agile Information Security
10
#
11
###
12
module Auxiliary::CRand
13
14
attr_accessor :randtbl
15
attr_accessor :unsafe_state
16
17
####################
18
# ported from https://git.uclibc.org/uClibc/tree/libc/stdlib/random.c
19
# and https://git.uclibc.org/uClibc/tree/libc/stdlib/random_r.c
20
21
TYPE_3 = 3
22
BREAK_3 = 128
23
DEG_3 = 31
24
SEP_3 = 3
25
26
def initialize(info = {})
27
super
28
29
@randtbl =
30
[
31
# we omit TYPE_3 from here, not needed
32
-1726662223, 379960547, 1735697613, 1040273694, 1313901226,
33
1627687941, -179304937, -2073333483, 1780058412, -1989503057,
34
-615974602, 344556628, 939512070, -1249116260, 1507946756,
35
-812545463, 154635395, 1388815473, -1926676823, 525320961,
36
-1009028674, 968117788, -123449607, 1284210865, 435012392,
37
-2017506339, -911064859, -370259173, 1132637927, 1398500161,
38
-205601318,
39
]
40
41
@unsafe_state = {
42
"fptr" => SEP_3,
43
"rptr" => 0,
44
"state" => 0,
45
"rand_type" => TYPE_3,
46
"rand_deg" => DEG_3,
47
"rand_sep" => SEP_3,
48
"end_ptr" => DEG_3
49
}
50
end
51
52
# Emulate the behaviour of C's srand
53
def srandom_r (seed)
54
state = @randtbl
55
if seed == 0
56
seed = 1
57
end
58
state[0] = seed
59
60
dst = 0
61
word = seed
62
kc = DEG_3
63
for i in 1..(kc-1)
64
hi = word / 127773
65
lo = word % 127773
66
word = 16807 * lo - 2836 * hi
67
if (word < 0)
68
word += 2147483647
69
end
70
dst += 1
71
state[dst] = word
72
end
73
74
@unsafe_state['fptr'] = @unsafe_state['rand_sep']
75
@unsafe_state['rptr'] = 0
76
77
kc *= 10
78
kc -= 1
79
while (kc >= 0)
80
random_r
81
kc -= 1
82
end
83
end
84
85
# Emulate the behaviour of C's rand
86
def random_r
87
buf = @unsafe_state
88
state = buf['state']
89
90
fptr = buf['fptr']
91
rptr = buf['rptr']
92
end_ptr = buf['end_ptr']
93
val = @randtbl[fptr] += @randtbl[rptr]
94
95
result = (val >> 1) & 0x7fffffff
96
fptr += 1
97
if (fptr >= end_ptr)
98
fptr = state
99
rptr += 1
100
else
101
rptr += 1
102
if (rptr >= end_ptr)
103
rptr = state
104
end
105
end
106
buf['fptr'] = fptr
107
buf['rptr'] = rptr
108
109
result
110
end
111
112
end
113
end
114
115